@shopgate/pwa-common-commerce 7.8.2 → 7.9.0-beta.2
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.
- package/favorites/action-creators/index.js +49 -10
- package/favorites/actions/addFavorites.js +4 -2
- package/favorites/actions/fetchFavorites.js +2 -2
- package/favorites/actions/fetchFavoritesListsWithItems.js +6 -0
- package/favorites/actions/removeFavorites.js +4 -2
- package/favorites/actions/toggleFavorites.js +15 -5
- package/favorites/actions/updateFavorites.js +9 -0
- package/favorites/constants/Pipelines.js +1 -1
- package/favorites/constants/index.js +3 -2
- package/favorites/index.js +1 -1
- package/favorites/reducers/lists.js +2 -2
- package/favorites/reducers/products.js +13 -11
- package/favorites/selectors/index.js +12 -12
- package/favorites/streams/index.js +20 -16
- package/favorites/streams/spec.js +6 -4
- package/favorites/subscriptions/index.js +15 -23
- package/favorites/subscriptions/spec.js +22 -24
- package/package.json +3 -3
- package/product/action-creators/receiveProducts.js +4 -2
|
@@ -1,9 +1,18 @@
|
|
|
1
|
-
import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,CANCEL_REQUEST_SYNC_FAVORITES,ERROR_FETCH_FAVORITES,RECEIVE_FAVORITES,REQUEST_FAVORITES,REQUEST_ADD_FAVORITES,SUCCESS_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,SUCCESS_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,ERROR_FAVORITES,IDLE_SYNC_FAVORITES,REQUEST_FLUSH_FAVORITES_BUFFER,OPEN_FAVORITE_LIST_CHOOSER,CLOSE_FAVORITE_LIST_CHOOSER}from"../constants";/**
|
|
1
|
+
import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,CANCEL_REQUEST_SYNC_FAVORITES,ERROR_FETCH_FAVORITES,RECEIVE_FAVORITES,REQUEST_FAVORITES,REQUEST_ADD_FAVORITES,SUCCESS_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,SUCCESS_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,ERROR_FAVORITES,IDLE_SYNC_FAVORITES,REQUEST_FLUSH_FAVORITES_BUFFER,OPEN_FAVORITE_LIST_CHOOSER,CLOSE_FAVORITE_LIST_CHOOSER,REQUEST_UPDATE_FAVORITES,SUCCESS_UPDATE_FAVORITES,ERROR_UPDATE_FAVORITES,UPDATE_PRODUCT_IN_FAVORITES,OPEN_FAVORITE_COMMENT_DIALOG,CLOSE_FAVORITE_COMMENT_DIALOG}from"../constants";import{makeGetFavorites}from"../selectors";/**
|
|
2
2
|
* First action to add one product to favorites.
|
|
3
3
|
* @param {number} productId Id of the product to add.
|
|
4
4
|
* @param {string} listId List identifier.
|
|
5
|
+
* @param {number} quantity New favorites quantity to set
|
|
6
|
+
* @param {string} notes New favorites notes to set
|
|
5
7
|
* @returns {Object}
|
|
6
|
-
*/export var addProductToFavorites=function addProductToFavorites(productId,listId){return{type:ADD_PRODUCT_TO_FAVORITES,productId:productId,listId:listId};};/**
|
|
8
|
+
*/export var addProductToFavorites=function addProductToFavorites(productId,listId,quantity,notes){return{type:ADD_PRODUCT_TO_FAVORITES,productId:productId,listId:listId,quantity:quantity,notes:notes};};/**
|
|
9
|
+
* First action to update a product in favorites.
|
|
10
|
+
* @param {number} productId Id of the product to add.
|
|
11
|
+
* @param {string} listId List identifier.
|
|
12
|
+
* @param {number} quantity The quantity of the product.
|
|
13
|
+
* @param {string} notes Notes about the product.
|
|
14
|
+
* @returns {Object}
|
|
15
|
+
*/export var updateProductInFavorites=function updateProductInFavorites(productId,listId,quantity,notes){return{type:UPDATE_PRODUCT_IN_FAVORITES,productId:productId,listId:listId,notes:notes,quantity:quantity};};/**
|
|
7
16
|
* First action to remove one product to favorites.
|
|
8
17
|
* @param {number} productId Id of the product to remove.
|
|
9
18
|
* @param {boolean} withRelatives States, whether to remove all relative products or not.
|
|
@@ -23,8 +32,10 @@ import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,CANCEL_REQUEST_SYN
|
|
|
23
32
|
* Request add favorites action. This action just updates the redux store.
|
|
24
33
|
* @param {string} productId Product identifier.
|
|
25
34
|
* @param {string} listId List identifier.
|
|
35
|
+
* @param {number} quantity New favorites quantity to set
|
|
36
|
+
* @param {string} notes New favorites notes to set
|
|
26
37
|
* @returns {Object}
|
|
27
|
-
*/export var requestAddFavorites=function requestAddFavorites(productId,listId){return{type:REQUEST_ADD_FAVORITES,productId:productId,listId:listId};};/**
|
|
38
|
+
*/export var requestAddFavorites=function requestAddFavorites(productId,listId,quantity,notes){return{type:REQUEST_ADD_FAVORITES,productId:productId,listId:listId,quantity:quantity,notes:notes};};/**
|
|
28
39
|
* Action to be triggered upon successful addFavorites pipeline call.
|
|
29
40
|
* @param {string} productId Product identifier.
|
|
30
41
|
* @param {string} listId List identifier.
|
|
@@ -36,11 +47,29 @@ import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,CANCEL_REQUEST_SYN
|
|
|
36
47
|
* @param {string} listId List identifier.
|
|
37
48
|
* @returns {Object}
|
|
38
49
|
*/export var errorAddFavorites=function errorAddFavorites(productId,error,listId){return{type:ERROR_ADD_FAVORITES,productId:productId,listId:listId,error:error};};/**
|
|
50
|
+
* Request update favorites action. This action just updates the redux store.
|
|
51
|
+
* @param {string} productId Product identifier.
|
|
52
|
+
* @param {string} listId List identifier.
|
|
53
|
+
* @param {number} quantity The quantity of the product
|
|
54
|
+
* @param {string} notes Notes about the product
|
|
55
|
+
* @returns {Object}
|
|
56
|
+
*/export var requestUpdateFavorites=function requestUpdateFavorites(productId,listId,quantity,notes){return{type:REQUEST_UPDATE_FAVORITES,productId:productId,listId:listId,notes:notes,quantity:quantity};};/**
|
|
57
|
+
* Action to be triggered upon successful updateFavorites pipeline call.
|
|
58
|
+
* @param {string} productId Product identifier.
|
|
59
|
+
* @param {string} listId List identifier.
|
|
60
|
+
* @returns {Object}
|
|
61
|
+
*/export var successUpdateFavorites=function successUpdateFavorites(productId,listId){return{type:SUCCESS_UPDATE_FAVORITES,productId:productId,listId:listId};};/**
|
|
62
|
+
* Action to be triggered upon failed updateFavorites pipeline call.
|
|
63
|
+
* @param {string} productId Product identifier.
|
|
64
|
+
* @param {string} listId List identifier.
|
|
65
|
+
* @param {Error} error The error that occurred.
|
|
66
|
+
* @returns {Object}
|
|
67
|
+
*/export var errorUpdateFavorites=function errorUpdateFavorites(productId,listId,error){return{type:ERROR_UPDATE_FAVORITES,productId:productId,listId:listId,error:error};};/**
|
|
39
68
|
* Request remove favorites action. This action just updates the redux store.
|
|
40
69
|
* @param {string} productId Product identifier.
|
|
41
70
|
* @param {string} listId List identifier.
|
|
42
71
|
* @returns {Object}
|
|
43
|
-
*/export var requestRemoveFavorites=function requestRemoveFavorites(productId,listId){return{type:REQUEST_REMOVE_FAVORITES,productId:productId,listId:listId};};/**
|
|
72
|
+
*/export var requestRemoveFavorites=function requestRemoveFavorites(productId,listId){return function(dispatch,getState){var getFavorites=makeGetFavorites(function(){return listId;});var favorites=getFavorites(getState());var matchingFavorite=favorites.find(function(_ref){var itemProductId=_ref.productId;return itemProductId===productId;})||{};return dispatch({type:REQUEST_REMOVE_FAVORITES,productId:productId,listId:listId,quantity:matchingFavorite.quantity||1,notes:matchingFavorite.notes||''});};};/**
|
|
44
73
|
* Action to be triggered upon successful removeFavorites (deleteFavorites) pipeline call.
|
|
45
74
|
* @param {string} productId Product identifier.
|
|
46
75
|
* @param {number} takenListId List id
|
|
@@ -48,10 +77,12 @@ import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,CANCEL_REQUEST_SYN
|
|
|
48
77
|
*/export var successRemoveFavorites=function successRemoveFavorites(productId,takenListId){return{type:SUCCESS_REMOVE_FAVORITES,productId:productId,listId:takenListId};};/**
|
|
49
78
|
* Action to be triggered upon a failed removeFavorites (deleteFavorites) pipeline call.
|
|
50
79
|
* @param {string} productId Product identifier.
|
|
51
|
-
* @param {
|
|
80
|
+
* @param {string} takenListId List id
|
|
52
81
|
* @param {Error} error The error that occurred.
|
|
82
|
+
* @param {number} quantity Quantity of the favorite
|
|
83
|
+
* @param {string} notes Notes of the favorite
|
|
53
84
|
* @returns {Object}
|
|
54
|
-
*/export var errorRemoveFavorites=function errorRemoveFavorites(productId,takenListId,error){return{type:ERROR_REMOVE_FAVORITES,productId:productId,listId:takenListId,error:error};};/**
|
|
85
|
+
*/export var errorRemoveFavorites=function errorRemoveFavorites(productId,takenListId,error,quantity,notes){return{type:ERROR_REMOVE_FAVORITES,productId:productId,listId:takenListId,error:error,quantity:quantity,notes:notes};};/**
|
|
55
86
|
* Return the flush favorites buffer Now action object
|
|
56
87
|
* @param {string} listId The Id of the wishlist.
|
|
57
88
|
* @return {Object}
|
|
@@ -66,11 +97,11 @@ import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,CANCEL_REQUEST_SYN
|
|
|
66
97
|
* @returns {Object}
|
|
67
98
|
*/export var cancelRequestSyncFavorites=function cancelRequestSyncFavorites(){var count=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var listId=arguments.length>1?arguments[1]:undefined;return{type:CANCEL_REQUEST_SYNC_FAVORITES,count:count,listId:listId};};/**
|
|
68
99
|
* Receive favorites action.
|
|
69
|
-
* @param {Array}
|
|
70
|
-
* @param {number} requestTimestamp Time when request was
|
|
100
|
+
* @param {Array} items Wishlist items.
|
|
101
|
+
* @param {number} requestTimestamp Time when request was initiated (ms).
|
|
71
102
|
* @param {string} listId The Id of the wishlist.
|
|
72
103
|
* @returns {Object}
|
|
73
|
-
*/export var receiveFavorites=function receiveFavorites(
|
|
104
|
+
*/export var receiveFavorites=function receiveFavorites(items,requestTimestamp){var listId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;return{type:RECEIVE_FAVORITES,items:items,requestTimestamp:requestTimestamp,listId:listId};};/**
|
|
74
105
|
* Request favorites action.
|
|
75
106
|
* @param {string} listId The Id of the wishlist.
|
|
76
107
|
* @returns {Object}
|
|
@@ -82,4 +113,12 @@ import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,CANCEL_REQUEST_SYN
|
|
|
82
113
|
*/export var openFavoritesListChooser=function openFavoritesListChooser(productId){var withRelatives=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return{type:OPEN_FAVORITE_LIST_CHOOSER,productId:productId,withRelatives:withRelatives};};/**
|
|
83
114
|
* Opens the favorite list chooser.
|
|
84
115
|
* @returns {Object}
|
|
85
|
-
*/export var closeFavoritesListChooser=function closeFavoritesListChooser(){return{type:CLOSE_FAVORITE_LIST_CHOOSER};}
|
|
116
|
+
*/export var closeFavoritesListChooser=function closeFavoritesListChooser(){return{type:CLOSE_FAVORITE_LIST_CHOOSER};};/**
|
|
117
|
+
* Opens the favorite comment sheet
|
|
118
|
+
* @param {string} productId The id of the product.
|
|
119
|
+
* @param {string} listId The id of the list.
|
|
120
|
+
* @returns {Object}
|
|
121
|
+
*/export var openFavoritesCommentDialog=function openFavoritesCommentDialog(productId,listId){return{type:OPEN_FAVORITE_COMMENT_DIALOG,productId:productId,listId:listId};};/**
|
|
122
|
+
* Closes the favorite comment sheet
|
|
123
|
+
* @returns {Object}
|
|
124
|
+
*/export var closeFavoritesCommentDialog=function closeFavoritesCommentDialog(){return{type:CLOSE_FAVORITE_COMMENT_DIALOG};};
|
|
@@ -2,6 +2,8 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
|
|
|
2
2
|
* Adds a single product to the favorite list using the `addFavorites` pipeline.
|
|
3
3
|
* @param {string} productId Id of the product to be added.
|
|
4
4
|
* @param {string} listId Id of the list to be added.
|
|
5
|
+
* @param {number} quantity New favorites quantity to set
|
|
6
|
+
* @param {string} notes New favorites notes to set
|
|
5
7
|
* @returns {Function} A redux thunk.
|
|
6
|
-
*/function addFavorites(productId){var listId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var lists,defaultList,takenListId,request;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// Fallback for deprecated calls without list id.
|
|
7
|
-
lists=getState().favorites.lists.lists;defaultList=(lists===null||lists===void 0?void 0:lists[0])||{id:'DEFAULT'};takenListId=listId||defaultList.id;request=new PipelineRequest(SHOPGATE_USER_ADD_FAVORITES).setInput({productId:productId,favoritesListId:takenListId}).setRetries(0).dispatch();_context.prev=4;_context.next=7;return request;case 7:dispatch(successAddFavorites(productId,takenListId));_context.next=13;break;case 10:_context.prev=10;_context.t0=_context["catch"](4);dispatch(errorAddFavorites(productId,_context.t0,takenListId));case 13:return _context.abrupt("return",request);case 14:case"end":return _context.stop();}}},_callee,null,[[4,10]]);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}export default addFavorites;
|
|
8
|
+
*/function addFavorites(productId){var listId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var quantity=arguments.length>2?arguments[2]:undefined;var notes=arguments.length>3?arguments[3]:undefined;return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var lists,defaultList,takenListId,request;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// Fallback for deprecated calls without list id.
|
|
9
|
+
lists=getState().favorites.lists.lists;defaultList=(lists===null||lists===void 0?void 0:lists[0])||{id:'DEFAULT'};takenListId=listId||defaultList.id;request=new PipelineRequest(SHOPGATE_USER_ADD_FAVORITES).setInput({productId:productId,favoritesListId:takenListId,quantity:quantity,notes:notes}).setRetries(0).dispatch();_context.prev=4;_context.next=7;return request;case 7:dispatch(successAddFavorites(productId,takenListId));_context.next=13;break;case 10:_context.prev=10;_context.t0=_context["catch"](4);dispatch(errorAddFavorites(productId,_context.t0,takenListId));case 13:return _context.abrupt("return",request);case 14:case"end":return _context.stop();}}},_callee,null,[[4,10]]);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}export default addFavorites;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
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);});};}import PipelineRequest from'@shopgate/pwa-core/classes/PipelineRequest';import{EFAVORITE,EUNKNOWN,EBIGAPI,ELIMIT}from'@shopgate/pwa-core/constants/Pipeline';import{shouldFetchData,mutable}from'@shopgate/pwa-common/helpers/redux';import{SHOPGATE_USER_GET_FAVORITES}from"../constants/Pipelines";import{receiveFavorites,requestFavorites,errorFetchFavorites}from"../action-creators";/**
|
|
1
|
+
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);});};}import PipelineRequest from'@shopgate/pwa-core/classes/PipelineRequest';import{EFAVORITE,EUNKNOWN,EBIGAPI,ELIMIT}from'@shopgate/pwa-core/constants/Pipeline';import{shouldFetchData,mutable}from'@shopgate/pwa-common/helpers/redux';import{SHOPGATE_USER_GET_FAVORITES}from"../constants/Pipelines";import{receiveFavorites,requestFavorites,errorFetchFavorites}from"../action-creators";import receiveProducts from"../../product/action-creators/receiveProducts";/**
|
|
2
2
|
* Fetch favorites action.
|
|
3
3
|
* @param {boolean} ignoreCache Ignores cache when true
|
|
4
4
|
* @param {string} listId The id of the list that needs to be fetched.
|
|
5
5
|
* @returns {Function} A redux thunk.
|
|
6
6
|
*/function fetchFavorites(){var ignoreCache=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var listId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:undefined;return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var lists,defaultList,takenListId,data,timestamp,request,result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// Fallback for deprecated calls without list id.
|
|
7
7
|
lists=getState().favorites.lists.lists;defaultList=(lists===null||lists===void 0?void 0:lists[0])||{code:'DEFAULT'};takenListId=listId||defaultList.code;// Check cache.
|
|
8
|
-
data=getState().favorites.products.byList[takenListId];if(!(!ignoreCache&&!shouldFetchData(data))){_context.next=6;break;}return _context.abrupt("return",null);case 6:timestamp=Date.now();dispatch(requestFavorites(takenListId));request=new PipelineRequest(SHOPGATE_USER_GET_FAVORITES).setInput({favoritesListId:takenListId}).setErrorBlacklist([EFAVORITE,EUNKNOWN,EBIGAPI,ELIMIT]).dispatch();_context.prev=9;_context.next=12;return request;case 12:result=_context.sent;dispatch(receiveFavorites(result.
|
|
8
|
+
data=getState().favorites.products.byList[takenListId];if(!(!ignoreCache&&!shouldFetchData(data))){_context.next=6;break;}return _context.abrupt("return",null);case 6:timestamp=Date.now();dispatch(requestFavorites(takenListId));request=new PipelineRequest(SHOPGATE_USER_GET_FAVORITES).setVersion(2).setInput({favoritesListId:takenListId}).setErrorBlacklist([EFAVORITE,EUNKNOWN,EBIGAPI,ELIMIT]).dispatch();_context.prev=9;_context.next=12;return request;case 12:result=_context.sent;dispatch(receiveFavorites(result.items,timestamp,takenListId));dispatch(receiveProducts({products:result.items.map(function(_ref2){var product=_ref2.product;return product;}),fetchInventory:false}));return _context.abrupt("return",result);case 18:_context.prev=18;_context.t0=_context["catch"](9);dispatch(errorFetchFavorites(_context.t0,takenListId));return _context.abrupt("return",null);case 22:case"end":return _context.stop();}}},_callee,null,[[9,18]]);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}/** @mixes {MutableFunction} */export default mutable(fetchFavorites);
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
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);});};}import fetchFavorites from"./fetchFavorites";import fetchFavoritesList from"./fetchFavoritesList";/**
|
|
2
|
+
*
|
|
3
|
+
* Combine fetch favorites list action and fetch favorites action.
|
|
4
|
+
* @param {boolean} ignoreCache Ignores cache when true
|
|
5
|
+
* @returns {Function} A redux thunk.
|
|
6
|
+
*/function fetchFavoritesListsWithItems(){var ignoreCache=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch){var lists,itemPromises,wishlistItems;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return dispatch(fetchFavoritesList(ignoreCache));case 2:_context.t0=_context.sent;if(_context.t0){_context.next=5;break;}_context.t0=[];case 5:lists=_context.t0;itemPromises=lists.map(function(list){return dispatch(fetchFavorites(ignoreCache,list.id));});_context.next=9;return Promise.all(itemPromises);case 9:wishlistItems=_context.sent;return _context.abrupt("return",lists.map(function(_ref2,index){var id=_ref2.id,name=_ref2.name;return{id:id,name:name,itemCount:(wishlistItems[index]||{}).itemCount,items:(wishlistItems[index]||{}).items};}));case 11:case"end":return _context.stop();}}},_callee);}));return function(_x){return _ref.apply(this,arguments);};}());}export default fetchFavoritesListsWithItems;
|
|
@@ -2,6 +2,8 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
|
|
|
2
2
|
* Removes a single product from the favorite list using the `deleteFavorites` pipeline.
|
|
3
3
|
* @param {string} productId Id of the product to be deleted.
|
|
4
4
|
* @param {string} listId Id of the list to be deleted.
|
|
5
|
+
* @param {number} quantity Quantity of the favorite
|
|
6
|
+
* @param {string} notes Notes of the favorite
|
|
5
7
|
* @returns {Function} A redux thunk.
|
|
6
|
-
*/function removeFavorites(productId,listId){return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var lists,defaultList,takenListId,request;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// Fallback for deprecated calls without list id.
|
|
7
|
-
lists=getState().favorites.lists.lists;defaultList=(lists===null||lists===void 0?void 0:lists[0])||{id:'DEFAULT'};takenListId=listId||defaultList.id;request=new PipelineRequest(SHOPGATE_USER_DELETE_FAVORITES).setInput({productId:productId,favoritesListId:takenListId}).setRetries(0).dispatch();_context.prev=4;_context.next=7;return request;case 7:dispatch(successRemoveFavorites(productId,takenListId));_context.next=13;break;case 10:_context.prev=10;_context.t0=_context["catch"](4);dispatch(errorRemoveFavorites(productId,takenListId,_context.t0));case 13:return _context.abrupt("return",request);case 14:case"end":return _context.stop();}}},_callee,null,[[4,10]]);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}export default removeFavorites;
|
|
8
|
+
*/function removeFavorites(productId,listId,quantity,notes){return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var lists,defaultList,takenListId,request;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// Fallback for deprecated calls without list id.
|
|
9
|
+
lists=getState().favorites.lists.lists;defaultList=(lists===null||lists===void 0?void 0:lists[0])||{id:'DEFAULT'};takenListId=listId||defaultList.id;request=new PipelineRequest(SHOPGATE_USER_DELETE_FAVORITES).setInput({productId:productId,favoritesListId:takenListId}).setRetries(0).dispatch();_context.prev=4;_context.next=7;return request;case 7:dispatch(successRemoveFavorites(productId,takenListId));_context.next=13;break;case 10:_context.prev=10;_context.t0=_context["catch"](4);dispatch(errorRemoveFavorites(productId,takenListId,_context.t0,quantity,notes));case 13:return _context.abrupt("return",request);case 14:case"end":return _context.stop();}}},_callee,null,[[4,10]]);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}export default removeFavorites;
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import{mutable}from'@shopgate/pwa-common/helpers/redux';import{getFavoritesDefaultList,getFavoritesLists,makeIsProductOnSpecificFavoriteList}from"../selectors";import{addProductToFavorites,removeProductFromFavorites,requestFlushFavoritesBuffer,openFavoritesListChooser}from"../action-creators";/**
|
|
1
|
+
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);});};}import{mutable}from'@shopgate/pwa-common/helpers/redux';import{getWishlistItemQuantityEnabled,getLoadWishlistOnAppStartEnabled}from'@shopgate/engage/core/selectors/shopSettings';import{getFavoritesDefaultList,getFavoritesLists,makeIsProductOnSpecificFavoriteList}from"../selectors";import{addProductToFavorites,removeProductFromFavorites,requestFlushFavoritesBuffer,openFavoritesListChooser,updateProductInFavorites}from"../action-creators";import fetchFavoritesListsWithItems from"./fetchFavoritesListsWithItems";/**
|
|
2
2
|
* Adds a product to the favorite list (debounced and buffered).
|
|
3
3
|
* @mixes {MutableFunction}
|
|
4
4
|
* @param {string} productId Product identifier.
|
|
5
5
|
* @param {string} listId List identifier.
|
|
6
|
+
* @param {number} quantity New favorites quantity to set
|
|
7
|
+
* @param {string} notes New favorites notes to set
|
|
6
8
|
* @return {Function}
|
|
7
|
-
*/export var addFavorite=mutable(function(productId,listId){return function(dispatch,getState){var defaultList=getFavoritesDefaultList(getState());dispatch(addProductToFavorites(productId,listId||defaultList.id));};});/**
|
|
9
|
+
*/export var addFavorite=mutable(function(productId,listId,quantity,notes){return function(dispatch,getState){var defaultList=getFavoritesDefaultList(getState());dispatch(addProductToFavorites(productId,listId||defaultList.id,quantity,notes));};});/**
|
|
8
10
|
* Adds a product to the favorite list (debounced and buffered).
|
|
9
11
|
* @param {string} productId Product identifier.
|
|
10
12
|
* @return {Function}
|
|
@@ -26,11 +28,19 @@ import{mutable}from'@shopgate/pwa-common/helpers/redux';import{getFavoritesDefau
|
|
|
26
28
|
* @param {string} listId List identifier.
|
|
27
29
|
* @param {boolean} withRelatives When true relatives which are on list are also removed.
|
|
28
30
|
* @return {Function}
|
|
29
|
-
*/export var toggleFavorite=function toggleFavorite(productId,listId){var withRelatives=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;return function(dispatch,getState){var
|
|
31
|
+
*/export var toggleFavorite=function toggleFavorite(productId,listId){var withRelatives=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;return function(dispatch,getState){var state=getState();// With quantity enabled the favorites button always adds (increases quantity)
|
|
32
|
+
var wishlistItemQuantityEnabled=getWishlistItemQuantityEnabled(state);var loadWishlistOnAppStartEnabled=getLoadWishlistOnAppStartEnabled(state);if(wishlistItemQuantityEnabled||!loadWishlistOnAppStartEnabled){dispatch(addFavorite(productId,listId));}else{var isOnList=makeIsProductOnSpecificFavoriteList(function(){return productId;},function(){return listId;})(state);dispatch(!isOnList?addFavorite(productId,listId):removeFavorites(productId,withRelatives,listId));}};};/**
|
|
33
|
+
* Updatest a product in the favorite list (debounced and buffered).
|
|
34
|
+
* @param {string} productId Product identifier.
|
|
35
|
+
* @param {string} listId List identifier.
|
|
36
|
+
* @param {number} quantity
|
|
37
|
+
* @param {string} notes
|
|
38
|
+
* @return {Function}
|
|
39
|
+
*/export var updateFavorite=mutable(function(productId,listId,quantity,notes){return function(dispatch,getState){var defaultList=getFavoritesDefaultList(getState());dispatch(updateProductInFavorites(productId,listId||defaultList.id,quantity,notes));};});/**
|
|
30
40
|
* Adds a product to a wishlist by opening a chooser if user has multiple lists.
|
|
31
41
|
* @mixes {MutableFunction}
|
|
32
42
|
* @param {string} productId Product identifier.
|
|
33
43
|
* @param {boolean} withRelatives When true relatives which are on list are also removed.
|
|
34
44
|
* @return {Function}
|
|
35
|
-
*/export var toggleFavoriteWithListChooser=mutable(function(productId){var withRelatives=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return function(dispatch,getState){var state=getState();
|
|
36
|
-
if(lists.length<=1){dispatch(toggleFavorite(productId,lists[0].id,withRelatives));return;
|
|
45
|
+
*/export var toggleFavoriteWithListChooser=mutable(function(productId){var withRelatives=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var state,lists;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return dispatch(fetchFavoritesListsWithItems());case 2:state=getState();lists=getFavoritesLists(state);// Only one list available therefore we just add/remove it the product there.
|
|
46
|
+
if(!(lists.length<=1)){_context.next=7;break;}dispatch(toggleFavorite(productId,lists[0].id,withRelatives));return _context.abrupt("return");case 7:dispatch(openFavoritesListChooser(productId,withRelatives));case 8:case"end":return _context.stop();}}},_callee);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
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 PipelineRequest from'@shopgate/pwa-core/classes/PipelineRequest';import isNumber from'lodash/isNumber';import isString from'lodash/isString';import{SHOPGATE_USER_UPDATE_FAVORITES}from"../constants/Pipelines";import{errorUpdateFavorites,successUpdateFavorites}from"../action-creators";/**
|
|
2
|
+
* Updates a single product on the favorite list using the `updateFavorites` pipeline.
|
|
3
|
+
* @param {string} productId The id of the product.
|
|
4
|
+
* @param {string} listId Id of the list to be updated.
|
|
5
|
+
* @param {number} quantity New favorites quantity to set
|
|
6
|
+
* @param {string} notes ew favorites notes to set
|
|
7
|
+
* @returns {Function} A redux thunk.
|
|
8
|
+
*/function updateFavorites(productId){var listId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var quantity=arguments.length>2?arguments[2]:undefined;var notes=arguments.length>3?arguments[3]:undefined;return(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var lists,defaultList,takenListId,request;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// Fallback for deprecated calls without list id.
|
|
9
|
+
lists=getState().favorites.lists.lists;defaultList=(lists===null||lists===void 0?void 0:lists[0])||{id:'DEFAULT'};takenListId=listId||defaultList.id;request=new PipelineRequest(SHOPGATE_USER_UPDATE_FAVORITES).setInput(_extends({productId:productId,favoritesListId:takenListId},isNumber(quantity)?{quantity:quantity}:{},{},isString(notes)?{notes:notes}:{})).setRetries(0).dispatch();_context.prev=4;_context.next=7;return request;case 7:dispatch(successUpdateFavorites(productId,takenListId));_context.next=13;break;case 10:_context.prev=10;_context.t0=_context["catch"](4);dispatch(errorUpdateFavorites(productId,_context.t0,takenListId));case 13:return _context.abrupt("return",request);case 14:case"end":return _context.stop();}}},_callee,null,[[4,10]]);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}export default updateFavorites;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export var SHOPGATE_USER_GET_FAVORITES='shopgate.user.getFavorites';export var SHOPGATE_USER_ADD_FAVORITES='shopgate.user.addFavorites';export var SHOPGATE_USER_DELETE_FAVORITES='shopgate.user.deleteFavorites';export var SHOPGATE_USER_GET_FAVORITES_LIST='shopgate.user.getFavoritesLists';export var SHOPGATE_USER_ADD_FAVORITES_LIST='shopgate.user.addFavoritesList';export var SHOPGATE_USER_UPDATE_FAVORITES_LIST='shopgate.user.updateFavoritesList';export var SHOPGATE_USER_REMOVE_FAVORITES_LIST='shopgate.user.removeFavoritesList';
|
|
1
|
+
export var SHOPGATE_USER_GET_FAVORITES='shopgate.user.getFavorites';export var SHOPGATE_USER_ADD_FAVORITES='shopgate.user.addFavorites';export var SHOPGATE_USER_DELETE_FAVORITES='shopgate.user.deleteFavorites';export var SHOPGATE_USER_UPDATE_FAVORITES='shopgate.user.updateFavorites';export var SHOPGATE_USER_GET_FAVORITES_LIST='shopgate.user.getFavoritesLists';export var SHOPGATE_USER_ADD_FAVORITES_LIST='shopgate.user.addFavoritesList';export var SHOPGATE_USER_UPDATE_FAVORITES_LIST='shopgate.user.updateFavoritesList';export var SHOPGATE_USER_REMOVE_FAVORITES_LIST='shopgate.user.removeFavoritesList';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export var FAVORITES_PATH='/favourite_list';export var ADD_PRODUCT_TO_FAVORITES='ADD_PRODUCT_TO_FAVORITES';export var REMOVE_PRODUCT_FROM_FAVORITES='REMOVE_PRODUCT_FROM_FAVORITES';export var REQUEST_FAVORITES='REQUEST_FAVORITES';export var RECEIVE_FAVORITES='RECEIVE_FAVORITES';export var ERROR_FAVORITES='ERROR_FAVORITES';export var ERROR_FETCH_FAVORITES='ERROR_FETCH_FAVORITES';export var REQUEST_ADD_FAVORITES='REQUEST_ADD_FAVORITES';export var SUCCESS_ADD_FAVORITES='SUCCESS_ADD_FAVORITES';export var ERROR_ADD_FAVORITES='ERROR_ADD_FAVORITES';export var REQUEST_REMOVE_FAVORITES='REQUEST_REMOVE_FAVORITES';export var SUCCESS_REMOVE_FAVORITES='SUCCESS_REMOVE_FAVORITES';export var ERROR_REMOVE_FAVORITES='ERROR_REMOVE_FAVORITES';export var CANCEL_REQUEST_SYNC_FAVORITES='CANCEL_REQUEST_SYNC_FAVORITES';export var IDLE_SYNC_FAVORITES='IDLE_SYNC_FAVORITES';export var REQUEST_FLUSH_FAVORITES_BUFFER='REQUEST_FLUSH_FAVORITES_BUFFER';// Defines a local error code which is not related to a backend call
|
|
1
|
+
export var FAVORITES_PATH='/favourite_list';export var ADD_PRODUCT_TO_FAVORITES='ADD_PRODUCT_TO_FAVORITES';export var UPDATE_PRODUCT_IN_FAVORITES='UPDATE_PRODUCT_IN_FAVORITES';export var REMOVE_PRODUCT_FROM_FAVORITES='REMOVE_PRODUCT_FROM_FAVORITES';export var REQUEST_UPDATE_FAVORITES='REQUEST_UPDATE_FAVORITES';export var SUCCESS_UPDATE_FAVORITES='SUCCESS_UPDATE_FAVORITES';export var ERROR_UPDATE_FAVORITES='ERROR_UPDATE_FAVORITES';export var REQUEST_FAVORITES='REQUEST_FAVORITES';export var RECEIVE_FAVORITES='RECEIVE_FAVORITES';export var ERROR_FAVORITES='ERROR_FAVORITES';export var ERROR_FETCH_FAVORITES='ERROR_FETCH_FAVORITES';export var REQUEST_ADD_FAVORITES='REQUEST_ADD_FAVORITES';export var SUCCESS_ADD_FAVORITES='SUCCESS_ADD_FAVORITES';export var ERROR_ADD_FAVORITES='ERROR_ADD_FAVORITES';export var REQUEST_REMOVE_FAVORITES='REQUEST_REMOVE_FAVORITES';export var SUCCESS_REMOVE_FAVORITES='SUCCESS_REMOVE_FAVORITES';export var ERROR_REMOVE_FAVORITES='ERROR_REMOVE_FAVORITES';export var CANCEL_REQUEST_SYNC_FAVORITES='CANCEL_REQUEST_SYNC_FAVORITES';export var IDLE_SYNC_FAVORITES='IDLE_SYNC_FAVORITES';export var REQUEST_FLUSH_FAVORITES_BUFFER='REQUEST_FLUSH_FAVORITES_BUFFER';// Defines a local error code which is not related to a backend call
|
|
2
2
|
export var FAVORITES_LIMIT_ERROR='FAVORITES_LIMIT_ERROR';export var FAVORITES_LIFETIME=3600000;// 1 hour
|
|
3
3
|
export var FETCH_FAVORITES_THROTTLE=process.env&&process.env.NODE_ENV==='test'?0:2000;export var FAVORITE_ACTION_BUFFER_TIME=500;export var FAVORITE_BUTTON_DEBOUNCE_TIME=200;// Handles duplicated add/remove button clicks
|
|
4
|
-
export var
|
|
4
|
+
export var FAVORITE_QUANTITY_DEBOUNCE_TIME=200;// Handles duplicated update button clicks
|
|
5
|
+
export var RECEIVE_FAVORITES_LISTS='SUCCESS_FETCH_FAVORITES_LIST';export var SUCCESS_ADD_FAVORITES_LIST='SUCCESS_ADD_FAVORITES_LIST';export var SUCCESS_UPDATE_FAVORITES_LIST='SUCCESS_UPDATE_FAVORITES_LIST';export var SUCCESS_REMOVE_FAVORITES_LIST='SUCCESS_REMOVE_FAVORITES_LIST';export var OPEN_FAVORITE_LIST_CHOOSER='OPEN_FAVORITE_LIST_CHOOSER';export var CLOSE_FAVORITE_LIST_CHOOSER='CLOSE_FAVORITE_LIST_CHOOSER';export var OPEN_FAVORITE_COMMENT_DIALOG='OPEN_FAVORITE_COMMENT_DIALOG';export var CLOSE_FAVORITE_COMMENT_DIALOG='CLOSE_FAVORITE_COMMENT_DIALOG';
|
package/favorites/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// ACTIONS
|
|
2
|
-
export{default as fetchFavorites}from"./actions/fetchFavorites";export{addFavorite,removeFavorites,requestSync as toggleFavorites}from"./actions/toggleFavorites";// CONSTANTS
|
|
2
|
+
export{default as fetchFavorites}from"./actions/fetchFavorites";export{addFavorite,removeFavorites,requestSync as toggleFavorites}from"./actions/toggleFavorites";export{default as fetchFavoritesListsWithItems}from"./actions/fetchFavoritesListsWithItems";// CONSTANTS
|
|
3
3
|
export*from"./constants/index";export*from"./constants/Pipelines";export*from"./constants/Portals";// SELECTORS
|
|
4
4
|
export*from"./selectors";// STREAMS
|
|
5
5
|
export*from"./streams";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{produce}from'immer';import{RECEIVE_FAVORITES_LISTS,SUCCESS_ADD_FAVORITES_LIST,SUCCESS_UPDATE_FAVORITES_LIST,SUCCESS_REMOVE_FAVORITES_LIST,OPEN_FAVORITE_LIST_CHOOSER,CLOSE_FAVORITE_LIST_CHOOSER,FAVORITES_LIFETIME}from"../constants";/**
|
|
1
|
+
import{produce}from'immer';import{RECEIVE_FAVORITES_LISTS,SUCCESS_ADD_FAVORITES_LIST,SUCCESS_UPDATE_FAVORITES_LIST,SUCCESS_REMOVE_FAVORITES_LIST,OPEN_FAVORITE_LIST_CHOOSER,CLOSE_FAVORITE_LIST_CHOOSER,FAVORITES_LIFETIME,OPEN_FAVORITE_COMMENT_DIALOG,CLOSE_FAVORITE_COMMENT_DIALOG}from"../constants";/**
|
|
2
2
|
* Favorites lists reducer.
|
|
3
3
|
* @param {Object} state Current state.
|
|
4
4
|
* @param {Object} action Dispatched action.
|
|
5
5
|
* @returns {Object} New state.
|
|
6
|
-
*/var lists=function lists(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{expires:0,lists:[],chooser:null};var action=arguments.length>1?arguments[1]:undefined;/* eslint-disable no-param-reassign */var newState=produce(state,function(draft){switch(action.type){case OPEN_FAVORITE_LIST_CHOOSER:{draft.chooser={productId:action.productId,withRelatives:action.withRelatives};break;}case CLOSE_FAVORITE_LIST_CHOOSER:{draft.chooser=null;break;}case RECEIVE_FAVORITES_LISTS:{draft.expires=Date.now()+FAVORITES_LIFETIME;draft.lists=action.favoritesLists;break;}case SUCCESS_ADD_FAVORITES_LIST:{draft.lists.push({id:action.listId,name:action.name});break;}case SUCCESS_UPDATE_FAVORITES_LIST:{var list=draft.lists.find(function(l){return l.id===action.listId;});list.name=action.name;break;}case SUCCESS_REMOVE_FAVORITES_LIST:{var listIndex=draft.lists.findIndex(function(l){return l.id===action.listId;});draft.lists.splice(listIndex,1);break;}default:break;}});/* eslint-enable no-param-reassign */return newState;};export default lists;
|
|
6
|
+
*/var lists=function lists(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{expires:0,lists:[],chooser:null,commentDialog:null};var action=arguments.length>1?arguments[1]:undefined;/* eslint-disable no-param-reassign */var newState=produce(state,function(draft){switch(action.type){case OPEN_FAVORITE_LIST_CHOOSER:{draft.chooser={productId:action.productId,withRelatives:action.withRelatives};break;}case CLOSE_FAVORITE_LIST_CHOOSER:{draft.chooser=null;break;}case OPEN_FAVORITE_COMMENT_DIALOG:{draft.commentDialog={productId:action.productId,listId:action.listId};break;}case CLOSE_FAVORITE_COMMENT_DIALOG:{draft.commentDialog=null;break;}case RECEIVE_FAVORITES_LISTS:{draft.expires=Date.now()+FAVORITES_LIFETIME;draft.lists=action.favoritesLists;break;}case SUCCESS_ADD_FAVORITES_LIST:{draft.lists.push({id:action.listId,name:action.name});break;}case SUCCESS_UPDATE_FAVORITES_LIST:{var list=draft.lists.find(function(l){return l.id===action.listId;});list.name=action.name;break;}case SUCCESS_REMOVE_FAVORITES_LIST:{var listIndex=draft.lists.findIndex(function(l){return l.id===action.listId;});draft.lists.splice(listIndex,1);break;}default:break;}});/* eslint-enable no-param-reassign */return newState;};export default lists;
|
|
@@ -1,26 +1,28 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{produce}from'immer';import isNumber from'lodash/isNumber';import isString from'lodash/isString';import{REQUEST_ADD_FAVORITES,SUCCESS_ADD_FAVORITES,CANCEL_REQUEST_SYNC_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,SUCCESS_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,REQUEST_FAVORITES,ERROR_FETCH_FAVORITES,SUCCESS_REMOVE_FAVORITES_LIST,SUCCESS_ADD_FAVORITES_LIST,RECEIVE_FAVORITES,FAVORITES_LIFETIME,SUCCESS_UPDATE_FAVORITES,REQUEST_UPDATE_FAVORITES,ERROR_UPDATE_FAVORITES,RECEIVE_FAVORITES_LISTS}from"../constants";/**
|
|
2
2
|
* Favorites reducer.
|
|
3
3
|
* @param {Object} state Current state.
|
|
4
4
|
* @param {Object} action Dispatched action.
|
|
5
5
|
* @returns {Object} New state.
|
|
6
|
-
*/var products=function products(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{byList:{}};var action=arguments.length>1?arguments[1]:undefined;/* eslint-disable no-param-reassign */var producedState=produce(state,function(draft){switch(action.type){// Handle
|
|
7
|
-
case REQUEST_FAVORITES:{var existingList=draft.byList[action.listId];if(!existingList){draft.byList[action.listId]={isFetching:true,lastChange:0,lastFetch:0,expires:0,
|
|
6
|
+
*/var products=function products(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{byList:{}};var action=arguments.length>1?arguments[1]:undefined;/* eslint-disable no-param-reassign */var producedState=produce(state,function(draft){switch(action.type){// Handle a new favorites request.
|
|
7
|
+
case REQUEST_FAVORITES:{var existingList=draft.byList[action.listId];if(!existingList){draft.byList[action.listId]={isFetching:true,lastChange:0,lastFetch:0,expires:0,items:[],syncCount:0};return;}existingList.isFetching=true;existingList.expires=0;break;}// Handle incoming favorite products.
|
|
8
8
|
case RECEIVE_FAVORITES:{var list=draft.byList[action.listId];var isSynching=list.syncCount>0;var isOngoing=state.lastChange>action.requestTimestamp;/**
|
|
9
9
|
* Note: When favorites are received, an add or remove request can be in progress. In this
|
|
10
10
|
* case only fetching state will be updated and the received data will be discarded.
|
|
11
11
|
* A new fetch request will be queued as soon as the sync is done, which will recover
|
|
12
12
|
* discarded data.
|
|
13
|
-
*/list.isFetching=false;if(list.ready&&(isSynching||isOngoing)){return;}list.expires=Date.now()+FAVORITES_LIFETIME;list.
|
|
13
|
+
*/list.isFetching=false;if(list.ready&&(isSynching||isOngoing)){return;}list.expires=Date.now()+FAVORITES_LIFETIME;list.items=action.items.map(function(_ref){var quantity=_ref.quantity,notes=_ref.notes,product=_ref.product;return{quantity:quantity,notes:notes,productId:product.id};});list.ready=true;// `syncCount` stays untouched because this is not considered to be a sync.
|
|
14
14
|
break;}// Handle failed fetching
|
|
15
15
|
case ERROR_FETCH_FAVORITES:{var _list=draft.byList[action.listId];_list.isFetching=false;_list.expires=0;_list.ready=true;// `syncCount` stays untouched because this is not considered to be a sync.
|
|
16
16
|
break;}// Handle adding favorite list products.
|
|
17
|
-
case REQUEST_ADD_FAVORITES:{var _list2=draft.byList[action.listId];_list2.
|
|
18
|
-
case REQUEST_REMOVE_FAVORITES:{var
|
|
17
|
+
case REQUEST_ADD_FAVORITES:{var _list2=draft.byList[action.listId];var matchingItem=_list2.items.find(function(_ref2){var productId=_ref2.productId;return productId===action.productId;});if(matchingItem){matchingItem.notes=typeof action.notes==='string'?action.notes:matchingItem.notes;matchingItem.quantity=typeof action.quantity==='number'?matchingItem.quantity+action.quantity:matchingItem.quantity+1;}else{_list2.items.push({notes:action.notes||'',quantity:action.quantity||1,productId:action.productId});}_list2.lastChange=Date.now();_list2.syncCount+=1;break;}case REQUEST_UPDATE_FAVORITES:{var _list3=draft.byList[action.listId];var _matchingItem=_list3.items.find(function(_ref3){var productId=_ref3.productId;return productId===action.productId;});if(_matchingItem){if(isNumber(action.quantity)){_matchingItem.quantity=action.quantity;}if(isString(action.notes)){_matchingItem.notes=action.notes;}_list3.lastChange=Date.now();_list3.syncCount+=1;}break;}// Handle removing favorite list products.
|
|
18
|
+
case REQUEST_REMOVE_FAVORITES:{var _list4=draft.byList[action.listId];var matchingItemIndex=_list4.items.findIndex(function(_ref4){var productId=_ref4.productId;return productId===action.productId;});if(matchingItemIndex>-1){_list4.items.splice(matchingItemIndex,1);}_list4.lastChange=Date.now();_list4.syncCount+=1;break;}// Handle cancellation of synchronization.
|
|
19
19
|
// Sync count needs to be updated, when an add or a remove favorites action is cancelled
|
|
20
20
|
// This recovers from invalid sync states when a backend call is detected to be redundant
|
|
21
|
-
case CANCEL_REQUEST_SYNC_FAVORITES:{var
|
|
22
|
-
case SUCCESS_ADD_FAVORITES:case SUCCESS_REMOVE_FAVORITES:{var
|
|
23
|
-
case ERROR_REMOVE_FAVORITES:{var
|
|
24
|
-
case ERROR_ADD_FAVORITES:{var
|
|
21
|
+
case CANCEL_REQUEST_SYNC_FAVORITES:{var _list5=draft.byList[action.listId];_list5.syncCount-=action.count;break;}// Handle success of adding favorite list products.
|
|
22
|
+
case SUCCESS_ADD_FAVORITES:case SUCCESS_UPDATE_FAVORITES:case SUCCESS_REMOVE_FAVORITES:{var _list6=draft.byList[action.listId];_list6.lastChange=Date.now();_list6.syncCount-=1;break;}// Handle deletion failure by adding the product back in to the list.
|
|
23
|
+
case ERROR_REMOVE_FAVORITES:{var _list7=draft.byList[action.listId];_list7.items.push({productId:action.productId,quantity:action.quantity||1,notes:action.notes||''});_list7.lastChange=Date.now();_list7.syncCount-=1;break;}// Handle adding failure by removing the product from the list.
|
|
24
|
+
case ERROR_ADD_FAVORITES:{var _list8=draft.byList[action.listId];var _matchingItemIndex=_list8.items.findIndex(function(_ref5){var productId=_ref5.productId;return productId===action.productId;});if(_matchingItemIndex>-1){_list8.items.splice(_matchingItemIndex,1);}_list8.lastChange=Date.now();_list8.syncCount-=1;break;}case ERROR_UPDATE_FAVORITES:{var _list9=draft.byList[action.listId];_list9.lastChange=Date.now();_list9.syncCount-=1;break;}// Handle cleanup after deletion of a list.
|
|
25
25
|
case SUCCESS_REMOVE_FAVORITES_LIST:{delete draft.byList[action.listId];break;}// Handle adding new lists.
|
|
26
|
-
case SUCCESS_ADD_FAVORITES_LIST:{draft.byList[action.listId]={isFetching:true,lastChange:0,lastFetch:0,expires:0,
|
|
26
|
+
case SUCCESS_ADD_FAVORITES_LIST:{draft.byList[action.listId]={isFetching:true,lastChange:0,lastFetch:0,expires:0,items:[],syncCount:0,ready:true};break;}// Handle cleanup after lists are updated
|
|
27
|
+
case RECEIVE_FAVORITES_LISTS:{var listIds=action.favoritesLists.map(function(_ref6){var id=_ref6.id;return id;});Object.keys(draft.byList).forEach(function(id){if(!listIds.includes(id)){// Remove list items that don't have a list anymore
|
|
28
|
+
delete draft.byList[id];}});break;}default:break;}});/* eslint-enable no-param-reassign */return producedState;};export default products;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createSelector}from'reselect';import uniq from'lodash/uniq';import{getProducts,getProductId}from"../../product/selectors/product";import{getKnownRelatives}from"../../product/selectors/variants";var defaultIds=[];/**
|
|
1
|
+
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{createSelector}from'reselect';import uniq from'lodash/uniq';import{getProducts,getProductId}from"../../product/selectors/product";import{getKnownRelatives}from"../../product/selectors/variants";var defaultIds=[];/**
|
|
2
2
|
* @param {Object} state The global state.
|
|
3
3
|
* @return {Object}
|
|
4
4
|
*/export var getFavoritesState=function getFavoritesState(state){return state.favorites||{};};/**
|
|
@@ -20,7 +20,7 @@ import{createSelector}from'reselect';import uniq from'lodash/uniq';import{getPro
|
|
|
20
20
|
* @param {Object} state The global state.
|
|
21
21
|
* @returns {Array}
|
|
22
22
|
* @deprecated
|
|
23
|
-
*/export var getFavoritesProductsIds=createSelector(getFavoritesProducts,function(products){if(!products||!products.byList){return defaultIds;}return uniq(Object.values(products.byList).map(function(l){return l.
|
|
23
|
+
*/export var getFavoritesProductsIds=createSelector(getFavoritesProducts,function(products){if(!products||!products.byList){return defaultIds;}return uniq(Object.values(products.byList).map(function(l){return l.items.map(function(_ref2){var productId=_ref2.productId;return productId;});}).flat());});/**
|
|
24
24
|
* @param {Object} state The global state.
|
|
25
25
|
* @deprecated
|
|
26
26
|
*/export var getFavorites=createSelector(getFavoritesProductsIds,getProducts,function(productIds,products){return productIds.filter(function(id){return!!products[id]&&products[id].productData;}).map(function(id){return products[id].productData;});});/**
|
|
@@ -28,32 +28,32 @@ import{createSelector}from'reselect';import uniq from'lodash/uniq';import{getPro
|
|
|
28
28
|
* to the given favorite list.
|
|
29
29
|
* @param {Function} getListCode Selects the list code.
|
|
30
30
|
* @returns {Function}
|
|
31
|
-
*/export var makeGetFavoritesIdsByList=function makeGetFavoritesIdsByList(getListCode){return createSelector(getFavoritesProducts,getListCode,function(favProducts,listId){var _favProducts$byList$l;
|
|
31
|
+
*/export var makeGetFavoritesIdsByList=function makeGetFavoritesIdsByList(getListCode){return createSelector(getFavoritesProducts,getListCode,function(favProducts,listId){var _favProducts$byList$l;return(favProducts===null||favProducts===void 0?void 0:(_favProducts$byList$l=favProducts.byList[listId])===null||_favProducts$byList$l===void 0?void 0:_favProducts$byList$l.items.map(function(_ref3){var productId=_ref3.productId;return productId;}))||[];});};/**
|
|
32
32
|
* Creates a selector that selects all products that belong
|
|
33
33
|
* to the given favorite list.
|
|
34
34
|
* @param {Function} getListCode Selects the list code.
|
|
35
35
|
* @returns {Function}
|
|
36
|
-
*/export var makeGetFavorites=function makeGetFavorites(getListCode){
|
|
36
|
+
*/export var makeGetFavorites=function makeGetFavorites(getListCode){return createSelector(getFavoritesProducts,getListCode,getProducts,function(favItems,listId,products){var _favItems$byList$list;var items=(favItems===null||favItems===void 0?void 0:(_favItems$byList$list=favItems.byList[listId])===null||_favItems$byList$list===void 0?void 0:_favItems$byList$list.items)||[];return items.map(function(item){var _products$item$produc;return _extends({},item,{product:(_products$item$produc=products[item.productId])===null||_products$item$produc===void 0?void 0:_products$item$produc.productData});});});};/**
|
|
37
37
|
* True when favorites where not yet fetched for the first time.
|
|
38
38
|
* @param {Object} state The global state.
|
|
39
39
|
* @returns {boolean}
|
|
40
|
-
*/export var isInitialLoading=createSelector(getFavoritesProducts,function(products){if(!products){return true;}return!Object.values(products.byList).every(function(l){return l.ready;});});/**
|
|
40
|
+
*/export var isInitialLoading=createSelector(getFavoritesProducts,function(products){if(!products){return true;}return!Object.values(products===null||products===void 0?void 0:products.byList).every(function(l){return l.ready;});});/**
|
|
41
41
|
* @param {Object} state The global state.
|
|
42
42
|
* @return {number}
|
|
43
|
-
*/export var getFavoritesCount=createSelector(getFavoritesProducts,function(products){if(!(products===null||products===void 0?void 0:products.byList)){return 0;}return Object.values(products.byList).reduce(function(prev,list){return prev+list.
|
|
43
|
+
*/export var getFavoritesCount=createSelector(getFavoritesProducts,function(products){if(!(products===null||products===void 0?void 0:products.byList)){return 0;}return Object.values(products.byList).reduce(function(prev,list){return prev+list.items.reduce(function(acc,_ref4){var _ref4$quantity=_ref4.quantity,quantity=_ref4$quantity===void 0?1:_ref4$quantity;return acc+quantity;},0);},0);});/**
|
|
44
44
|
* @param {Object} state The global state.
|
|
45
45
|
* @return {boolean}
|
|
46
46
|
*/export var hasFavorites=createSelector(getFavoritesCount,function(count){return!!count;});/**
|
|
47
47
|
* @param {Object} state The global state.
|
|
48
48
|
* @return {boolean}
|
|
49
|
-
*/export var isFetching=createSelector(getFavoritesProducts,function(products){if(!products){return false;}return Object.values(products.byList).
|
|
49
|
+
*/export var isFetching=createSelector(getFavoritesProducts,function(products){if(!products){return false;}return Object.values(products.byList).some(function(l){return l.isFetching;});});/**
|
|
50
50
|
* @param {Function} getProductCode Reads the product id.
|
|
51
51
|
* @param {Function} getListCode Reads the list id.
|
|
52
52
|
* @return {boolean}
|
|
53
|
-
*/export var makeIsProductOnSpecificFavoriteList=function makeIsProductOnSpecificFavoriteList(getProductCode,getListCode){return createSelector(getProductCode,getListCode,getFavoritesProducts,function(productId,listId,products){var _products$byList$list;return!!((_products$byList$list=products.byList[listId])===null||_products$byList$list===void 0?void 0:_products$byList$list.
|
|
53
|
+
*/export var makeIsProductOnSpecificFavoriteList=function makeIsProductOnSpecificFavoriteList(getProductCode,getListCode){return createSelector(getProductCode,getListCode,getFavoritesProducts,function(productId,listId,products){var _products$byList$list;return!!((_products$byList$list=products.byList[listId])===null||_products$byList$list===void 0?void 0:_products$byList$list.items.some(function(_ref5){var itemProductId=_ref5.productId;return itemProductId===productId;}));});};/**
|
|
54
54
|
* @param {Function} getProductCode Reads the product id.
|
|
55
55
|
* @return {boolean}
|
|
56
|
-
*/export var makeIsProductOnFavoriteList=function makeIsProductOnFavoriteList(getProductCode){return createSelector(getProductCode,getFavoritesProducts,function(productId,products){return!!Object.values(products.byList).find(function(list){return!!list.
|
|
56
|
+
*/export var makeIsProductOnFavoriteList=function makeIsProductOnFavoriteList(getProductCode){return createSelector(getProductCode,getFavoritesProducts,function(productId,products){return!!Object.values(products.byList).find(function(list){var _list$items;return!!(list===null||list===void 0?void 0:(_list$items=list.items)===null||_list$items===void 0?void 0:_list$items.find(function(_ref6){var itemProductId=_ref6.productId;return itemProductId===productId;}));});});};/**
|
|
57
57
|
* @param {Object} state The global state.
|
|
58
58
|
* @return {boolean}
|
|
59
59
|
*/export var isCurrentProductOnFavoriteList=makeIsProductOnFavoriteList(getProductId);/**
|
|
@@ -61,13 +61,13 @@ import{createSelector}from'reselect';import uniq from'lodash/uniq';import{getPro
|
|
|
61
61
|
* @param {Object} state Current state.
|
|
62
62
|
* @param {string} productId
|
|
63
63
|
* @returns {Array}
|
|
64
|
-
*/export var getProductRelativesOnFavorites=createSelector(getKnownRelatives,getFavoritesProducts,function(productRelativesIds,products){return productRelativesIds.filter(function(id){return!!Object.values(products.byList).find(function(list){return!!list.
|
|
64
|
+
*/export var getProductRelativesOnFavorites=createSelector(getKnownRelatives,getFavoritesProducts,function(productRelativesIds,products){return productRelativesIds.filter(function(id){return!!Object.values(products.byList).find(function(list){return!!list.items.find(function(_ref7){var productId=_ref7.productId;return id===productId;});});});});/**
|
|
65
65
|
* Returns all relatives which are on a specific favorites list.
|
|
66
66
|
* @param {Function} getListCode Gets the list code.
|
|
67
67
|
* @returns {Function}
|
|
68
|
-
*/export var makeGetProductRelativesOnFavorites=function makeGetProductRelativesOnFavorites(getListCode){return createSelector(getListCode,getKnownRelatives,getFavoritesProducts,function(listId,productRelativesIds,products){return productRelativesIds.filter(function(id){var _products$byList$list2;return(_products$byList$list2=products.byList[listId])===null||_products$byList$list2===void 0?void 0:_products$byList$list2.
|
|
68
|
+
*/export var makeGetProductRelativesOnFavorites=function makeGetProductRelativesOnFavorites(getListCode){return createSelector(getListCode,getKnownRelatives,getFavoritesProducts,function(listId,productRelativesIds,products){return productRelativesIds.filter(function(id){var _products$byList$list2;return(_products$byList$list2=products.byList[listId])===null||_products$byList$list2===void 0?void 0:_products$byList$list2.items.map(function(_ref8){var productId=_ref8.productId;return productId;}).find(function(p){return id===p;});});});};/**
|
|
69
69
|
* Checks if product or any relative is on favorites list.
|
|
70
70
|
* @param {Object} state Current state.
|
|
71
71
|
* @param {string} productId Product id.
|
|
72
72
|
* @return {boolean}
|
|
73
|
-
*/export var isRelativeProductOnList=createSelector(getProductRelativesOnFavorites,function(relativesOnFavorites){return relativesOnFavorites.length>0;});
|
|
73
|
+
*/export var isRelativeProductOnList=createSelector(getProductRelativesOnFavorites,function(relativesOnFavorites){return relativesOnFavorites.length>0;});export var getCommentDialogSettings=createSelector(getFavoritesListState,getFavoritesProducts,getProducts,function(_ref9,favItems,products){var _favItems$byList$list2,_products$item$produc2;var commentDialog=_ref9.commentDialog;var _ref10=commentDialog||{},listId=_ref10.listId,productId=_ref10.productId;if(!listId||!productId){return undefined;}var items=((_favItems$byList$list2=favItems.byList[listId])===null||_favItems$byList$list2===void 0?void 0:_favItems$byList$list2.items)||[];var item=items.find(function(_ref11){var itemProductId=_ref11.productId;return productId===itemProductId;});if(!item){return undefined;}return{listId:listId,productId:productId,item:item,product:(_products$item$produc2=products[item.productId])===null||_products$item$produc2===void 0?void 0:_products$item$produc2.productData};});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{routeWillEnter$}from'@shopgate/pwa-common/streams/router';import{main$}from'@shopgate/pwa-common/streams/main';import{appDidStart$}from'@shopgate/pwa-common/streams/app';import{userDidLogin$,userDidLogout$}from'@shopgate/pwa-common/streams/user';import{getCurrentPathname}from'@shopgate/pwa-common/selectors/router';import{WISH_LIST_PATH}from'@shopgate/engage/account/constants/routes';import{FAVORITES_PATH,ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,RECEIVE_FAVORITES,ERROR_FAVORITES,ERROR_FETCH_FAVORITES,REQUEST_ADD_FAVORITES,SUCCESS_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,SUCCESS_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,IDLE_SYNC_FAVORITES,REQUEST_FLUSH_FAVORITES_BUFFER,FAVORITES_LIMIT_ERROR,FETCH_FAVORITES_THROTTLE,FAVORITE_ACTION_BUFFER_TIME,FAVORITE_BUTTON_DEBOUNCE_TIME,SUCCESS_ADD_FAVORITES_LIST}from"../constants";/**
|
|
1
|
+
import{routeWillEnter$}from'@shopgate/pwa-common/streams/router';import{main$}from'@shopgate/pwa-common/streams/main';import{appDidStart$}from'@shopgate/pwa-common/streams/app';import{userDidLogin$,userDidLogout$}from'@shopgate/pwa-common/streams/user';import{getCurrentPathname}from'@shopgate/pwa-common/selectors/router';import{WISH_LIST_PATH}from'@shopgate/engage/account/constants/routes';import{FAVORITES_PATH,ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,RECEIVE_FAVORITES,ERROR_FAVORITES,ERROR_FETCH_FAVORITES,REQUEST_ADD_FAVORITES,SUCCESS_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,SUCCESS_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,IDLE_SYNC_FAVORITES,REQUEST_FLUSH_FAVORITES_BUFFER,FAVORITES_LIMIT_ERROR,FETCH_FAVORITES_THROTTLE,FAVORITE_ACTION_BUFFER_TIME,FAVORITE_BUTTON_DEBOUNCE_TIME,SUCCESS_ADD_FAVORITES_LIST,REQUEST_UPDATE_FAVORITES,UPDATE_PRODUCT_IN_FAVORITES,FAVORITE_QUANTITY_DEBOUNCE_TIME}from"../constants";/**
|
|
2
2
|
* @link https://developer.shopgate.com/references/engage/streams/favorites
|
|
3
3
|
*/ /**
|
|
4
4
|
* Gets triggered when the favorites page is about to be entered.
|
|
@@ -7,16 +7,19 @@ import{routeWillEnter$}from'@shopgate/pwa-common/streams/router';import{main$}fr
|
|
|
7
7
|
* Gets triggered when the debounce time of `addProductToFavorites` passes.
|
|
8
8
|
* @type {Observable}
|
|
9
9
|
*/export var addProductToFavoritesDebounced$=main$.filter(function(_ref2){var action=_ref2.action;return action.type===ADD_PRODUCT_TO_FAVORITES;}).debounceTime(FAVORITE_BUTTON_DEBOUNCE_TIME);/**
|
|
10
|
+
* Gets triggered when the debounce time of `updateProductInFavorites` passes.
|
|
11
|
+
* @type {Observable}
|
|
12
|
+
*/export var updateProductInFavoritesDebounced$=main$.filter(function(_ref3){var action=_ref3.action;return action.type===UPDATE_PRODUCT_IN_FAVORITES;}).debounceTime(FAVORITE_QUANTITY_DEBOUNCE_TIME);/**
|
|
10
13
|
* Gets triggered when the debounce time of `removeProductFromFavorites` passes.
|
|
11
14
|
* @type {Observable}
|
|
12
|
-
*/export var removeProductFromFavoritesDebounced$=main$.filter(function(
|
|
15
|
+
*/export var removeProductFromFavoritesDebounced$=main$.filter(function(_ref4){var action=_ref4.action;return action.type===REMOVE_PRODUCT_FROM_FAVORITES;}).debounceTime(FAVORITE_BUTTON_DEBOUNCE_TIME);/**
|
|
13
16
|
* Gets triggered when any errors related to the favorite list occur.
|
|
14
17
|
* @type {Observable}
|
|
15
|
-
*/export var favoritesError$=main$.filter(function(
|
|
18
|
+
*/export var favoritesError$=main$.filter(function(_ref5){var action=_ref5.action;return[ERROR_FETCH_FAVORITES,ERROR_ADD_FAVORITES,ERROR_REMOVE_FAVORITES,ERROR_FAVORITES].includes(action.type);});/**
|
|
16
19
|
* Gets triggered when errors occur, that are only related to the frontend part of the
|
|
17
20
|
* favorite list.
|
|
18
21
|
* @type {Observable}
|
|
19
|
-
*/export var errorFavoritesLimit$=favoritesError$.filter(function(
|
|
22
|
+
*/export var errorFavoritesLimit$=favoritesError$.filter(function(_ref6){var action=_ref6.action;return action.type===ERROR_FAVORITES&&action.error&&action.error.code===FAVORITES_LIMIT_ERROR;});/**
|
|
20
23
|
* Gets triggered when the app started or when the favorites page is about to be entered.
|
|
21
24
|
* @type {Observable}
|
|
22
25
|
*/export var shouldFetchFavorites$=favoritesWillEnter$.merge(appDidStart$);/**
|
|
@@ -25,40 +28,41 @@ import{routeWillEnter$}from'@shopgate/pwa-common/streams/router';import{main$}fr
|
|
|
25
28
|
*/export var shouldFetchFreshFavorites$=userDidLogin$.merge(userDidLogout$);/**
|
|
26
29
|
* Gets triggered when the favorites updated in any way.
|
|
27
30
|
* @type {Observable}
|
|
28
|
-
*/export var favoritesDidUpdate$=main$.filter(function(
|
|
31
|
+
*/export var favoritesDidUpdate$=main$.filter(function(_ref7){var action=_ref7.action;return[REQUEST_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,RECEIVE_FAVORITES,ERROR_FETCH_FAVORITES].includes(action.type);});/**
|
|
29
32
|
* Gets triggered when an "add to favorites" action is being placed into the favorite list buffer.
|
|
30
33
|
* @type {Observable}
|
|
31
|
-
*/export var favoritesWillAddItem$=main$.filter(function(
|
|
34
|
+
*/export var favoritesWillAddItem$=main$.filter(function(_ref8){var action=_ref8.action;return action.type===REQUEST_ADD_FAVORITES;});/**
|
|
32
35
|
* Gets triggered when a single product has been successfully added to the favorite list.
|
|
33
36
|
* @type {Observable}
|
|
34
|
-
*/export var favoritesDidAddItem$=main$.filter(function(
|
|
37
|
+
*/export var favoritesDidAddItem$=main$.filter(function(_ref9){var action=_ref9.action;return action.type===SUCCESS_ADD_FAVORITES;});/**
|
|
35
38
|
* Gets triggered when a "remove from favorites" action is being placed into the favorite
|
|
36
39
|
* list buffer.
|
|
37
40
|
* @type {Observable}
|
|
38
|
-
*/export var favoritesWillRemoveItem$=main$.filter(function(
|
|
41
|
+
*/export var favoritesWillRemoveItem$=main$.filter(function(_ref10){var action=_ref10.action;return action.type===REQUEST_REMOVE_FAVORITES;});/**
|
|
39
42
|
* Gets triggered when a single product has been successfully removed from the favorite list.
|
|
40
43
|
* @type {Observable}
|
|
41
|
-
*/export var favoritesDidRemoveItem$=main$.filter(function(
|
|
44
|
+
*/export var favoritesDidRemoveItem$=main$.filter(function(_ref11){var action=_ref11.action;return action.type===SUCCESS_REMOVE_FAVORITES;});/**
|
|
42
45
|
* Gets triggered when the favorite list has successfully been received from the backend.
|
|
43
46
|
* @type {Observable}
|
|
44
|
-
*/export var receiveFavorites$=main$.filter(function(
|
|
47
|
+
*/export var receiveFavorites$=main$.filter(function(_ref12){var action=_ref12.action;return action.type===RECEIVE_FAVORITES;});export var receiveFavoritesWhileVisible$=receiveFavorites$.filter(function(_ref13){var getState=_ref13.getState;var currentPath=getCurrentPathname(getState());return currentPath===FAVORITES_PATH||currentPath===WISH_LIST_PATH;});/**
|
|
45
48
|
* Gets triggered whenever all favorite changes have been successfully processed or once when
|
|
46
49
|
* any of the buffered change requests fails.
|
|
47
50
|
* @type {Observable}
|
|
48
|
-
*/export var favoritesSyncIdle$=main$.filter(function(
|
|
51
|
+
*/export var favoritesSyncIdle$=main$.filter(function(_ref14){var action=_ref14.action;return action.type===IDLE_SYNC_FAVORITES;});/**
|
|
49
52
|
* Gets triggered after an favorites list has been added.
|
|
50
|
-
*/export var favoritesListAdded$=main$.filter(function(
|
|
53
|
+
*/export var favoritesListAdded$=main$.filter(function(_ref15){var action=_ref15.action;return action.type===SUCCESS_ADD_FAVORITES_LIST;});/**
|
|
51
54
|
* Gets triggered when the favorites should be refreshed to maintain data consistency.
|
|
52
55
|
* @type {Observable}
|
|
53
56
|
*/export var refreshFavorites$=favoritesSyncIdle$.debounceTime(FETCH_FAVORITES_THROTTLE);/**
|
|
54
|
-
* Gets triggered when a product is requested to be added
|
|
57
|
+
* Gets triggered when a product is requested to be added, removed or updated
|
|
58
|
+
* from the favorite list.
|
|
55
59
|
* @type {Observable}
|
|
56
|
-
*/export var
|
|
60
|
+
*/export var didRequestChangeFavorites$=main$.filter(function(_ref16){var action=_ref16.action;return action.type===REQUEST_ADD_FAVORITES||action.type===REQUEST_REMOVE_FAVORITES||action.type===REQUEST_UPDATE_FAVORITES;});/**
|
|
57
61
|
* Gets triggered when the favorites action buffer should be flushed immediately.
|
|
58
62
|
* @type {Observable}
|
|
59
|
-
*/export var didRequestFlushFavoritesBuffer$=main$.filter(function(
|
|
63
|
+
*/export var didRequestFlushFavoritesBuffer$=main$.filter(function(_ref17){var action=_ref17.action;return action.type===REQUEST_FLUSH_FAVORITES_BUFFER;});/**
|
|
60
64
|
* Gets triggered when the favorites buffer is supposed to be flushed after some delay time or
|
|
61
65
|
* when the `requestFlushFavoritesBuffer` action was triggered.
|
|
62
66
|
* @type {Observable}
|
|
63
|
-
*/export var didReceiveFlushFavoritesBuffer$=
|
|
67
|
+
*/export var didReceiveFlushFavoritesBuffer$=didRequestChangeFavorites$.buffer(didRequestChangeFavorites$.debounceTime(FAVORITE_ACTION_BUFFER_TIME)// Compress delayed actions into a single one
|
|
64
68
|
.merge(didRequestFlushFavoritesBuffer$));
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
/* eslint-disable extra-rules/no-single-line-objects */import{mainSubject}from'@shopgate/pwa-common/store/middelwares/streams';import{APP_DID_START,ROUTE_WILL_ENTER,SUCCESS_LOGIN,SUCCESS_LOGOUT}from'@shopgate/pwa-common/constants/ActionTypes';import{favoritesWillEnter$,addProductToFavoritesDebounced$,removeProductFromFavoritesDebounced$,favoritesError$,errorFavoritesLimit$,shouldFetchFavorites$,shouldFetchFreshFavorites$,favoritesDidUpdate$,favoritesWillAddItem$,favoritesDidAddItem$,favoritesWillRemoveItem$,favoritesDidRemoveItem$,receiveFavorites$,favoritesSyncIdle$,refreshFavorites$,
|
|
2
|
-
jest.mock('@shopgate/pwa-core',function(){return{UIEvents:{emit:jest.fn(),on:jest.fn(),addListener:jest.fn(),removeListener:jest.fn()}};});describe('Favorites streams',function(){var DUMMY_ACTION='DUMMY_ACTION';var subscriber;beforeEach(function(){subscriber=jest.fn();});describe('favoritesWillEnter$',function(){it('should call subscribers when the favorites page will open',function(){favoritesWillEnter$.subscribe(subscriber);mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:FAVORITES_PATH}}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the path does not match',function(){favoritesWillEnter$.subscribe(subscriber);mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:'/other_path'}}});expect(subscriber).toHaveBeenCalledTimes(0);});it('should not call subscribers when the action does not match',function(){favoritesWillEnter$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION,route:{pattern:FAVORITES_PATH}}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('addProductToFavoritesDebounced$',function(){afterEach(function(){jest.useRealTimers();});it('should call subscribers only once, when the action is triggered multiple times',function(){jest.useFakeTimers();addProductToFavoritesDebounced$.subscribe(subscriber);var action=addProductToFavorites('product1');mainSubject.next({action:action});mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscribers twice, when debounce time has passed',function(){jest.useFakeTimers();addProductToFavoritesDebounced$.subscribe(subscriber);var action=addProductToFavorites('product1');mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){addProductToFavoritesDebounced$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('removeProductFromFavoritesDebounced$',function(){afterEach(function(){jest.useRealTimers();});it('should call subscribers only once, when the action is triggered multiple times',function(){jest.useFakeTimers();removeProductFromFavoritesDebounced$.subscribe(subscriber);var action=removeProductFromFavorites('product1',true);mainSubject.next({action:action});mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscribers twice, when debounce time has passed',function(){jest.useFakeTimers();removeProductFromFavoritesDebounced$.subscribe(subscriber);var action=removeProductFromFavorites('product1',true);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){removeProductFromFavoritesDebounced$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesError$',function(){var actionTypes=[ERROR_FETCH_FAVORITES,ERROR_ADD_FAVORITES,ERROR_REMOVE_FAVORITES,ERROR_FAVORITES,DUMMY_ACTION];it('should call subscribers for every dispatched favorites error and no others',function(){favoritesError$.subscribe(subscriber);actionTypes.forEach(function(type){mainSubject.next({action:{type:type}});});expect(subscriber).toHaveBeenCalledTimes(4);});});describe('errorFavoritesLimit$',function(){it('should call subscribers only for the internal favorites limit error and no others',function(){errorFavoritesLimit$.subscribe(subscriber);mainSubject.next({action:{type:ERROR_FAVORITES,error:{code:FAVORITES_LIMIT_ERROR}}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){errorFavoritesLimit$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});it('should not call subscribers on any other internal favorites error',function(){errorFavoritesLimit$.subscribe(subscriber);mainSubject.next({action:{type:ERROR_FAVORITES,error:{code:'SOME_OTHER_CODE'}}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('shouldFetchFavorites$',function(){it('should call subscribers to fetch favorites on every app start and on route enter',function(){shouldFetchFavorites$.subscribe(subscriber);mainSubject.next({action:{type:APP_DID_START}});mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:FAVORITES_PATH}}});expect(subscriber).toHaveBeenCalledTimes(2);});it('should call subscribers on any other action',function(){shouldFetchFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('shouldFetchFreshFavorites$',function(){it('should call subscribers to fetch fresh favorites on every login and logout',function(){shouldFetchFreshFavorites$.subscribe(subscriber);mainSubject.next({action:{type:SUCCESS_LOGIN}});mainSubject.next({action:{type:SUCCESS_LOGOUT}});expect(subscriber).toHaveBeenCalledTimes(2);});it('should call subscribers on any other action',function(){shouldFetchFreshFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesDidUpdate$',function(){var actionTypes=[REQUEST_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,RECEIVE_FAVORITES,ERROR_FETCH_FAVORITES,DUMMY_ACTION];it('should call subscribers for every dispatched favorites update and no others',function(){favoritesDidUpdate$.subscribe(subscriber);actionTypes.forEach(function(type){mainSubject.next({action:{type:type}});});expect(subscriber).toHaveBeenCalledTimes(6);});});describe('favoritesWillAddItem$',function(){it('should call subscribers for every favorite to be added',function(){favoritesWillAddItem$.subscribe(subscriber);mainSubject.next({action:requestAddFavorites('product1')});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesWillAddItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesDidAddItem$',function(){it('should call subscribers for every favorite that was added',function(){favoritesDidAddItem$.subscribe(subscriber);mainSubject.next({action:successAddFavorites('product1')});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesDidAddItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesWillRemoveItem$',function(){it('should call subscribers for every favorite to be removed',function(){favoritesWillRemoveItem$.subscribe(subscriber);mainSubject.next({action:requestRemoveFavorites('product1')});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesWillRemoveItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesDidRemoveItem$',function(){it('should call subscribers for every favorite that was removed',function(){favoritesDidRemoveItem$.subscribe(subscriber);mainSubject.next({action:successRemoveFavorites('product1')});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesDidRemoveItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('receiveFavorites$',function(){it('should call subscribers for every receive favorites action',function(){receiveFavorites$.subscribe(subscriber);mainSubject.next({action:receiveFavorites()});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){receiveFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesSyncIdle$',function(){it('should call subscribers for every sync idle call',function(){favoritesSyncIdle$.subscribe(subscriber);mainSubject.next({action:idleSyncFavorites()});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesSyncIdle$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('refreshFavorites$',function(){afterEach(function(){jest.useRealTimers();});it('should call subscribers only once, when the action is triggered multiple times',function(){jest.useFakeTimers();refreshFavorites$.subscribe(subscriber);var action=idleSyncFavorites();mainSubject.next({action:action});mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscribers twice, when debounce time has passed',function(){jest.useFakeTimers();refreshFavorites$.subscribe(subscriber);var action=idleSyncFavorites();mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){refreshFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('didRequestAddOrRemoveFavorites$',function(){it('should call subscribers for every actual add or remove request',function(){didRequestAddOrRemoveFavorites$.subscribe(subscriber);mainSubject.next({action:requestAddFavorites('product1')});mainSubject.next({action:requestRemoveFavorites('product2',false)});expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){didRequestAddOrRemoveFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('didRequestFlushFavoritesBuffer$',function(){it('should call subscribers for every buffer flush request',function(){didRequestFlushFavoritesBuffer$.subscribe(subscriber);mainSubject.next({action:requestFlushFavoritesBuffer()});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){didRequestFlushFavoritesBuffer$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('didReceiveFlushFavoritesBuffer$',function(){it('should call subscribers with the full action buffer when the buffer period has passed',function(){jest.useFakeTimers();var bufferedActions=[{action:requestAddFavorites('product1')},{action:requestAddFavorites('product2')},{action:requestRemoveFavorites('product2',false)},{action:requestAddFavorites('product2')}];didReceiveFlushFavoritesBuffer$.subscribe(subscriber);// Pump all actions into the buffer
|
|
3
|
-
bufferedActions.forEach(function(action){
|
|
1
|
+
/* eslint-disable extra-rules/no-single-line-objects */import{mainSubject}from'@shopgate/pwa-common/store/middelwares/streams';import{APP_DID_START,ROUTE_WILL_ENTER,SUCCESS_LOGIN,SUCCESS_LOGOUT}from'@shopgate/pwa-common/constants/ActionTypes';import{favoritesWillEnter$,addProductToFavoritesDebounced$,removeProductFromFavoritesDebounced$,favoritesError$,errorFavoritesLimit$,shouldFetchFavorites$,shouldFetchFreshFavorites$,favoritesDidUpdate$,favoritesWillAddItem$,favoritesDidAddItem$,favoritesWillRemoveItem$,favoritesDidRemoveItem$,receiveFavorites$,favoritesSyncIdle$,refreshFavorites$,didRequestChangeFavorites$,didRequestFlushFavoritesBuffer$,didReceiveFlushFavoritesBuffer$}from"./index";import{FAVORITES_PATH,RECEIVE_FAVORITES,ERROR_FAVORITES,ERROR_FETCH_FAVORITES,REQUEST_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,FAVORITES_LIMIT_ERROR,FAVORITE_ACTION_BUFFER_TIME,FAVORITE_BUTTON_DEBOUNCE_TIME}from"../constants";import{addProductToFavorites,removeProductFromFavorites,requestAddFavorites,requestRemoveFavorites,successAddFavorites,successRemoveFavorites,receiveFavorites,idleSyncFavorites,requestFlushFavoritesBuffer}from"../action-creators";// Required for custom runner without env-setup
|
|
2
|
+
jest.mock('@shopgate/pwa-core',function(){return{UIEvents:{emit:jest.fn(),on:jest.fn(),addListener:jest.fn(),removeListener:jest.fn()}};});describe('Favorites streams',function(){var DUMMY_ACTION='DUMMY_ACTION';var subscriber;beforeEach(function(){subscriber=jest.fn();});describe('favoritesWillEnter$',function(){it('should call subscribers when the favorites page will open',function(){favoritesWillEnter$.subscribe(subscriber);mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:FAVORITES_PATH}}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the path does not match',function(){favoritesWillEnter$.subscribe(subscriber);mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:'/other_path'}}});expect(subscriber).toHaveBeenCalledTimes(0);});it('should not call subscribers when the action does not match',function(){favoritesWillEnter$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION,route:{pattern:FAVORITES_PATH}}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('addProductToFavoritesDebounced$',function(){afterEach(function(){jest.useRealTimers();});it('should call subscribers only once, when the action is triggered multiple times',function(){jest.useFakeTimers();addProductToFavoritesDebounced$.subscribe(subscriber);var action=addProductToFavorites('product1');mainSubject.next({action:action});mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscribers twice, when debounce time has passed',function(){jest.useFakeTimers();addProductToFavoritesDebounced$.subscribe(subscriber);var action=addProductToFavorites('product1');mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){addProductToFavoritesDebounced$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('removeProductFromFavoritesDebounced$',function(){afterEach(function(){jest.useRealTimers();});it('should call subscribers only once, when the action is triggered multiple times',function(){jest.useFakeTimers();removeProductFromFavoritesDebounced$.subscribe(subscriber);var action=removeProductFromFavorites('product1',true);mainSubject.next({action:action});mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscribers twice, when debounce time has passed',function(){jest.useFakeTimers();removeProductFromFavoritesDebounced$.subscribe(subscriber);var action=removeProductFromFavorites('product1',true);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){removeProductFromFavoritesDebounced$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesError$',function(){var actionTypes=[ERROR_FETCH_FAVORITES,ERROR_ADD_FAVORITES,ERROR_REMOVE_FAVORITES,ERROR_FAVORITES,DUMMY_ACTION];it('should call subscribers for every dispatched favorites error and no others',function(){favoritesError$.subscribe(subscriber);actionTypes.forEach(function(type){mainSubject.next({action:{type:type}});});expect(subscriber).toHaveBeenCalledTimes(4);});});describe('errorFavoritesLimit$',function(){it('should call subscribers only for the internal favorites limit error and no others',function(){errorFavoritesLimit$.subscribe(subscriber);mainSubject.next({action:{type:ERROR_FAVORITES,error:{code:FAVORITES_LIMIT_ERROR}}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){errorFavoritesLimit$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});it('should not call subscribers on any other internal favorites error',function(){errorFavoritesLimit$.subscribe(subscriber);mainSubject.next({action:{type:ERROR_FAVORITES,error:{code:'SOME_OTHER_CODE'}}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('shouldFetchFavorites$',function(){it('should call subscribers to fetch favorites on every app start and on route enter',function(){shouldFetchFavorites$.subscribe(subscriber);mainSubject.next({action:{type:APP_DID_START}});mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:FAVORITES_PATH}}});expect(subscriber).toHaveBeenCalledTimes(2);});it('should call subscribers on any other action',function(){shouldFetchFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('shouldFetchFreshFavorites$',function(){it('should call subscribers to fetch fresh favorites on every login and logout',function(){shouldFetchFreshFavorites$.subscribe(subscriber);mainSubject.next({action:{type:SUCCESS_LOGIN}});mainSubject.next({action:{type:SUCCESS_LOGOUT}});expect(subscriber).toHaveBeenCalledTimes(2);});it('should call subscribers on any other action',function(){shouldFetchFreshFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesDidUpdate$',function(){var actionTypes=[REQUEST_ADD_FAVORITES,ERROR_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,ERROR_REMOVE_FAVORITES,RECEIVE_FAVORITES,ERROR_FETCH_FAVORITES,DUMMY_ACTION];it('should call subscribers for every dispatched favorites update and no others',function(){favoritesDidUpdate$.subscribe(subscriber);actionTypes.forEach(function(type){mainSubject.next({action:{type:type}});});expect(subscriber).toHaveBeenCalledTimes(6);});});describe('favoritesWillAddItem$',function(){it('should call subscribers for every favorite to be added',function(){favoritesWillAddItem$.subscribe(subscriber);mainSubject.next({action:requestAddFavorites('product1')});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesWillAddItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesDidAddItem$',function(){it('should call subscribers for every favorite that was added',function(){favoritesDidAddItem$.subscribe(subscriber);mainSubject.next({action:successAddFavorites('product1')});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesDidAddItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesWillRemoveItem$',function(){it('should call subscribers for every favorite to be removed',function(){favoritesWillRemoveItem$.subscribe(subscriber);mainSubject.next({action:requestRemoveFavorites('product1')(function(action){return action;},function(){return{};})});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesWillRemoveItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesDidRemoveItem$',function(){it('should call subscribers for every favorite that was removed',function(){favoritesDidRemoveItem$.subscribe(subscriber);mainSubject.next({action:successRemoveFavorites('product1')});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesDidRemoveItem$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('receiveFavorites$',function(){it('should call subscribers for every receive favorites action',function(){receiveFavorites$.subscribe(subscriber);mainSubject.next({action:receiveFavorites()});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){receiveFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('favoritesSyncIdle$',function(){it('should call subscribers for every sync idle call',function(){favoritesSyncIdle$.subscribe(subscriber);mainSubject.next({action:idleSyncFavorites()});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){favoritesSyncIdle$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('refreshFavorites$',function(){afterEach(function(){jest.useRealTimers();});it('should call subscribers only once, when the action is triggered multiple times',function(){jest.useFakeTimers();refreshFavorites$.subscribe(subscriber);var action=idleSyncFavorites();mainSubject.next({action:action});mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscribers twice, when debounce time has passed',function(){jest.useFakeTimers();refreshFavorites$.subscribe(subscriber);var action=idleSyncFavorites();mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);mainSubject.next({action:action});jest.advanceTimersByTime(FAVORITE_BUTTON_DEBOUNCE_TIME);expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){refreshFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('didRequestChangeFavorites$',function(){it('should call subscribers for every actual add or remove request',function(){didRequestChangeFavorites$.subscribe(subscriber);mainSubject.next({action:requestAddFavorites('product1')});mainSubject.next({action:requestRemoveFavorites('product2',false)(function(actionInner){return actionInner;},function(){return{};})});expect(subscriber).toHaveBeenCalledTimes(2);});it('should not call subscribers when the action does not match',function(){didRequestChangeFavorites$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('didRequestFlushFavoritesBuffer$',function(){it('should call subscribers for every buffer flush request',function(){didRequestFlushFavoritesBuffer$.subscribe(subscriber);mainSubject.next({action:requestFlushFavoritesBuffer()});expect(subscriber).toHaveBeenCalledTimes(1);});it('should not call subscribers when the action does not match',function(){didRequestFlushFavoritesBuffer$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});describe('didReceiveFlushFavoritesBuffer$',function(){it('should call subscribers with the full action buffer when the buffer period has passed',function(){jest.useFakeTimers();var bufferedActions=[{action:requestAddFavorites('product1')},{action:requestAddFavorites('product2')},{action:requestRemoveFavorites('product2',false)},{action:requestAddFavorites('product2')}];didReceiveFlushFavoritesBuffer$.subscribe(subscriber);// Pump all actions into the buffer
|
|
3
|
+
bufferedActions.forEach(function(action){if(typeof(action===null||action===void 0?void 0:action.action)==='function'){// eslint-disable-next-line no-param-reassign
|
|
4
|
+
action.action=action.action(function(actionInner){return actionInner;},function(){return{};});}mainSubject.next(action);});// Trigger flush by timeout
|
|
4
5
|
jest.advanceTimersByTime(FAVORITE_ACTION_BUFFER_TIME);expect(subscriber).toHaveBeenCalledTimes(1);expect(subscriber).toHaveBeenCalledWith(bufferedActions);jest.useRealTimers();});it('should call subscribers with the full action buffer when the buffer is cleared by manual request',function(){var bufferedActions=[{action:requestAddFavorites('product1')},{action:requestAddFavorites('product2')},{action:requestRemoveFavorites('product2',false)},{action:requestAddFavorites('product2')}];didReceiveFlushFavoritesBuffer$.subscribe(subscriber);// Pump all actions into the buffer
|
|
5
|
-
bufferedActions.forEach(function(action){
|
|
6
|
+
bufferedActions.forEach(function(action){if(typeof(action===null||action===void 0?void 0:action.action)==='function'){// eslint-disable-next-line no-param-reassign
|
|
7
|
+
action.action=action.action(function(actionInner){return actionInner;},function(){return{};});}mainSubject.next(action);});// Trigger flush via manual request action
|
|
6
8
|
mainSubject.next({action:requestFlushFavoritesBuffer()});expect(subscriber).toHaveBeenCalledTimes(1);expect(subscriber).toHaveBeenCalledWith(bufferedActions);});it('should not call subscribers when the action does not match',function(){didReceiveFlushFavoritesBuffer$.subscribe(subscriber);mainSubject.next({action:{type:DUMMY_ACTION}});expect(subscriber).toHaveBeenCalledTimes(0);});});});/* eslint-enable extra-rules/no-single-line-objects */
|
|
@@ -1,31 +1,23 @@
|
|
|
1
|
-
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);});};}import pipelineDependencies from'@shopgate/pwa-core/classes/PipelineDependencies';import appConfig from'@shopgate/pwa-common/helpers/config';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{appDidStart$}from'@shopgate/pwa-common/streams';import{
|
|
1
|
+
import _regeneratorRuntime from"@babel/runtime/regenerator";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 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 pipelineDependencies from'@shopgate/pwa-core/classes/PipelineDependencies';import appConfig from'@shopgate/pwa-common/helpers/config';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{appDidStart$}from'@shopgate/pwa-common/streams';import groupBy from'lodash/groupBy';import ToastProvider from'@shopgate/pwa-common/providers/toast';import{getLoadWishlistOnAppStartEnabled,getWishlistItemQuantityEnabled}from'@shopgate/engage/core/selectors/shopSettings';import{LoadingProvider}from'@shopgate/pwa-common/providers';import{favoritesWillEnter$,shouldFetchFreshFavorites$,addProductToFavoritesDebounced$,removeProductFromFavoritesDebounced$,errorFavoritesLimit$,refreshFavorites$,didReceiveFlushFavoritesBuffer$,updateProductInFavoritesDebounced$,favoritesDidAddItem$}from"../streams";import{SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES}from"../constants/Pipelines";import addFavorites from"../actions/addFavorites";import updateFavorites from"../actions/updateFavorites";import removeFavorites from"../actions/removeFavorites";import fetchFavoritesListsWithItems from"../actions/fetchFavoritesListsWithItems";import fetchFavorites from"../actions/fetchFavorites";import{requestAddFavorites,requestRemoveFavorites,cancelRequestSyncFavorites,errorFavorites,idleSyncFavorites,requestUpdateFavorites}from"../action-creators";import{REQUEST_ADD_FAVORITES,REQUEST_REMOVE_FAVORITES,FAVORITES_LIMIT_ERROR,REQUEST_UPDATE_FAVORITES,FAVORITES_PATH}from"../constants";import{getFavoritesCount,makeGetProductRelativesOnFavorites,getFavoritesProducts}from"../selectors";/**
|
|
2
2
|
* @param {Function} subscribe Subscribes to an observable.
|
|
3
|
-
*/export default function favorites(subscribe){if(!appConfig.hasFavorites){return;}/** App start */subscribe(appDidStart$,/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref){var dispatch,
|
|
4
|
-
pipelineDependencies.set(SHOPGATE_USER_ADD_FAVORITES,[SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);pipelineDependencies.set(SHOPGATE_USER_DELETE_FAVORITES,[SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);
|
|
5
|
-
var activeProductInList=(_getFavoritesProducts=getFavoritesProducts(
|
|
6
|
-
dispatch(cancelRequestSyncFavorites(0,action.listId));return;}var _appConfig$favorites=appConfig.favorites;_appConfig$favorites=_appConfig$favorites===void 0?{}:_appConfig$favorites;var _appConfig$favorites$=_appConfig$favorites.limit,limit=_appConfig$favorites$===void 0?100:_appConfig$favorites$;var count=getFavoritesCount(
|
|
7
|
-
var error=new Error('Limit exceeded');error.code=FAVORITES_LIMIT_ERROR;dispatch(errorFavorites(action.productId,error));}else{dispatch(requestAddFavorites(action.productId,action.listId));}});subscribe(removeProductFromFavoritesDebounced$,function(
|
|
3
|
+
*/export default function favorites(subscribe){if(!appConfig.hasFavorites){return;}/** App start */subscribe(appDidStart$,/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref){var dispatch,getState,loadWishlistOnAppStartEnabled;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:dispatch=_ref.dispatch,getState=_ref.getState;// Setup sync pipeline dependencies (concurrency to each other and themselves)
|
|
4
|
+
pipelineDependencies.set(SHOPGATE_USER_ADD_FAVORITES,[SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);pipelineDependencies.set(SHOPGATE_USER_DELETE_FAVORITES,[SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);loadWishlistOnAppStartEnabled=getLoadWishlistOnAppStartEnabled(getState());if(!loadWishlistOnAppStartEnabled){_context.next=7;break;}_context.next=7;return dispatch(fetchFavoritesListsWithItems(false));case 7:case"end":return _context.stop();}}},_callee);}));return function(_x){return _ref2.apply(this,arguments);};}());/** Favorites route enter */subscribe(favoritesWillEnter$,/*#__PURE__*/function(){var _ref4=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref3){var dispatch;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:dispatch=_ref3.dispatch;_context2.next=3;return dispatch(fetchFavoritesListsWithItems(true));case 3:case"end":return _context2.stop();}}},_callee2);}));return function(_x2){return _ref4.apply(this,arguments);};}());/** User login / logout */subscribe(shouldFetchFreshFavorites$,/*#__PURE__*/function(){var _ref6=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref5){var dispatch;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:dispatch=_ref5.dispatch;_context3.next=3;return dispatch(fetchFavoritesListsWithItems(true));case 3:case"end":return _context3.stop();}}},_callee3);}));return function(_x3){return _ref6.apply(this,arguments);};}());subscribe(addProductToFavoritesDebounced$,function(_ref7){var _getFavoritesProducts;var action=_ref7.action,dispatch=_ref7.dispatch,getState=_ref7.getState;var state=getState();var wishlistItemQuantityEnabled=getWishlistItemQuantityEnabled(state);// Nothing to do, when the store already contains the item
|
|
5
|
+
var activeProductInList=(_getFavoritesProducts=getFavoritesProducts(state).byList[action.listId])===null||_getFavoritesProducts===void 0?void 0:_getFavoritesProducts.items.find(function(_ref8){var productId=_ref8.productId;return productId===action.productId;});if(activeProductInList&&!wishlistItemQuantityEnabled){// Call cancel action with "zero" count, because request was even dispatched
|
|
6
|
+
dispatch(cancelRequestSyncFavorites(0,action.listId));return;}var _appConfig$favorites=appConfig.favorites;_appConfig$favorites=_appConfig$favorites===void 0?{}:_appConfig$favorites;var _appConfig$favorites$=_appConfig$favorites.limit,limit=_appConfig$favorites$===void 0?100:_appConfig$favorites$;var count=getFavoritesCount(state);if(count>=limit){// Dispatch a local error only, because the request to add is prevented
|
|
7
|
+
var error=new Error('Limit exceeded');error.code=FAVORITES_LIMIT_ERROR;dispatch(errorFavorites(action.productId,error));}else{dispatch(requestAddFavorites(action.productId,action.listId,action.quantity,action.notes));}});subscribe(updateProductInFavoritesDebounced$,function(_ref9){var action=_ref9.action,dispatch=_ref9.dispatch;dispatch(requestUpdateFavorites(action.productId,action.listId,action.quantity,action.notes));});subscribe(removeProductFromFavoritesDebounced$,function(_ref10){var _getFavoritesProducts2;var action=_ref10.action,dispatch=_ref10.dispatch,getState=_ref10.getState;var count=getFavoritesCount(getState());if(count>0){if(action.withRelatives){// Will only handle ids which are present in the store, no additional check needed
|
|
8
8
|
var allOnList=makeGetProductRelativesOnFavorites(function(){return action.listId;})(getState(),{productId:action.productId});allOnList.forEach(function(id){return dispatch(requestRemoveFavorites(id,action.listId));});return;}// Avoids trying to remove something that was already removed (incoming fetch response)
|
|
9
|
-
var list=getFavoritesProducts(getState()).byList[action.listId];if(!(list===null||list===void 0?void 0:list.
|
|
9
|
+
var list=getFavoritesProducts(getState()).byList[action.listId];if(!(list===null||list===void 0?void 0:list.items.find(function(_ref11){var productId=_ref11.productId;return productId===action.productId;}))){// Call cancel action with "zero" count, because request was even dispatched
|
|
10
10
|
dispatch(cancelRequestSyncFavorites(0,action.listId));return;}dispatch(requestRemoveFavorites(action.productId,action.listId));}else if(!((_getFavoritesProducts2=getFavoritesProducts(getState()).byList[action.listId])===null||_getFavoritesProducts2===void 0?void 0:_getFavoritesProducts2.isFetching)){// Remove should not be possible when no favorites available
|
|
11
11
|
// Refresh to fix inconsistencies, by dispatching an idleSync action when not fetching
|
|
12
12
|
dispatch(idleSyncFavorites(action.listId));}});// Catch local limit errors (backend errors are handled autonomously)
|
|
13
|
-
subscribe(errorFavoritesLimit$,function(
|
|
13
|
+
subscribe(errorFavoritesLimit$,function(_ref12){var dispatch=_ref12.dispatch;dispatch(showModal({confirm:null,dismiss:'modal.ok',title:'modal.title_error',message:'favorites.error_limit'}));});/**
|
|
14
14
|
* Request after N seconds since last add or remove request to make sure
|
|
15
15
|
* backend did actually save it
|
|
16
|
-
*/subscribe(refreshFavorites$,/*#__PURE__*/function(){var
|
|
17
|
-
* Takes an action buffer of the request-add and request-
|
|
18
|
-
* Pipeline requests for all of them. Errors are handled autonomously.
|
|
16
|
+
*/subscribe(refreshFavorites$,/*#__PURE__*/function(){var _ref14=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(_ref13){var dispatch,action;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:dispatch=_ref13.dispatch,action=_ref13.action;if(!action.listId){_context4.next=4;break;}dispatch(fetchFavorites(true,action.listId));return _context4.abrupt("return");case 4:_context4.next=6;return dispatch(fetchFavoritesListsWithItems(true));case 6:case"end":return _context4.stop();}}},_callee4);}));return function(_x4){return _ref14.apply(this,arguments);};}());/**
|
|
17
|
+
* Takes an action buffer of the request-add, request-remove and request-update favorites actions
|
|
18
|
+
* and triggers Pipeline requests for all of them. Errors are handled autonomously.
|
|
19
19
|
* After all pipeline requests are done it resets the favorite page's state to "idle".
|
|
20
|
-
*/subscribe(didReceiveFlushFavoritesBuffer$,/*#__PURE__*/function(){var
|
|
21
|
-
dispatch=actionBuffer[0].dispatch;//
|
|
22
|
-
|
|
23
|
-
if(
|
|
24
|
-
// -> use object because of easy access and unique keys
|
|
25
|
-
if(bufferedProductIdsToSync[action.listId][action.productId]===undefined){bufferedProductIdsToSync[action.listId][action.productId]={id:action.productId,listId:action.listId,count:0};}if(action.type===REQUEST_ADD_FAVORITES){bufferedProductIdsToSync[action.listId][action.productId].count+=1;}else if(action.type===REQUEST_REMOVE_FAVORITES){bufferedProductIdsToSync[action.listId][action.productId].count-=1;}});Object.keys(bufferedProductIdsToSync).forEach(/*#__PURE__*/function(){var _ref14=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(listId){var pendingProductIdsToSync,productIdsToSync,countRemoved;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:pendingProductIdsToSync=bufferedProductIdsToSync[listId];// Filter out all products that sum up to a neutral sync state
|
|
26
|
-
productIdsToSync=Object.values(pendingProductIdsToSync).filter(function(p){return p.count!==0;});// Cancel filtered out requests (incoming_from_buffer - outgoing)
|
|
27
|
-
countRemoved=actionBuffer.length-productIdsToSync.length;if(countRemoved>0){dispatch(cancelRequestSyncFavorites(countRemoved,listId));}if(productIdsToSync.length){_context5.next=6;break;}return _context5.abrupt("return");case 6:_context5.prev=6;_context5.next=9;return Promise.all(productIdsToSync.map(function(p){if(p.count>0){return dispatch(addFavorites(p.id,listId));}return dispatch(removeFavorites(p.id,listId));}));case 9:// Add and delete handle success and failure already.
|
|
28
|
-
// Ignore 'fetching' state and force fetch every time (fetch request can be outdated)
|
|
29
|
-
dispatch(idleSyncFavorites(listId));_context5.next=15;break;case 12:_context5.prev=12;_context5.t0=_context5["catch"](6);// Errors are handled for each pipeline call. Just mark as idle here.
|
|
30
|
-
// Ignore 'fetching' state and force fetch every time (fetch request can be outdated)
|
|
31
|
-
dispatch(idleSyncFavorites(listId));case 15:case"end":return _context5.stop();}}},_callee5,null,[[6,12]]);}));return function(_x6){return _ref14.apply(this,arguments);};}());case 6:case"end":return _context6.stop();}}},_callee6);}));return function(_x5){return _ref12.apply(this,arguments);};}());}
|
|
20
|
+
*/subscribe(didReceiveFlushFavoritesBuffer$,/*#__PURE__*/function(){var _ref15=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(actionBuffer){var dispatch,actions,actionsByListAndProduct,idleLists;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:if(!(!Array.isArray(actionBuffer)||!actionBuffer.length)){_context6.next=2;break;}return _context6.abrupt("return");case 2:LoadingProvider.setLoading(FAVORITES_PATH);// All actions provide the same functionality, just take the first entry
|
|
21
|
+
dispatch=actionBuffer[0].dispatch;// Group all buffered actions by listId and productID
|
|
22
|
+
actions=actionBuffer.map(function(_ref16){var action=_ref16.action;return action;});actionsByListAndProduct=groupBy(actions,function(_ref17){var listId=_ref17.listId,productId=_ref17.productId;return"".concat(listId,"-").concat(productId,"}");});idleLists=[];_context6.next=9;return Object.values(actionsByListAndProduct).forEach(/*#__PURE__*/function(){var _ref18=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(groupedActions){var _groupedActions,_groupedActions$,productId,listId,quantity,notes,updateActions,addActions,removeActions,_updateActions$slice,_updateActions$slice2,lastUpdateAction,addRemoveBalance;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_groupedActions=_slicedToArray(groupedActions,1),_groupedActions$=_groupedActions[0];_groupedActions$=_groupedActions$===void 0?{}:_groupedActions$;productId=_groupedActions$.productId,listId=_groupedActions$.listId,quantity=_groupedActions$.quantity,notes=_groupedActions$.notes;updateActions=groupedActions.filter(function(action){return action.type===REQUEST_UPDATE_FAVORITES;});addActions=groupedActions.filter(function(action){return action.type===REQUEST_ADD_FAVORITES;});removeActions=groupedActions.filter(function(action){return action.type===REQUEST_REMOVE_FAVORITES;});_context5.prev=6;if(!(updateActions.length>0)){_context5.next=11;break;}_updateActions$slice=updateActions.slice(-1),_updateActions$slice2=_slicedToArray(_updateActions$slice,1),lastUpdateAction=_updateActions$slice2[0];_context5.next=11;return dispatch(updateFavorites(lastUpdateAction.productId,lastUpdateAction.listId,lastUpdateAction.quantity,lastUpdateAction.notes));case 11:// Sum up all adds and removes, based on sum dispatch add / remove
|
|
23
|
+
addRemoveBalance=addActions.length-removeActions.length;if(!(addRemoveBalance>0)){_context5.next=15;break;}_context5.next=15;return dispatch(addFavorites(productId,listId,quantity,notes));case 15:if(!(addRemoveBalance<0)){_context5.next=18;break;}_context5.next=18;return dispatch(removeFavorites(productId,listId,quantity,notes));case 18:if(!(updateActions.length===0&&addRemoveBalance===0)){_context5.next=22;break;}dispatch(cancelRequestSyncFavorites(groupedActions.length,listId));_context5.next=26;break;case 22:if(idleLists.includes(listId)){_context5.next=26;break;}idleLists.push(listId);_context5.next=26;return dispatch(idleSyncFavorites(listId));case 26:_context5.next=34;break;case 28:_context5.prev=28;_context5.t0=_context5["catch"](6);if(idleLists.includes(listId)){_context5.next=34;break;}idleLists.push(listId);_context5.next=34;return dispatch(idleSyncFavorites(listId));case 34:case"end":return _context5.stop();}}},_callee5,null,[[6,28]]);}));return function(_x6){return _ref18.apply(this,arguments);};}());case 9:LoadingProvider.unsetLoading(FAVORITES_PATH);case 10:case"end":return _context6.stop();}}},_callee6);}));return function(_x5){return _ref15.apply(this,arguments);};}());subscribe(favoritesDidAddItem$,function(_ref19){var events=_ref19.events;var shouldShowToast=true;if(shouldShowToast){events.emit(ToastProvider.ADD,{id:'favorites.added',message:'favorites.added'});}});}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
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);});};}import{subscribe,invoke,getSubscriptionCount,resetSubscriptions}from'@shopgate/pwa-common/subscriptions/mock';import pipelineDependencies from'@shopgate/pwa-core/classes/PipelineDependencies';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{appDidStart$}from'@shopgate/pwa-common/streams';import{favoritesWillEnter$,shouldFetchFreshFavorites$,addProductToFavoritesDebounced$,removeProductFromFavoritesDebounced$,didReceiveFlushFavoritesBuffer$,errorFavoritesLimit$,refreshFavorites$}from"../streams";import favorites from"./index";import fetchFavorites from"../actions/fetchFavorites";import addFavorites from"../actions/addFavorites";import removeFavorites from"../actions/removeFavorites";import{FAVORITES_LIMIT_ERROR}from"../constants";import{SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES}from"../constants/Pipelines";import{
|
|
2
|
-
jest.mock('@shopgate/pwa-core',function(){});jest.mock('@shopgate/pwa-common/actions/modal/showModal',function(){return jest.fn().mockReturnValue('showModal');});jest.mock('@shopgate/pwa-common-commerce/product',function(){return{fetchProductsById:jest.fn()};});var mockedDefaultListId='DEFAULT';jest.mock("../actions/fetchFavorites",function(){return jest.fn().mockReturnValue('fetchFavoritesResult');});jest.mock("../actions/fetchFavoritesList",function(){return jest.fn().mockResolvedValue([{id:'DEFAULT',name:'Wish List'}]);});// Mock all used selectors to avoid mocking the store
|
|
3
|
-
var mockedGetFavoritesProductsIdsReturnValue;var mockedGetFavoritesCountReturnValue;var mockedGetFavoritesProductsReturnValue;var mockedGetProductRelativesOnFavoritesReturnValue;jest.mock("../selectors",function(){return{getFavoritesProductsIds:jest.fn(function(){return mockedGetFavoritesProductsIdsReturnValue;}),getFavoritesProducts:jest.fn(function(){return mockedGetFavoritesProductsReturnValue;}),getFavoritesCount:jest.fn(function(){return mockedGetFavoritesCountReturnValue;}),makeGetProductRelativesOnFavorites:jest.fn(function(){return jest.fn().mockReturnValue(mockedGetProductRelativesOnFavoritesReturnValue);})};});jest.mock("../actions/addFavorites",function(){return jest.fn().mockReturnValue('addFavoritesResult');});jest.mock("../actions/removeFavorites",function(){return jest.fn().mockReturnValue('removeFavoritesResult');});var mockedHasFavorites=true;var mockedFavoritesLimit=100;jest.mock('@shopgate/pwa-common/helpers/config',function(){return{get hasFavorites(){return mockedHasFavorites;},get favorites(){return{limit:mockedFavoritesLimit};}};});/**
|
|
1
|
+
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);});};}import{subscribe,invoke,getSubscriptionCount,resetSubscriptions}from'@shopgate/pwa-common/subscriptions/mock';import pipelineDependencies from'@shopgate/pwa-core/classes/PipelineDependencies';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{appDidStart$}from'@shopgate/pwa-common/streams';import{favoritesWillEnter$,shouldFetchFreshFavorites$,addProductToFavoritesDebounced$,removeProductFromFavoritesDebounced$,didReceiveFlushFavoritesBuffer$,errorFavoritesLimit$,refreshFavorites$,updateProductInFavoritesDebounced$}from"../streams";import favorites from"./index";import fetchFavorites from"../actions/fetchFavorites";import addFavorites from"../actions/addFavorites";import removeFavorites from"../actions/removeFavorites";import updateFavorites from"../actions/updateFavorites";import{FAVORITES_LIMIT_ERROR}from"../constants";import{SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES}from"../constants/Pipelines";import{addProductToFavorites,removeProductFromFavorites,requestAddFavorites,requestRemoveFavorites,cancelRequestSyncFavorites,errorFavorites,idleSyncFavorites,updateProductInFavorites,requestUpdateFavorites}from"../action-creators";import{getFavoritesProducts,getFavoritesCount,makeGetProductRelativesOnFavorites}from"../selectors";import fetchFavoritesListsWithItems from"../actions/fetchFavoritesListsWithItems";// Required for custom runner without env-setup
|
|
2
|
+
jest.mock('@shopgate/pwa-core',function(){});jest.mock('@shopgate/pwa-common/actions/modal/showModal',function(){return jest.fn().mockReturnValue('showModal');});jest.mock('@shopgate/pwa-common-commerce/product',function(){return{fetchProductsById:jest.fn()};});jest.mock('@shopgate/pwa-common/providers',function(){return{LoadingProvider:{setLoading:jest.fn(),unsetLoading:jest.fn()}};});var mockedDefaultListId='DEFAULT';jest.mock("../actions/fetchFavorites",function(){return jest.fn().mockReturnValue('fetchFavoritesResult');});jest.mock("../actions/fetchFavoritesList",function(){return jest.fn().mockResolvedValue([{id:'DEFAULT',name:'Wish List'}]);});jest.mock("../actions/fetchFavoritesListsWithItems",function(){var original=jest.requireActual('../actions/fetchFavoritesListsWithItems');return{__esModule:true,"default":jest.fn(original["default"])};});// Mock all used selectors to avoid mocking the store
|
|
3
|
+
var mockedGetFavoritesProductsIdsReturnValue;var mockedGetFavoritesCountReturnValue;var mockedGetFavoritesProductsReturnValue;var mockedGetProductRelativesOnFavoritesReturnValue;var mockedMakeGetFavoritesReturnValue;jest.mock("../selectors",function(){return{getFavoritesProductsIds:jest.fn(function(){return mockedGetFavoritesProductsIdsReturnValue;}),getFavoritesProducts:jest.fn(function(){return mockedGetFavoritesProductsReturnValue;}),getFavoritesCount:jest.fn(function(){return mockedGetFavoritesCountReturnValue;}),makeGetFavorites:jest.fn(function(){return mockedMakeGetFavoritesReturnValue;}),makeGetProductRelativesOnFavorites:jest.fn(function(){return jest.fn().mockReturnValue(mockedGetProductRelativesOnFavoritesReturnValue);})};});jest.mock("../actions/addFavorites",function(){return jest.fn().mockReturnValue('addFavoritesResult');});jest.mock("../actions/removeFavorites",function(){return jest.fn().mockReturnValue('removeFavoritesResult');});jest.mock("../actions/updateFavorites",function(){return jest.fn().mockReturnValue('updateFavoritesResult');});var mockedHasFavorites=true;var mockedFavoritesLimit=100;jest.mock('@shopgate/pwa-common/helpers/config',function(){return{get hasFavorites(){return mockedHasFavorites;},get favorites(){return{limit:mockedFavoritesLimit};},get themeConfig(){return{};}};});/**
|
|
4
4
|
* Flushes the promise queue.
|
|
5
5
|
* @returns {Promise}
|
|
6
6
|
*/var flushPromises=function flushPromises(){return new Promise(function(resolve){return setImmediate(resolve);});};describe('Favorites - subscriptions',function(){describe('Favorites enabled',function(){var pipelineDependenciesSet=pipelineDependencies.set;beforeAll(function(){// Make sure no conflicting subscriptions exist
|
|
@@ -8,25 +8,23 @@ resetSubscriptions();// Replace singleton object property with a mock
|
|
|
8
8
|
pipelineDependencies.set=jest.fn();// Subscribe all streams
|
|
9
9
|
favorites(subscribe);});afterAll(function(){// Clean up subscriptions
|
|
10
10
|
resetSubscriptions();// Restore singleton
|
|
11
|
-
pipelineDependencies.set=pipelineDependenciesSet;});// Dispatch always resolves it's promise by default
|
|
12
|
-
var dispatch=jest.fn(function(result){
|
|
13
|
-
mockedGetFavoritesProductsIdsReturnValue=productIds;mockedGetFavoritesCountReturnValue=productIds.length;mockedGetProductRelativesOnFavoritesReturnValue=[];mockedGetFavoritesProductsReturnValue={byList:{DEFAULT:{
|
|
14
|
-
expect(pipelineDependencies.set).toHaveBeenCalledTimes(2);expect(pipelineDependencies.set.mock.calls[0][0]).toBe(SHOPGATE_USER_ADD_FAVORITES);expect(pipelineDependencies.set.mock.calls[0][1]).toEqual([SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);expect(pipelineDependencies.set.mock.calls[1][0]).toBe(SHOPGATE_USER_DELETE_FAVORITES);expect(pipelineDependencies.set.mock.calls[1][1]).toEqual([SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);});it('should fetch favorites',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return invoke(appDidStart$,{dispatch:dispatch});case 2
|
|
15
|
-
expect(
|
|
16
|
-
expect(
|
|
17
|
-
expect(
|
|
18
|
-
|
|
19
|
-
expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledTimes(2);expect(dispatch.mock.calls[0][0]).toEqual(requestRemoveFavorites(productIds[0],mockedDefaultListId));expect(dispatch.mock.calls[1][0]).toEqual(requestRemoveFavorites(productIds[1],mockedDefaultListId));});it('should cancel the remove request if the product is not on the list',function(){var productId='prod0';mockedGetProductRelativesOnFavoritesReturnValue=productIds;invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites(productId,false,mockedDefaultListId),dispatch:dispatch,getState:getState});// Don't expect any remove requests to be triggered
|
|
20
|
-
expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(0);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(cancelRequestSyncFavorites(0,mockedDefaultListId));});it('should request the removal of the single favorite item',function(){var productId='prod0';mockedGetFavoritesProductsReturnValue={byList:{DEFAULT:{ids:[].concat(mockedGetFavoritesProductsReturnValue.byList.DEFAULT.ids,[productId])}}};var mock=jest.fn(function(){return productIds;});makeGetProductRelativesOnFavorites.mockReturnValueOnce(mock);invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites(productId,false,mockedDefaultListId),dispatch:dispatch,getState:getState});// Only one removal request is expected
|
|
21
|
-
expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(0);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(requestRemoveFavorites(productId,mockedDefaultListId));});});describe('errorFavoritesLimit$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(errorFavoritesLimit$)).toBe(1);});it('should not return any value',function(){expect(invoke(errorFavoritesLimit$,{dispatch:dispatch})).toBeUndefined();});it('should dispatch an action to show a modal',function(){invoke(errorFavoritesLimit$,{dispatch:dispatch});expect(showModal).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(showModal({confirm:null,dismiss:'modal.ok',title:'modal.title_error',message:'favorites.error_limit'}));});});describe('refreshFavorites$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(refreshFavorites$)).toBe(1);});it('should not return any value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:_context7.next=2;return expect(invoke(refreshFavorites$,{dispatch:dispatch,action:{listId:mockedDefaultListId}})).resolves.toBeUndefined();case 2:case"end":return _context7.stop();}}},_callee7);})));it('should refresh favorites by fetching them without using the cache',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_context8.next=2;return invoke(refreshFavorites$,{dispatch:dispatch,action:{listId:mockedDefaultListId}});case 2:expect(fetchFavorites).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(fetchFavorites(true));case 5:case"end":return _context8.stop();}}},_callee8);})));});describe('didReceiveFlushFavoritesBuffer$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(didReceiveFlushFavoritesBuffer$)).toBe(1);});it('should not return any value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var productId;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:productId='prod1';_context9.t0=expect;_context9.next=4;return invoke(didReceiveFlushFavoritesBuffer$,null);case 4:_context9.t1=_context9.sent;(0,_context9.t0)(_context9.t1).toBeUndefined();_context9.t2=expect;_context9.next=9;return invoke(didReceiveFlushFavoritesBuffer$,[]);case 9:_context9.t3=_context9.sent;(0,_context9.t2)(_context9.t3).toBeUndefined();_context9.t4=expect;_context9.next=14;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState}]);case 14:_context9.t5=_context9.sent;(0,_context9.t4)(_context9.t5).toBeUndefined();_context9.t6=expect;_context9.next=19;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState}]);case 19:_context9.t7=_context9.sent;(0,_context9.t6)(_context9.t7).toBeUndefined();case 21:case"end":return _context9.stop();}}},_callee9);})));it('should cancel all redundant requests',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(){var productId;return _regeneratorRuntime.wrap(function _callee10$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:productId='prod1';// Add and remove the same product to make both redundant
|
|
22
|
-
_context10.next=3;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState}]);case 3:expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(cancelRequestSyncFavorites(2,mockedDefaultListId));case 5:case"end":return _context10.stop();}}},_callee10);})));it('should filter out duplicated add requests',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee11(){var productId;return _regeneratorRuntime.wrap(function _callee11$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:productId='prod1';// Add the same product twice
|
|
11
|
+
pipelineDependencies.set=pipelineDependenciesSet;});var getState=jest.fn().mockReturnValue(function(){});// Dispatch always resolves it's promise by default
|
|
12
|
+
var dispatch=jest.fn(function(result){if(typeof result==='function'){return result(dispatch,getState);}return result;});var productIds=['prod1','prod2'];var defaultListItems=[{quantity:1,notes:null,productId:productIds[0]},{quantity:1,notes:null,productId:productIds[1]}];beforeEach(function(){jest.clearAllMocks();// Reset selector return values
|
|
13
|
+
mockedGetFavoritesProductsIdsReturnValue=productIds;mockedGetFavoritesCountReturnValue=productIds.length;mockedGetProductRelativesOnFavoritesReturnValue=[];mockedGetFavoritesProductsReturnValue={byList:{DEFAULT:{items:defaultListItems,isFetching:false}}};mockedMakeGetFavoritesReturnValue=jest.fn().mockReturnValue(defaultListItems);});describe('appDidStart$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(appDidStart$)).toBe(1);});it('should not return any value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return expect(invoke(appDidStart$,{dispatch:dispatch,getState:getState})).resolves.toBeUndefined();case 2:case"end":return _context.stop();}}},_callee);})));it('should set up pipeline dependencies correctly',function(){invoke(appDidStart$,{dispatch:dispatch,getState:getState});// Expect pipeline dependencies to be set correctly
|
|
14
|
+
expect(pipelineDependencies.set).toHaveBeenCalledTimes(2);expect(pipelineDependencies.set.mock.calls[0][0]).toBe(SHOPGATE_USER_ADD_FAVORITES);expect(pipelineDependencies.set.mock.calls[0][1]).toEqual([SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);expect(pipelineDependencies.set.mock.calls[1][0]).toBe(SHOPGATE_USER_DELETE_FAVORITES);expect(pipelineDependencies.set.mock.calls[1][1]).toEqual([SHOPGATE_USER_ADD_FAVORITES,SHOPGATE_USER_DELETE_FAVORITES]);});it('should fetch favorites',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return invoke(appDidStart$,{dispatch:dispatch,getState:getState});case 2:expect(fetchFavoritesListsWithItems).toHaveBeenCalledTimes(1);expect(fetchFavoritesListsWithItems).toHaveBeenCalledWith(false);expect(dispatch).toHaveBeenCalledTimes(3);case 5:case"end":return _context2.stop();}}},_callee2);})));});describe('favoritesWillEnter$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(favoritesWillEnter$)).toBe(1);});it('should not return any value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_context3.t0=expect;_context3.next=3;return invoke(favoritesWillEnter$,{dispatch:dispatch,getState:getState});case 3:_context3.t1=_context3.sent;(0,_context3.t0)(_context3.t1).toBeUndefined();case 5:case"end":return _context3.stop();}}},_callee3);})));it('should handle fetch and map favorites',/*#__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 invoke(favoritesWillEnter$,{dispatch:dispatch,getState:getState});case 2:expect(fetchFavoritesListsWithItems).toHaveBeenCalledTimes(1);expect(fetchFavoritesListsWithItems).toHaveBeenCalledWith(true);expect(dispatch).toHaveBeenCalledTimes(3);case 5:case"end":return _context4.stop();}}},_callee4);})));});describe('shouldFetchFreshFavorites$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(shouldFetchFreshFavorites$)).toBe(1);});it('should not return any value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_context5.next=2;return expect(invoke(shouldFetchFreshFavorites$,{dispatch:dispatch})).resolves.toBeUndefined();case 2:case"end":return _context5.stop();}}},_callee5);})));it('should fetch fresh favorites without using the cache',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_context6.next=2;return invoke(shouldFetchFreshFavorites$,{dispatch:dispatch,getState:getState});case 2:expect(fetchFavoritesListsWithItems).toHaveBeenCalledTimes(1);expect(fetchFavoritesListsWithItems).toHaveBeenCalledWith(true);expect(dispatch).toHaveBeenCalledTimes(3);case 5:case"end":return _context6.stop();}}},_callee6);})));});describe('addProductToFavoritesDebounced$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(addProductToFavoritesDebounced$)).toBe(1);});it('should not return any value',function(){expect(invoke(addProductToFavoritesDebounced$,{action:addProductToFavorites('prod3'),dispatch:dispatch,getState:getState})).toBeUndefined();});it('should cancel the request when the product is already there',function(){invoke(addProductToFavoritesDebounced$,{action:addProductToFavorites('prod1',mockedDefaultListId),dispatch:dispatch,getState:getState});expect(getState).toHaveBeenCalledTimes(1);expect(getFavoritesProducts).toHaveBeenCalledWith(getState());expect(getFavoritesProducts).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(cancelRequestSyncFavorites(0,mockedDefaultListId));expect(dispatch).toHaveBeenCalledTimes(1);});it('should proceed and dispatch an error if the product is not yet on the list and the limit is reached',function(){var favoritesLimit=mockedFavoritesLimit;var productId='prod3';mockedFavoritesLimit=2;mockedGetFavoritesCountReturnValue=2;invoke(addProductToFavoritesDebounced$,{action:addProductToFavorites(productId),dispatch:dispatch,getState:getState});expect(getState).toHaveBeenCalledTimes(1);expect(getFavoritesProducts).toHaveBeenCalledWith(getState());expect(getFavoritesProducts).toHaveBeenCalledTimes(1);expect(getFavoritesCount).toHaveBeenCalledWith(getState());expect(getFavoritesCount).toHaveBeenCalledTimes(1);var error=new Error('Limit exceeded');error.code=FAVORITES_LIMIT_ERROR;expect(dispatch).toHaveBeenCalledWith(errorFavorites(productId,error));expect(dispatch).toHaveBeenCalledTimes(1);mockedFavoritesLimit=favoritesLimit;});it('should proceed and dispatch an add request if all is good',function(){var productId='prod3';invoke(addProductToFavoritesDebounced$,{action:addProductToFavorites(productId),dispatch:dispatch,getState:getState});expect(getState).toHaveBeenCalledTimes(1);expect(getFavoritesProducts).toHaveBeenCalledWith(getState());expect(getFavoritesProducts).toHaveBeenCalledTimes(1);expect(getFavoritesCount).toHaveBeenCalledWith(getState());expect(getFavoritesCount).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(requestAddFavorites(productId));expect(dispatch).toHaveBeenCalledTimes(1);});});describe('updateProductInFavoritesDebounced$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(updateProductInFavoritesDebounced$)).toBe(1);});it('should not return any value',function(){expect(invoke(updateProductInFavoritesDebounced$,{action:updateProductInFavorites('prod3'),dispatch:dispatch,getState:getState})).toBeUndefined();});it('should proceed and dispatch an add request if all is good',function(){var productId='prod3';invoke(updateProductInFavoritesDebounced$,{action:updateProductInFavorites(productId),dispatch:dispatch,getState:getState});expect(dispatch).toHaveBeenCalledWith(requestUpdateFavorites(productId));expect(dispatch).toHaveBeenCalledTimes(1);});});describe('removeProductFromFavoritesDebounced$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(removeProductFromFavoritesDebounced$)).toBe(1);});it('should not return any value',function(){expect(invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites('prod1',true,mockedDefaultListId),dispatch:dispatch,getState:getState})).toBeUndefined();expect(invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites('prod1',false,mockedDefaultListId),dispatch:dispatch,getState:getState})).toBeUndefined();});it('should not do anything if no products are on the list and currently fetching',function(){mockedGetFavoritesCountReturnValue=0;mockedGetFavoritesProductsReturnValue.isFetching=true;invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites('prod1',false,mockedDefaultListId),dispatch:dispatch,getState:getState});expect(getFavoritesCount).toHaveBeenCalledTimes(1);expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(0);expect(getFavoritesProducts).toHaveBeenCalledTimes(1);expect(getState).toHaveBeenCalledTimes(2);expect(dispatch).toHaveBeenCalledTimes(1);});it('should idle-sync when no products are on the list and not fetching',function(){mockedGetFavoritesCountReturnValue=0;invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites('prod1',false,mockedDefaultListId),dispatch:dispatch,getState:getState});expect(getFavoritesCount).toHaveBeenCalledTimes(1);expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(0);expect(getFavoritesProducts).toHaveBeenCalledTimes(1);expect(getState).toHaveBeenCalledTimes(2);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(idleSyncFavorites(mockedDefaultListId));});it('should dispatch a remove request for each relative',function(){var productId='prod0';var mock=jest.fn(function(){return productIds;});makeGetProductRelativesOnFavorites.mockReturnValueOnce(mock);invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites(productId,true,mockedDefaultListId),dispatch:dispatch,getState:getState});// Expect multiple remove requests to be dispatched
|
|
15
|
+
expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledTimes(4);expect(dispatch.mock.calls[1][0]).toEqual(requestRemoveFavorites(productIds[0],mockedDefaultListId)(dispatch,getState));expect(dispatch.mock.calls[3][0]).toEqual(requestRemoveFavorites(productIds[1],mockedDefaultListId)(dispatch,getState));});it('should cancel the remove request if the product is not on the list',function(){var productId='prod0';mockedGetProductRelativesOnFavoritesReturnValue=productIds;invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites(productId,false,mockedDefaultListId),dispatch:dispatch,getState:getState});// Don't expect any remove requests to be triggered
|
|
16
|
+
expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(0);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(cancelRequestSyncFavorites(0,mockedDefaultListId));});it('should request the removal of the single favorite item',function(){var productId='prod0';mockedGetFavoritesProductsReturnValue={byList:{DEFAULT:{items:[].concat(mockedGetFavoritesProductsReturnValue.byList.DEFAULT.items,[{productId:productId,quantity:1,notes:null}])}}};var mock=jest.fn(function(){return productIds;});makeGetProductRelativesOnFavorites.mockReturnValueOnce(mock);invoke(removeProductFromFavoritesDebounced$,{action:removeProductFromFavorites(productId,false,mockedDefaultListId),dispatch:dispatch,getState:getState});// Only one removal request is expected
|
|
17
|
+
expect(makeGetProductRelativesOnFavorites).toHaveBeenCalledTimes(0);expect(dispatch).toHaveBeenCalledTimes(2);expect(dispatch.mock.calls[1][0]).toEqual(requestRemoveFavorites(productId,mockedDefaultListId)(dispatch,getState));});});describe('errorFavoritesLimit$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(errorFavoritesLimit$)).toBe(1);});it('should not return any value',function(){expect(invoke(errorFavoritesLimit$,{dispatch:dispatch})).toBeUndefined();});it('should dispatch an action to show a modal',function(){invoke(errorFavoritesLimit$,{dispatch:dispatch});expect(showModal).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(showModal({confirm:null,dismiss:'modal.ok',title:'modal.title_error',message:'favorites.error_limit'}));});});describe('refreshFavorites$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(refreshFavorites$)).toBe(1);});it('should not return any value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:_context7.next=2;return expect(invoke(refreshFavorites$,{dispatch:dispatch,action:{listId:mockedDefaultListId}})).resolves.toBeUndefined();case 2:case"end":return _context7.stop();}}},_callee7);})));it('should refresh favorites by fetching them without using the cache',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_context8.next=2;return invoke(refreshFavorites$,{dispatch:dispatch,action:{listId:mockedDefaultListId}});case 2:expect(fetchFavorites).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(fetchFavorites(true));case 5:case"end":return _context8.stop();}}},_callee8);})));});describe('didReceiveFlushFavoritesBuffer$',function(){it('should subscribe to the stream',function(){expect(getSubscriptionCount(didReceiveFlushFavoritesBuffer$)).toBe(1);});it('should not return any value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var productId;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:productId='prod1';_context9.t0=expect;_context9.next=4;return invoke(didReceiveFlushFavoritesBuffer$,null);case 4:_context9.t1=_context9.sent;(0,_context9.t0)(_context9.t1).toBeUndefined();_context9.t2=expect;_context9.next=9;return invoke(didReceiveFlushFavoritesBuffer$,[]);case 9:_context9.t3=_context9.sent;(0,_context9.t2)(_context9.t3).toBeUndefined();_context9.t4=expect;_context9.next=14;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState}]);case 14:_context9.t5=_context9.sent;(0,_context9.t4)(_context9.t5).toBeUndefined();_context9.t6=expect;_context9.next=19;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestUpdateFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites(productId,mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState}]);case 19:_context9.t7=_context9.sent;(0,_context9.t6)(_context9.t7).toBeUndefined();case 21:case"end":return _context9.stop();}}},_callee9);})));it('should cancel all redundant requests',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(){var productId;return _regeneratorRuntime.wrap(function _callee10$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:productId='prod1';// Add and remove the same product to make both redundant
|
|
18
|
+
_context10.next=3;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites(productId,mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState}]);case 3:expect(dispatch).toHaveBeenCalledTimes(2);expect(dispatch).toHaveBeenCalledWith(cancelRequestSyncFavorites(2,mockedDefaultListId));case 5:case"end":return _context10.stop();}}},_callee10);})));it('should filter out duplicated add requests',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee11(){var productId;return _regeneratorRuntime.wrap(function _callee11$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:productId='prod1';// Add the same product twice
|
|
23
19
|
_context11.next=3;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestAddFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState}]);case 3:_context11.next=5;return flushPromises();case 5:// One cancel and one add action call as well as one idle-sync afterwards
|
|
24
|
-
expect(addFavorites).toHaveBeenCalledTimes(1);expect(addFavorites.mock.calls[0][0]).toBe(productId);expect(dispatch).toHaveBeenCalledTimes(
|
|
25
|
-
_context12.next=3;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestRemoveFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites(productId,mockedDefaultListId),dispatch:dispatch,getState:getState}]);case 3:_context12.next=5;return flushPromises();case 5:// One cancel and one add action call as well as one idle-sync afterwards
|
|
26
|
-
expect(removeFavorites).toHaveBeenCalledTimes(1);expect(removeFavorites.mock.calls[0][0]).toBe(productId);expect(dispatch).toHaveBeenCalledTimes(
|
|
27
|
-
expect(addFavorites).toHaveBeenCalledTimes(2);expect(addFavorites.mock.calls[0][0]).toBe('prod3');expect(addFavorites.mock.calls[1][0]).toBe('prod4');expect(removeFavorites).toHaveBeenCalledTimes(2);expect(removeFavorites.mock.calls[0][0]).toBe('prod1');expect(removeFavorites.mock.calls[1][0]).toBe('prod2');expect(dispatch).toHaveBeenCalledTimes(
|
|
28
|
-
dispatch:dispatch,getState:getState},{action:
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
20
|
+
expect(addFavorites).toHaveBeenCalledTimes(1);expect(addFavorites.mock.calls[0][0]).toBe(productId);expect(dispatch).toHaveBeenCalledTimes(2);expect(dispatch.mock.calls[0][0]).toEqual(addFavorites());expect(dispatch.mock.calls[1][0]).toEqual(idleSyncFavorites(mockedDefaultListId));case 10:case"end":return _context11.stop();}}},_callee11);})));it('should filter out duplicated remove requests',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee12(){var productId;return _regeneratorRuntime.wrap(function _callee12$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:productId='prod1';// Remove the same product twice
|
|
21
|
+
_context12.next=3;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestRemoveFavorites(productId,mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites(productId,mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState}]);case 3:_context12.next=5;return flushPromises();case 5:// One cancel and one add action call as well as one idle-sync afterwards
|
|
22
|
+
expect(removeFavorites).toHaveBeenCalledTimes(1);expect(removeFavorites.mock.calls[0][0]).toBe(productId);expect(dispatch).toHaveBeenCalledTimes(4);expect(dispatch.mock.calls[2][0]).toEqual(removeFavorites());expect(dispatch.mock.calls[3][0]).toEqual(idleSyncFavorites(mockedDefaultListId));case 10:case"end":return _context12.stop();}}},_callee12);})));it('should not filter out unique add or remove requests',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee13(){return _regeneratorRuntime.wrap(function _callee13$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:_context13.next=2;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites('prod3',mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestAddFavorites('prod4',mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites('prod1',mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites('prod2',mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState}]);case 2:_context13.next=4;return flushPromises();case 4:// Only dispatch add and remove actions, no cancellation
|
|
23
|
+
expect(addFavorites).toHaveBeenCalledTimes(2);expect(addFavorites.mock.calls[0][0]).toBe('prod3');expect(addFavorites.mock.calls[1][0]).toBe('prod4');expect(removeFavorites).toHaveBeenCalledTimes(2);expect(removeFavorites.mock.calls[0][0]).toBe('prod1');expect(removeFavorites.mock.calls[1][0]).toBe('prod2');expect(dispatch).toHaveBeenCalledTimes(7);expect(dispatch.mock.calls[2][0]).toEqual(addFavorites());expect(dispatch.mock.calls[3][0]).toEqual(addFavorites());expect(dispatch.mock.calls[4][0]).toEqual(removeFavorites());expect(dispatch.mock.calls[5][0]).toEqual(removeFavorites());expect(dispatch.mock.calls[6][0]).toEqual(idleSyncFavorites(mockedDefaultListId));case 16:case"end":return _context13.stop();}}},_callee13);})));it('should filter out duplicated update requests',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee14(){var productId;return _regeneratorRuntime.wrap(function _callee14$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:productId='prod1';// Add the same product twice
|
|
24
|
+
_context14.next=3;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestUpdateFavorites(productId,mockedDefaultListId,2),dispatch:dispatch,getState:getState},{action:requestUpdateFavorites(productId,mockedDefaultListId,3),dispatch:dispatch,getState:getState}]);case 3:_context14.next=5;return flushPromises();case 5:// One cancel and one add action call as well as one idle-sync afterwards
|
|
25
|
+
expect(updateFavorites).toHaveBeenCalledTimes(1);expect(updateFavorites.mock.calls[0][0]).toBe(productId);expect(updateFavorites.mock.calls[0][1]).toBe(mockedDefaultListId);expect(updateFavorites.mock.calls[0][2]).toBe(3);expect(dispatch).toHaveBeenCalledTimes(2);expect(dispatch.mock.calls[0][0]).toEqual(updateFavorites());expect(dispatch.mock.calls[1][0]).toEqual(idleSyncFavorites(mockedDefaultListId));case 12:case"end":return _context14.stop();}}},_callee14);})));it('should properly handle conflicts and duplicates when they occur at once',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee15(){return _regeneratorRuntime.wrap(function _callee15$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:_context15.next=2;return invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites('prod3',mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestAddFavorites('prod4',mockedDefaultListId),dispatch:dispatch,getState:getState},{action:requestAddFavorites('prod4',mockedDefaultListId),// duplicated
|
|
26
|
+
dispatch:dispatch,getState:getState},{action:requestRemoveFavorites('prod1',mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState},{action:requestAddFavorites('prod1',mockedDefaultListId),// conflict
|
|
27
|
+
dispatch:dispatch,getState:getState},{action:requestRemoveFavorites('prod2',mockedDefaultListId)(dispatch,getState),dispatch:dispatch,getState:getState}]);case 2:_context15.next=4;return flushPromises();case 4:// Cancel three calls (conflict -> 2 + duplicate -> 1 => 3), handle the rest
|
|
28
|
+
expect(addFavorites).toHaveBeenCalledTimes(2);expect(addFavorites.mock.calls[0][0]).toBe('prod3');expect(addFavorites.mock.calls[1][0]).toBe('prod4');expect(removeFavorites).toHaveBeenCalledTimes(1);expect(removeFavorites.mock.calls[0][0]).toBe('prod2');expect(dispatch).toHaveBeenCalledTimes(7);expect(dispatch.mock.calls[2][0]).toEqual(addFavorites());expect(dispatch.mock.calls[3][0]).toEqual(addFavorites());expect(dispatch.mock.calls[4][0]).toEqual(cancelRequestSyncFavorites(2,mockedDefaultListId));expect(dispatch.mock.calls[5][0]).toEqual(removeFavorites());expect(dispatch.mock.calls[6][0]).toEqual(idleSyncFavorites(mockedDefaultListId));case 15:case"end":return _context15.stop();}}},_callee15);})));it('should not break on any failing request',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee17(){return _regeneratorRuntime.wrap(function _callee17$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:dispatch.mockImplementation(/*#__PURE__*/function(){var _ref17=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee16(action){return _regeneratorRuntime.wrap(function _callee16$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:if(!(action===addFavorites()||action===removeFavorites()||action===updateFavorites())){_context16.next=2;break;}throw new Error('Failed to add/remove favorite');case 2:case"end":return _context16.stop();}}},_callee16);}));return function(_x){return _ref17.apply(this,arguments);};}());// Remove the same product twice
|
|
29
|
+
_context17.next=3;return expect(invoke(didReceiveFlushFavoritesBuffer$,[{action:requestAddFavorites('prod3'),dispatch:dispatch,getState:getState},{action:requestUpdateFavorites('prod3'),dispatch:dispatch,getState:getState},{action:requestRemoveFavorites('prod1')(dispatch,getState),dispatch:dispatch,getState:getState}])).resolves.toBeUndefined();case 3:case"end":return _context17.stop();}}},_callee17);})));it('should dispatch only the requests and one idle-sync if any error occurs',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee19(){return _regeneratorRuntime.wrap(function _callee19$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:dispatch.mockImplementation(/*#__PURE__*/function(){var _ref19=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee18(action){return _regeneratorRuntime.wrap(function _callee18$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:if(!(action===addFavorites()||action===updateFavorites()||action===removeFavorites())){_context18.next=2;break;}throw new Error('Failed to add/remove favorite');case 2:if(!(typeof action==='function')){_context18.next=4;break;}return _context18.abrupt("return",action(dispatch,getState));case 4:return _context18.abrupt("return",action);case 5:case"end":return _context18.stop();}}},_callee18);}));return function(_x2){return _ref19.apply(this,arguments);};}());// Remove the same product twice
|
|
30
|
+
_context19.t0=invoke;_context19.t1=didReceiveFlushFavoritesBuffer$;_context19.t2={action:requestAddFavorites('prod3',mockedDefaultListId),dispatch:dispatch,getState:getState};_context19.t3={action:requestUpdateFavorites('prod2',mockedDefaultListId,3),dispatch:dispatch,getState:getState};_context19.next=7;return requestRemoveFavorites('prod1',mockedDefaultListId)(dispatch,getState);case 7:_context19.t4=_context19.sent;_context19.t5=dispatch;_context19.t6=getState;_context19.t7={action:_context19.t4,dispatch:_context19.t5,getState:_context19.t6};_context19.t8=[_context19.t2,_context19.t3,_context19.t7];_context19.next=14;return(0,_context19.t0)(_context19.t1,_context19.t8);case 14:_context19.next=16;return flushPromises();case 16:expect(dispatch).toHaveBeenCalledTimes(5);expect(dispatch.mock.calls[1][0]).toEqual(addFavorites());expect(dispatch.mock.calls[2][0]).toEqual(updateFavorites());expect(dispatch.mock.calls[3][0]).toEqual(removeFavorites());expect(dispatch.mock.calls[4][0]).toEqual(idleSyncFavorites(mockedDefaultListId));case 21:case"end":return _context19.stop();}}},_callee19);})));});});describe('Favorites disabled',function(){it('should not subscribe to anything',function(){var hasFavorites=mockedHasFavorites;mockedHasFavorites=false;favorites(subscribe);expect(getSubscriptionCount()).toBe(0);mockedHasFavorites=hasFavorites;});});});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shopgate/pwa-common-commerce",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.9.0-beta.2",
|
|
4
4
|
"description": "Commerce library for the Shopgate Connect PWA.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Shopgate <support@shopgate.com>",
|
|
@@ -19,8 +19,8 @@
|
|
|
19
19
|
"reselect": "^3.0.1"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
|
-
"@shopgate/pwa-common": "7.
|
|
23
|
-
"@shopgate/pwa-core": "7.
|
|
22
|
+
"@shopgate/pwa-common": "7.9.0-beta.2",
|
|
23
|
+
"@shopgate/pwa-core": "7.9.0-beta.2",
|
|
24
24
|
"lodash": "^4.17.4",
|
|
25
25
|
"react": "~16.12.0",
|
|
26
26
|
"react-dom": "~16.12.0"
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
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{RECEIVE_PRODUCTS}from"../constants";/**
|
|
1
|
+
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 _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}import{RECEIVE_PRODUCTS}from"../constants";/**
|
|
2
2
|
* Creates the dispatched RECEIVE_PRODUCTS action object.
|
|
3
3
|
* @param {Object} payload The action payload.
|
|
4
4
|
* @param {string} payload.hash The store hash.
|
|
5
5
|
* @param {Object} payload.params The criteria of the products received.
|
|
6
6
|
* @param {Object} payload.products The data of the received products.
|
|
7
7
|
* @param {boolean} payload.cached If the result should be cached.
|
|
8
|
+
* @param {boolean} [payload.fetchInventory=true] If the inventory needs to be fetched after
|
|
9
|
+
* products where received.
|
|
8
10
|
* @return {Object} The RECEIVE_PRODUCTS action.
|
|
9
|
-
*/var receiveProducts=function receiveProducts(payload){return _extends({type:RECEIVE_PRODUCTS},
|
|
11
|
+
*/var receiveProducts=function receiveProducts(payload){var _payload$fetchInvento=payload.fetchInventory,fetchInventory=_payload$fetchInvento===void 0?true:_payload$fetchInvento,rest=_objectWithoutProperties(payload,["fetchInventory"]);return _extends({type:RECEIVE_PRODUCTS},rest,{fetchInventory:fetchInventory});};export default receiveProducts;
|