@shopgate/engage 6.22.0-beta.1 → 6.22.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/app-rating/action-creators/appStart.js +3 -3
- package/app-rating/action-creators/ordersPlaced.js +3 -3
- package/app-rating/action-creators/popup.js +4 -4
- package/app-rating/action-creators/timer.js +3 -3
- package/app-rating/actions/showModal.js +2 -2
- package/app-rating/constants/index.js +2 -2
- package/app-rating/reducers/index.js +2 -2
- package/app-rating/subscriptions/index.js +2 -2
- package/core/actions/__tests__/grantPermissions.spec.js +4 -4
- package/core/actions/grantPermissions.js +3 -3
- package/package.json +7 -7
- package/push-opt-in/action-creators/index.js +1 -0
- package/push-opt-in/action-creators/optInTrigger.js +23 -0
- package/push-opt-in/actions/index.js +1 -0
- package/push-opt-in/actions/optInTrigger.js +6 -0
- package/push-opt-in/constants/index.js +1 -0
- package/push-opt-in/constants/optInTrigger.js +1 -0
- package/push-opt-in/reducers/index.js +1 -0
- package/push-opt-in/reducers/optInTrigger.js +6 -0
- package/push-opt-in/selectors/index.js +1 -0
- package/push-opt-in/selectors/optInTrigger.js +5 -0
- package/push-opt-in/subscriptions/index.js +1 -0
- package/push-opt-in/subscriptions/optInTrigger.js +12 -0
- package/push-opt-in/subscriptions/optInTrigger.spec.js +41 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{APP_RATING_RESET_APP_START_COUNT,APP_RATING_INCREASE_APP_START_COUNT}from"../constants";/**
|
|
2
2
|
* Increment the app start count
|
|
3
3
|
* @return {Object} The dispatched action object.
|
|
4
|
-
*/export var increaseAppStartCount=function increaseAppStartCount(){return{type:
|
|
4
|
+
*/export var increaseAppStartCount=function increaseAppStartCount(){return{type:APP_RATING_INCREASE_APP_START_COUNT};};/**
|
|
5
5
|
* Reset the app start count, and increment reset counts
|
|
6
6
|
* @return {Object} The dispatched action object.
|
|
7
|
-
*/export var resetAppStartCount=function resetAppStartCount(){return{type:
|
|
7
|
+
*/export var resetAppStartCount=function resetAppStartCount(){return{type:APP_RATING_RESET_APP_START_COUNT};};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{APP_RATING_RESET_ORDERS_PLACED_COUNT,APP_RATING_INCREASE_ORDERS_PLACED_COUNT}from"../constants";/**
|
|
2
2
|
* Increment the orders placed count
|
|
3
3
|
* @return {Object} The dispatched action object.
|
|
4
|
-
*/export var increaseOrdersPlacedCount=function increaseOrdersPlacedCount(){return{type:
|
|
4
|
+
*/export var increaseOrdersPlacedCount=function increaseOrdersPlacedCount(){return{type:APP_RATING_INCREASE_ORDERS_PLACED_COUNT};};/**
|
|
5
5
|
* Reset the orders placed count, and increment reset counts
|
|
6
6
|
* @return {Object} The dispatched action object.
|
|
7
|
-
*/export var resetOrdersPlacedCount=function resetOrdersPlacedCount(){return{type:
|
|
7
|
+
*/export var resetOrdersPlacedCount=function resetOrdersPlacedCount(){return{type:APP_RATING_RESET_ORDERS_PLACED_COUNT};};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{APP_RATING_INCREASE_REJECTION_COUNT,APP_RATING_SET_ALREADY_RATED,APP_RATING_SET_LAST_POPUP_TIMESTAMP}from"../constants";/**
|
|
2
2
|
* Sets the last popup timestamp
|
|
3
3
|
* @return {Object} The dispatched action object.
|
|
4
|
-
*/export var setLastPopupTimestamp=function setLastPopupTimestamp(){return{type:
|
|
4
|
+
*/export var setLastPopupTimestamp=function setLastPopupTimestamp(){return{type:APP_RATING_SET_LAST_POPUP_TIMESTAMP};};/**
|
|
5
5
|
* Sets the last popup timestamp
|
|
6
6
|
* @return {Object} The dispatched action object.
|
|
7
|
-
*/export var increaseRejectionCount=function increaseRejectionCount(){return{type:
|
|
7
|
+
*/export var increaseRejectionCount=function increaseRejectionCount(){return{type:APP_RATING_INCREASE_REJECTION_COUNT};};/**
|
|
8
8
|
* Sets the last popup timestamp
|
|
9
9
|
* @param {boolean} to the value to set the rated status
|
|
10
10
|
* @return {Object} The dispatched action object.
|
|
11
|
-
*/export var setAlreadyRated=function setAlreadyRated(to){return{type:
|
|
11
|
+
*/export var setAlreadyRated=function setAlreadyRated(to){return{type:APP_RATING_SET_ALREADY_RATED,to:to};};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{APP_RATING_SET_TIMER_START_TIME,APP_RATING_INCREASE_TIMER_REPEATS}from"../constants";/**
|
|
2
2
|
* Reset the orders placed count, and increment reset counts
|
|
3
3
|
* @return {Object} The dispatched action object.
|
|
4
|
-
*/export var resetTimerState=function resetTimerState(){return{type:
|
|
4
|
+
*/export var resetTimerState=function resetTimerState(){return{type:APP_RATING_INCREASE_TIMER_REPEATS};};/**
|
|
5
5
|
* Sets the timer start time
|
|
6
6
|
* @return {Object} The dispatched action object.
|
|
7
|
-
*/export var setTimerStartTime=function setTimerStartTime(){return{type:
|
|
7
|
+
*/export var setTimerStartTime=function setTimerStartTime(){return{type:APP_RATING_SET_TIMER_START_TIME};};
|
|
@@ -1,4 +1,4 @@
|
|
|
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);});};}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 showModalAction from'@shopgate/pwa-common/actions/modal/showModal';import{getPlatform}from'@shopgate/pwa-common/selectors/client';import{historyPush}from'@shopgate/pwa-common/actions/router';import appConfig from'@shopgate/pwa-common/helpers/config';import{track}from'@shopgate/pwa-tracking/helpers';import{increaseRejectionCount,setAlreadyRated,setLastPopupTimestamp}from"../action-creators/popup";import{generateReviewLink}from"../helpers";import{
|
|
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);});};}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 showModalAction from'@shopgate/pwa-common/actions/modal/showModal';import{getPlatform}from'@shopgate/pwa-common/selectors/client';import{historyPush}from'@shopgate/pwa-common/actions/router';import appConfig from'@shopgate/pwa-common/helpers/config';import{track}from'@shopgate/pwa-tracking/helpers';import{increaseRejectionCount,setAlreadyRated,setLastPopupTimestamp}from"../action-creators/popup";import{generateReviewLink}from"../helpers";import{APP_RATING_TIMER_TIMESPAN}from"../constants";import{getAppRatingState}from"../selectors/appRating";var _appConfig$appRating=appConfig.appRating,bundleId=_appConfig$appRating.bundleId,minDaysBetweenPopups=_appConfig$appRating.minDaysBetweenPopups,askForFeedback=_appConfig$appRating.askForFeedback,feedbackLink=_appConfig$appRating.feedbackLink;/**
|
|
2
2
|
* to handle the modal confirmation
|
|
3
3
|
* @param {string} url the url to redirect to
|
|
4
4
|
* @param {boolean | null} setRated the url to redirect to
|
|
@@ -11,7 +11,7 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
|
|
|
11
11
|
* @param {boolean} hasRepeats if the counters has repeats
|
|
12
12
|
* @return {(function(*, *): void)|*}
|
|
13
13
|
*/export function showModal(resetAction,increaseAction,mustShow,hasRepeats){return/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var state,platform,reviewLink,appRatingState,isMinDaysBetweenPopupsElapsed,firstModalConfirmed,userGivesFeedback;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:state=getState();platform=getPlatform(state);reviewLink=generateReviewLink(bundleId[platform],platform);// no review link for current platform found -> don't show modal
|
|
14
|
-
if(reviewLink){_context.next=5;break;}return _context.abrupt("return");case 5:if(!mustShow&&hasRepeats&&increaseAction){dispatch(increaseAction());}if(mustShow&&hasRepeats){_context.next=8;break;}return _context.abrupt("return");case 8:appRatingState=getAppRatingState(state);isMinDaysBetweenPopupsElapsed=Date.now()-appRatingState.lastPopupAt>=minDaysBetweenPopups*
|
|
14
|
+
if(reviewLink){_context.next=5;break;}return _context.abrupt("return");case 5:if(!mustShow&&hasRepeats&&increaseAction){dispatch(increaseAction());}if(mustShow&&hasRepeats){_context.next=8;break;}return _context.abrupt("return");case 8:appRatingState=getAppRatingState(state);isMinDaysBetweenPopupsElapsed=Date.now()-appRatingState.lastPopupAt>=minDaysBetweenPopups*APP_RATING_TIMER_TIMESPAN;if(isMinDaysBetweenPopupsElapsed){_context.next=12;break;}return _context.abrupt("return");case 12:dispatch(resetAction());dispatch(setLastPopupTimestamp());_context.next=16;return dispatch(showModalAction({confirm:'appRating.yes',dismiss:'appRating.no',title:'appRating.title',message:'appRating.message'}));case 16:firstModalConfirmed=_context.sent;track('customEvent',{eventCategory:'appReviewPrompt',eventAction:'decision',eventLabel:firstModalConfirmed?'yes':'no'},state);// user touched yes and we
|
|
15
15
|
// redirect to store
|
|
16
16
|
if(!firstModalConfirmed){_context.next=21;break;}dispatch(redirectTo(reviewLink,true));return _context.abrupt("return");case 21:// user doesn't want to rate
|
|
17
17
|
dispatch(increaseRejectionCount());// we approve for rejection
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export var
|
|
2
|
-
export var
|
|
1
|
+
export var APP_RATING_INCREASE_APP_START_COUNT='APP_RATING_INCREASE_APP_START_COUNT';export var APP_RATING_RESET_APP_START_COUNT='APP_RATING_RESET_APP_START_COUNT';export var APP_RATING_RESET_APP_START_STATE='APP_RATING_RESET_APP_START_STATE';export var APP_RATING_INCREASE_ORDERS_PLACED_COUNT='APP_RATING_INCREASE_ORDERS_PLACED_COUNT';export var APP_RATING_RESET_ORDERS_PLACED_COUNT='APP_RATING_RESET_ORDERS_PLACED_COUNT';export var APP_RATING_RESET_ORDERS_PLACED_STATE='APP_RATING_RESET_ORDERS_PLACED_STATE';export var APP_RATING_INCREASE_TIMER_REPEATS='APP_RATING_INCREASE_TIMER_REPEATS';export var APP_RATING_SET_TIMER_START_TIME='APP_RATING_SET_TIMER_START_TIME';export var APP_RATING_SET_LAST_POPUP_TIMESTAMP='APP_RATING_SET_LAST_POPUP_TIMESTAMP';export var APP_RATING_INCREASE_REJECTION_COUNT='APP_RATING_INCREASE_REJECTION_COUNT';export var APP_RATING_SET_ALREADY_RATED='APP_RATING_SET_ALREADY_RATED';// currently the timespan is set to a day
|
|
2
|
+
export var APP_RATING_TIMER_TIMESPAN=1000*60*60*24;
|
|
@@ -1,6 +1,6 @@
|
|
|
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{
|
|
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{APP_RATING_INCREASE_APP_START_COUNT,APP_RATING_RESET_APP_START_STATE,APP_RATING_RESET_APP_START_COUNT,APP_RATING_INCREASE_ORDERS_PLACED_COUNT,APP_RATING_RESET_ORDERS_PLACED_COUNT,APP_RATING_RESET_ORDERS_PLACED_STATE,APP_RATING_INCREASE_TIMER_REPEATS,APP_RATING_SET_TIMER_START_TIME,APP_RATING_SET_LAST_POPUP_TIMESTAMP,APP_RATING_INCREASE_REJECTION_COUNT,APP_RATING_SET_ALREADY_RATED}from"../constants";var defaultState={appStartCount:0,appStartResetCount:0,ordersPlacedCount:0,ordersPlacedResetCount:0,timerRepeatsCount:0,timerStartTimestamp:null,lastPopupAt:null,rejectionCount:0,alreadyRated:false};/**
|
|
2
2
|
* Stores all the app rating states.
|
|
3
3
|
* @param {Object} [state] The current state.
|
|
4
4
|
* @param {Object} action The action object.
|
|
5
5
|
* @return {Object} The new state.
|
|
6
|
-
*/export default(function(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultState;var action=arguments.length>1?arguments[1]:undefined;switch(action.type){case
|
|
6
|
+
*/export default(function(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultState;var action=arguments.length>1?arguments[1]:undefined;switch(action.type){case APP_RATING_INCREASE_APP_START_COUNT:{return _extends({},state,{appStartCount:state.appStartCount+1});}case APP_RATING_RESET_APP_START_COUNT:{return _extends({},state,{appStartCount:0,appStartResetCount:state.appStartResetCount+1});}case APP_RATING_RESET_APP_START_STATE:{return _extends({},state,{appStartCount:0,appStartResetCount:0});}case APP_RATING_INCREASE_ORDERS_PLACED_COUNT:{return _extends({},state,{ordersPlacedCount:state.ordersPlacedCount+1});}case APP_RATING_RESET_ORDERS_PLACED_COUNT:{return _extends({},state,{ordersPlacedCount:0,ordersPlacedResetCount:state.ordersPlacedResetCount+1});}case APP_RATING_RESET_ORDERS_PLACED_STATE:{return _extends({},state,{ordersPlacedCount:0,ordersPlacedResetCount:0});}case APP_RATING_INCREASE_TIMER_REPEATS:{return _extends({},state,{timerRepeatsCount:state.timerRepeatsCount+1});}case APP_RATING_SET_TIMER_START_TIME:{return _extends({},state,{timerStartTimestamp:Date.now()});}case APP_RATING_SET_LAST_POPUP_TIMESTAMP:{return _extends({},state,{lastPopupAt:Date.now()});}case APP_RATING_INCREASE_REJECTION_COUNT:{return _extends({},state,{rejectionCount:state.rejectionCount+1});}case APP_RATING_SET_ALREADY_RATED:{return _extends({},state,{alreadyRated:action.to});}default:return state;}});
|
|
@@ -1,4 +1,4 @@
|
|
|
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 appConfig from'@shopgate/pwa-common/helpers/config';import{appDidStart$}from'@shopgate/pwa-common/streams/app';import event from'@shopgate/pwa-core/classes/Event';import{increaseAppStartCount,resetAppStartCount}from"../action-creators/appStart";import{increaseOrdersPlacedCount,resetOrdersPlacedCount}from"../action-creators/ordersPlaced";import{resetTimerState,setTimerStartTime}from"../action-creators/timer";import{
|
|
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 appConfig from'@shopgate/pwa-common/helpers/config';import{appDidStart$}from'@shopgate/pwa-common/streams/app';import event from'@shopgate/pwa-core/classes/Event';import{increaseAppStartCount,resetAppStartCount}from"../action-creators/appStart";import{increaseOrdersPlacedCount,resetOrdersPlacedCount}from"../action-creators/ordersPlaced";import{resetTimerState,setTimerStartTime}from"../action-creators/timer";import{APP_RATING_TIMER_TIMESPAN}from"../constants";import{getAppRatingState}from"../selectors/appRating";import{showModal}from"../actions/showModal";/**
|
|
2
2
|
* App rating subscriptions
|
|
3
3
|
* @param {Function} subscribe The subscribe function
|
|
4
4
|
*/export default function appRating(subscribe){var _appConfig$appRating=appConfig.appRating,appStarts=_appConfig$appRating.appStarts,ordersPlaced=_appConfig$appRating.ordersPlaced,timeInterval=_appConfig$appRating.timeInterval,rejectionMaxCount=_appConfig$appRating.rejectionMaxCount,bundleId=_appConfig$appRating.bundleId;// even subscriber to handle app start ratings
|
|
@@ -9,7 +9,7 @@ dispatch(increaseAppStartCount());state=getAppRatingState(getState());// if the
|
|
|
9
9
|
// we'll cancel the operations as we
|
|
10
10
|
// don't have to show the modal once more
|
|
11
11
|
if(!state.alreadyRated){_context.next=7;break;}return _context.abrupt("return");case 7:if(!(state.rejectionCount>=rejectionMaxCount)){_context.next=9;break;}return _context.abrupt("return");case 9:// initiate the first start time
|
|
12
|
-
if(state.timerStartTimestamp===null){dispatch(setTimerStartTime());}mustShowModal=false;hasRepeats=false;resetAction=null;increaseAction=null;if(timeInterval&&Number(timeInterval.value)>0&&Number(state.timerStartTimestamp)>0&&Date.now()-state.timerStartTimestamp>=timeInterval.value*
|
|
12
|
+
if(state.timerStartTimestamp===null){dispatch(setTimerStartTime());}mustShowModal=false;hasRepeats=false;resetAction=null;increaseAction=null;if(timeInterval&&Number(timeInterval.value)>0&&Number(state.timerStartTimestamp)>0&&Date.now()-state.timerStartTimestamp>=timeInterval.value*APP_RATING_TIMER_TIMESPAN){mustShowModal=true;hasRepeats=timeInterval.repeats===null||state.timerRepeatsCount<=timeInterval.repeats;resetAction=resetTimerState;// since the time is elapsed
|
|
13
13
|
// we reset the starting time
|
|
14
14
|
increaseAction=setTimerStartTime;}else if(appStarts){mustShowModal=Number(appStarts.value)>0&&state.appStartCount>=appStarts.value;hasRepeats=appStarts.repeats===null||state.appStartResetCount<=appStarts.repeats;resetAction=resetAppStartCount;increaseAction=null;}// the actual show modal logic
|
|
15
15
|
dispatch(showModal(resetAction,increaseAction,mustShowModal,hasRepeats));case 16:case"end":return _context.stop();}}},_callee);}));return function(_x){return _ref2.apply(this,arguments);};}());// event subscriber to handle order placed ratings
|
|
@@ -1,9 +1,9 @@
|
|
|
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 _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 event from'@shopgate/pwa-core/classes/Event';import{APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND}from'@shopgate/pwa-core/constants/AppEvents';import openAppSettings from'@shopgate/pwa-core/commands/openAppSettings';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{
|
|
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 _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 event from'@shopgate/pwa-core/classes/Event';import{APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND}from'@shopgate/pwa-core/constants/AppEvents';import openAppSettings from'@shopgate/pwa-core/commands/openAppSettings';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{PERMISSION_STATUS_DENIED,PERMISSION_STATUS_GRANTED,PERMISSION_STATUS_NOT_DETERMINED,PERMISSION_STATUS_NOT_SUPPORTED,PERMISSION_ID_CAMERA}from'@shopgate/pwa-core/constants/AppPermissions';import{getAppPermissions,requestAppPermissions}from'@shopgate/pwa-core/commands/appPermissions';import{logger}from'@shopgate/pwa-core/helpers';import grantPermissions from"../grantPermissions";jest.mock('@shopgate/pwa-core/classes/Event');jest.mock('@shopgate/pwa-core/commands/openAppSettings');jest.mock('@shopgate/pwa-core/commands/appPermissions',function(){return{getAppPermissions:jest.fn(),requestAppPermissions:jest.fn()};});jest.mock('@shopgate/pwa-common/actions/modal/showModal',function(){return jest.fn();});jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:jest.fn()}};});/**
|
|
2
2
|
* @param {string} status The desired permission status.
|
|
3
3
|
* @returns {Array}
|
|
4
|
-
*/var getPermissionsResponse=function getPermissionsResponse(){var status=arguments.length>0&&arguments[0]!==undefined?arguments[0]:
|
|
4
|
+
*/var getPermissionsResponse=function getPermissionsResponse(){var status=arguments.length>0&&arguments[0]!==undefined?arguments[0]:PERMISSION_STATUS_GRANTED;return[{status:status}];};/**
|
|
5
5
|
* Flushes the promise queue.
|
|
6
6
|
* @returns {Promise}
|
|
7
|
-
*/var flushPromises=function flushPromises(){return new Promise(function(resolve){return setImmediate(resolve);});};var customModalOptions={message:'Modal message',confirm:'Confirm label',dismiss:'Dismiss label',params:{param:'one'}};describe('engage > core > actions > grantPermissions',function(){var dispatch=jest.fn(function(action){return action;});jest.useFakeTimers();beforeAll(function(){getAppPermissions.mockResolvedValue(getPermissionsResponse(
|
|
8
|
-
flushPromises().then(function(){event.call(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND);jest.runAllTimers();});});it('should resolve with TRUE when the user opened the settings, and granted permissions',function(done){getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(
|
|
7
|
+
*/var flushPromises=function flushPromises(){return new Promise(function(resolve){return setImmediate(resolve);});};var customModalOptions={message:'Modal message',confirm:'Confirm label',dismiss:'Dismiss label',params:{param:'one'}};describe('engage > core > actions > grantPermissions',function(){var dispatch=jest.fn(function(action){return action;});jest.useFakeTimers();beforeAll(function(){getAppPermissions.mockResolvedValue(getPermissionsResponse(PERMISSION_STATUS_GRANTED));requestAppPermissions.mockResolvedValue(getPermissionsResponse(PERMISSION_STATUS_GRANTED));showModal.mockResolvedValue(true);});beforeEach(function(){jest.clearAllMocks();event.removeAllListeners();});var permissionId=PERMISSION_ID_CAMERA;it('should resolve with TRUE when the permissions are granted',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var granted;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return grantPermissions({permissionId:permissionId})(dispatch);case 2:granted=_context.sent;expect(granted).toBe(true);expect(getAppPermissions).toHaveBeenCalledWith([permissionId]);expect(requestAppPermissions).not.toHaveBeenCalled();expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();case 9:case"end":return _context.stop();}}},_callee);})));it('should resolve with FALSE when called with an invalid permissionId',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var granted;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return grantPermissions({permissionId:'unknownId'})(dispatch);case 2:granted=_context2.sent;expect(granted).toBe(false);expect(getAppPermissions).not.toHaveBeenCalled();expect(requestAppPermissions).not.toHaveBeenCalled();expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).toHaveBeenCalledTimes(1);case 10:case"end":return _context2.stop();}}},_callee2);})));it('should resolve with FALSE when the permissions are not supported',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var granted;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_NOT_SUPPORTED));_context3.next=3;return grantPermissions({permissionId:permissionId})(dispatch);case 3:granted=_context3.sent;expect(granted).toBe(false);expect(getAppPermissions).toHaveBeenCalledWith([permissionId]);expect(requestAppPermissions).not.toHaveBeenCalled();expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 11:case"end":return _context3.stop();}}},_callee3);})));it('should resolve with TRUE when the permissions where not determined, but the user granted them',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var granted;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_NOT_DETERMINED));_context4.next=3;return grantPermissions({permissionId:permissionId})(dispatch);case 3:granted=_context4.sent;expect(granted).toBe(true);expect(getAppPermissions).toHaveBeenCalledWith([permissionId]);expect(requestAppPermissions).toHaveBeenCalledWith([{permissionId:permissionId}]);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 11:case"end":return _context4.stop();}}},_callee4);})));it('should resolve with FALSE when the permissions where not determined, and the user denied them',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var granted;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_NOT_DETERMINED));requestAppPermissions.mockResolvedValue(getPermissionsResponse(PERMISSION_STATUS_DENIED));_context5.next=4;return grantPermissions({permissionId:permissionId})(dispatch);case 4:granted=_context5.sent;expect(granted).toBe(false);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 10:case"end":return _context5.stop();}}},_callee5);})));it('should resolve with FALSE when the permissions where not determined, and the user denied them temporary',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var granted;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_NOT_DETERMINED));requestAppPermissions.mockResolvedValue(getPermissionsResponse(PERMISSION_STATUS_NOT_DETERMINED));_context6.next=4;return grantPermissions({permissionId:permissionId})(dispatch);case 4:granted=_context6.sent;expect(granted).toBe(false);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 10:case"end":return _context6.stop();}}},_callee6);})));it('should resolve with FALSE when the permissions are denied, and no settings modal is about to be shown',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var granted;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_DENIED));_context7.next=3;return grantPermissions({permissionId:permissionId})(dispatch);case 3:granted=_context7.sent;expect(granted).toBe(false);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 9:case"end":return _context7.stop();}}},_callee7);})));it('should resolve with FALSE when the user denied to open the app settings',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){var granted;return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_DENIED));showModal.mockResolvedValueOnce(false);_context8.next=4;return grantPermissions({permissionId:permissionId,useSettingsModal:true,modal:customModalOptions})(dispatch);case 4:granted=_context8.sent;expect(granted).toBe(false);expect(dispatch).toHaveBeenCalledTimes(1);expect(showModal).toHaveBeenCalledWith(_extends({title:null},customModalOptions));expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();case 10:case"end":return _context8.stop();}}},_callee8);})));it('should resolve with FALSE when the user opened the settings, but did not grant permissions',function(done){getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_DENIED));getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_DENIED));grantPermissions({permissionId:permissionId,useSettingsModal:true})(dispatch).then(function(granted){expect(granted).toBe(false);expect(dispatch).toHaveBeenCalledTimes(1);expect(openAppSettings).toHaveBeenCalledTimes(1);expect(event.removeCallbackSpy).toHaveBeenCalledWith(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND,expect.any(Function));done();});// Flush the promise queue, so that the code inside of promise from the action is executed.
|
|
8
|
+
flushPromises().then(function(){event.call(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND);jest.runAllTimers();});});it('should resolve with TRUE when the user opened the settings, and granted permissions',function(done){getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_DENIED));getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(PERMISSION_STATUS_GRANTED));grantPermissions({permissionId:permissionId,useSettingsModal:true})(dispatch).then(function(granted){expect(granted).toBe(true);expect(dispatch).toHaveBeenCalledTimes(1);expect(openAppSettings).toHaveBeenCalledTimes(1);expect(event.removeCallbackSpy).toHaveBeenCalledWith(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND,expect.any(Function));done();});// Flush the promise queue, so that the code inside of promise from the action is executed.
|
|
9
9
|
flushPromises().then(function(){event.call(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND);jest.runAllTimers();});});});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_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 event from'@shopgate/pwa-core/classes/Event';import{APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND}from'@shopgate/pwa-core/constants/AppEvents';import openAppSettings from'@shopgate/pwa-core/commands/openAppSettings';import{showModal}from'@shopgate/engage/core';import{
|
|
1
|
+
import _regeneratorRuntime from"@babel/runtime/regenerator";function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_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 event from'@shopgate/pwa-core/classes/Event';import{APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND}from'@shopgate/pwa-core/constants/AppEvents';import openAppSettings from'@shopgate/pwa-core/commands/openAppSettings';import{showModal}from'@shopgate/engage/core';import{PERMISSION_STATUS_DENIED,PERMISSION_STATUS_GRANTED,PERMISSION_STATUS_NOT_DETERMINED,PERMISSION_STATUS_NOT_SUPPORTED,availablePermissionsIds}from'@shopgate/pwa-core/constants/AppPermissions';import{getAppPermissions,requestAppPermissions}from'@shopgate/pwa-core/commands/appPermissions';import{logger}from'@shopgate/pwa-core/helpers';/**
|
|
2
2
|
* Determines the current state of a specific permission for an app feature. If not already
|
|
3
3
|
* happened, the user will be prompted to grant permissions.
|
|
4
4
|
* The action returns a promise which resolves with a boolean value, that indicates the state.
|
|
@@ -20,9 +20,9 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function _slicedToAr
|
|
|
20
20
|
* @param {string} options.modal.dismiss Label for the dismiss button.
|
|
21
21
|
* @param {Object} options.modal.params Additional parameters for i18n strings.
|
|
22
22
|
* @return { Function } A redux thunk.
|
|
23
|
-
*/var grantPermissions=function grantPermissions(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};return function(dispatch){return new Promise(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(resolve){var permissionId,_options$useSettingsM,useSettingsModal,_options$useRationale,useRationaleModal,_options$rationaleMod,rationaleModalOptions,_options$modal,modalOptions,status,_yield$getAppPermissi,_yield$getAppPermissi2,requestAllowed,_yield$requestAppPerm,_yield$requestAppPerm2,openSettings,handler;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:permissionId=options.permissionId,_options$useSettingsM=options.useSettingsModal,useSettingsModal=_options$useSettingsM===void 0?false:_options$useSettingsM,_options$useRationale=options.useRationaleModal,useRationaleModal=_options$useRationale===void 0?false:_options$useRationale,_options$rationaleMod=options.rationaleModal,rationaleModalOptions=_options$rationaleMod===void 0?{}:_options$rationaleMod,_options$modal=options.modal,modalOptions=_options$modal===void 0?{}:_options$modal;if(availablePermissionsIds.includes(permissionId)){_context2.next=5;break;}logger.error('grandPermissions: %s is no valid permission id',permissionId);resolve(false);return _context2.abrupt("return");case 5:_context2.next=7;return getAppPermissions([permissionId]);case 7:_yield$getAppPermissi=_context2.sent;_yield$getAppPermissi2=_slicedToArray(_yield$getAppPermissi,1);status=_yield$getAppPermissi2[0].status;if(!(status===
|
|
23
|
+
*/var grantPermissions=function grantPermissions(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};return function(dispatch){return new Promise(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(resolve){var permissionId,_options$useSettingsM,useSettingsModal,_options$useRationale,useRationaleModal,_options$rationaleMod,rationaleModalOptions,_options$modal,modalOptions,status,_yield$getAppPermissi,_yield$getAppPermissi2,requestAllowed,_yield$requestAppPerm,_yield$requestAppPerm2,openSettings,handler;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:permissionId=options.permissionId,_options$useSettingsM=options.useSettingsModal,useSettingsModal=_options$useSettingsM===void 0?false:_options$useSettingsM,_options$useRationale=options.useRationaleModal,useRationaleModal=_options$useRationale===void 0?false:_options$useRationale,_options$rationaleMod=options.rationaleModal,rationaleModalOptions=_options$rationaleMod===void 0?{}:_options$rationaleMod,_options$modal=options.modal,modalOptions=_options$modal===void 0?{}:_options$modal;if(availablePermissionsIds.includes(permissionId)){_context2.next=5;break;}logger.error('grandPermissions: %s is no valid permission id',permissionId);resolve(false);return _context2.abrupt("return");case 5:_context2.next=7;return getAppPermissions([permissionId]);case 7:_yield$getAppPermissi=_context2.sent;_yield$getAppPermissi2=_slicedToArray(_yield$getAppPermissi,1);status=_yield$getAppPermissi2[0].status;if(!(status===PERMISSION_STATUS_NOT_SUPPORTED)){_context2.next=13;break;}resolve(false);return _context2.abrupt("return");case 13:if(!(status===PERMISSION_STATUS_NOT_DETERMINED)){_context2.next=29;break;}if(!useRationaleModal){_context2.next=21;break;}_context2.next=17;return dispatch(showModal({message:rationaleModalOptions.message||'',confirm:rationaleModalOptions.confirm||'',dismiss:rationaleModalOptions.dismiss||'',params:rationaleModalOptions.params||''}));case 17:requestAllowed=_context2.sent;if(!(requestAllowed===false)){_context2.next=21;break;}resolve(false);return _context2.abrupt("return");case 21:_context2.next=23;return requestAppPermissions([{permissionId:permissionId}]);case 23:_yield$requestAppPerm=_context2.sent;_yield$requestAppPerm2=_slicedToArray(_yield$requestAppPerm,1);status=_yield$requestAppPerm2[0].status;if(![PERMISSION_STATUS_DENIED,PERMISSION_STATUS_NOT_DETERMINED].includes(status)){_context2.next=29;break;}resolve(false);return _context2.abrupt("return");case 29:if(!(status===PERMISSION_STATUS_GRANTED)){_context2.next=32;break;}resolve(true);return _context2.abrupt("return");case 32:if(!(status===PERMISSION_STATUS_DENIED)){_context2.next=45;break;}if(useSettingsModal){_context2.next=36;break;}resolve(false);return _context2.abrupt("return");case 36:_context2.next=38;return dispatch(showModal({title:modalOptions.title||null,message:modalOptions.message,confirm:modalOptions.confirm,dismiss:modalOptions.dismiss,params:modalOptions.params}));case 38:openSettings=_context2.sent;if(openSettings){_context2.next=42;break;}resolve(false);return _context2.abrupt("return");case 42:/**
|
|
24
24
|
* Handler for the app event.
|
|
25
|
-
*/handler=/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var _yield$getAppPermissi3,_yield$getAppPermissi4;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:event.removeCallback(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND,handler);_context.next=3;return getAppPermissions([permissionId]);case 3:_yield$getAppPermissi3=_context.sent;_yield$getAppPermissi4=_slicedToArray(_yield$getAppPermissi3,1);status=_yield$getAppPermissi4[0].status;resolve(status===
|
|
25
|
+
*/handler=/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var _yield$getAppPermissi3,_yield$getAppPermissi4;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:event.removeCallback(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND,handler);_context.next=3;return getAppPermissions([permissionId]);case 3:_yield$getAppPermissi3=_context.sent;_yield$getAppPermissi4=_slicedToArray(_yield$getAppPermissi3,1);status=_yield$getAppPermissi4[0].status;resolve(status===PERMISSION_STATUS_GRANTED);case 7:case"end":return _context.stop();}}},_callee);}));return function handler(){return _ref2.apply(this,arguments);};}();/**
|
|
26
26
|
* Register an event handler, so that we can perform the permissions check again,
|
|
27
27
|
* when the user comes back from the settings.
|
|
28
28
|
*/event.addCallback(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND,handler);// Open the settings (protected by a timeout, so that the modal closes before the app is left).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shopgate/engage",
|
|
3
|
-
"version": "6.22.0-beta.
|
|
3
|
+
"version": "6.22.0-beta.2",
|
|
4
4
|
"description": "Shopgate's ENGAGE library.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Shopgate <support@shopgate.com>",
|
|
@@ -15,12 +15,12 @@
|
|
|
15
15
|
"connect"
|
|
16
16
|
],
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@shopgate/pwa-common": "6.22.0-beta.
|
|
19
|
-
"@shopgate/pwa-common-commerce": "6.22.0-beta.
|
|
20
|
-
"@shopgate/pwa-core": "6.22.0-beta.
|
|
21
|
-
"@shopgate/pwa-ui-ios": "6.22.0-beta.
|
|
22
|
-
"@shopgate/pwa-ui-material": "6.22.0-beta.
|
|
23
|
-
"@shopgate/pwa-ui-shared": "6.22.0-beta.
|
|
18
|
+
"@shopgate/pwa-common": "6.22.0-beta.2",
|
|
19
|
+
"@shopgate/pwa-common-commerce": "6.22.0-beta.2",
|
|
20
|
+
"@shopgate/pwa-core": "6.22.0-beta.2",
|
|
21
|
+
"@shopgate/pwa-ui-ios": "6.22.0-beta.2",
|
|
22
|
+
"@shopgate/pwa-ui-material": "6.22.0-beta.2",
|
|
23
|
+
"@shopgate/pwa-ui-shared": "6.22.0-beta.2",
|
|
24
24
|
"@virtuous/conductor": "~2.4.0",
|
|
25
25
|
"babel-plugin-transform-es3-member-expression-literals": "^6.8.0",
|
|
26
26
|
"babel-plugin-transform-es3-property-literals": "^6.8.0",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"./optInTrigger";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{PUSH_OPT_IN_INCREASE_APP_START_COUNT,PUSH_OPT_IN_RESET_APP_START_COUNT,PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT,PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT,PUSH_OPT_IN_INCREASE_REJECTION_COUNT,PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP,PUSH_OPT_IN_OPT_IN_POSTPONED}from"../constants";/**
|
|
2
|
+
* Increment the app start count
|
|
3
|
+
* @return {Object} The dispatched action object.
|
|
4
|
+
*/export var increaseAppStartCount=function increaseAppStartCount(){return{type:PUSH_OPT_IN_INCREASE_APP_START_COUNT};};/**
|
|
5
|
+
* Reset the app start count, and increment reset counts
|
|
6
|
+
* @return {Object} The dispatched action object.
|
|
7
|
+
*/export var resetAppStartCount=function resetAppStartCount(){return{type:PUSH_OPT_IN_RESET_APP_START_COUNT};};/**
|
|
8
|
+
* Increment the orders placed count
|
|
9
|
+
* @return {Object} The dispatched action object.
|
|
10
|
+
*/export var increaseOrdersPlacedCount=function increaseOrdersPlacedCount(){return{type:PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT};};/**
|
|
11
|
+
* Reset the orders placed count, and increment reset counts
|
|
12
|
+
* @return {Object} The dispatched action object.
|
|
13
|
+
*/export var resetOrdersPlacedCount=function resetOrdersPlacedCount(){return{type:PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT};};/**
|
|
14
|
+
* Sets the last opt-in timestamp
|
|
15
|
+
* @return {Object} The dispatched action object.
|
|
16
|
+
*/export var setLastPopupTimestamp=function setLastPopupTimestamp(){return{type:PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP};};/**
|
|
17
|
+
* Increased the opt-in rejection / postponement count
|
|
18
|
+
* @return {Object} The dispatched action object.
|
|
19
|
+
*/export var increaseRejectionCount=function increaseRejectionCount(){return{type:PUSH_OPT_IN_INCREASE_REJECTION_COUNT};};/**
|
|
20
|
+
* Action to be dispatched when push opt in was postponed e.g. Opt In Modal was closed without
|
|
21
|
+
* taking a decision about permissions.
|
|
22
|
+
* @return {Object} The dispatched action object.
|
|
23
|
+
*/export var optInPostponed=function optInPostponed(){return{type:PUSH_OPT_IN_OPT_IN_POSTPONED};};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"./optInTrigger";
|
|
@@ -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);});};}/**
|
|
2
|
+
* Redux thunk to the dispatched when the push opt in is supposed to be shown
|
|
3
|
+
* (Modal or native Dialog)
|
|
4
|
+
* @returns {Function}
|
|
5
|
+
*/export var showOptIn=function showOptIn(){return/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// TODO implement logic
|
|
6
|
+
console.warn('SHOW_PUSH_OPT_IN');case 1:case"end":return _context.stop();}}},_callee);}));};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"./optInTrigger";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export var PUSH_OPT_IN_INCREASE_APP_START_COUNT='PUSH_OPT_IN_INCREASE_APP_START_COUNT';export var PUSH_OPT_IN_RESET_APP_START_COUNT='PUSH_OPT_IN_RESET_APP_START_COUNT';export var PUSH_OPT_IN_RESET_APP_START_STATE='PUSH_OPT_IN_RESET_APP_START_STATE';export var PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT='PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT';export var PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT='PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT';export var PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE='PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE';export var PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP='PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP';export var PUSH_OPT_IN_INCREASE_REJECTION_COUNT='PUSH_OPT_IN_INCREASE_REJECTION_COUNT';export var PUSH_OPT_IN_OPT_IN_POSTPONED='PUSH_OPT_IN_OPT_IN_POSTPONED';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{combineReducers}from'redux';import optInTrigger from"./optInTrigger";export default combineReducers({optInTrigger:optInTrigger});
|
|
@@ -0,0 +1,6 @@
|
|
|
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{PUSH_OPT_IN_INCREASE_APP_START_COUNT,PUSH_OPT_IN_RESET_APP_START_STATE,PUSH_OPT_IN_RESET_APP_START_COUNT,PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT,PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT,PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE,PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP,PUSH_OPT_IN_INCREASE_REJECTION_COUNT}from"../constants";var defaultState={appStartCount:0,appStartResetCount:0,ordersPlacedCount:0,ordersPlacedResetCount:0,lastPopupAt:null,rejectionCount:0};/**
|
|
2
|
+
* Stores all the states related to the pushOptInTrigger functionality.
|
|
3
|
+
* @param {Object} [state] The current state.
|
|
4
|
+
* @param {Object} action The action object.
|
|
5
|
+
* @return {Object} The new state.
|
|
6
|
+
*/var pushOptInReducer=function pushOptInReducer(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultState;var action=arguments.length>1?arguments[1]:undefined;switch(action.type){case PUSH_OPT_IN_INCREASE_APP_START_COUNT:{return _extends({},state,{appStartCount:state.appStartCount+1});}case PUSH_OPT_IN_RESET_APP_START_COUNT:{return _extends({},state,{appStartCount:0,appStartResetCount:state.appStartResetCount+1});}case PUSH_OPT_IN_RESET_APP_START_STATE:{return _extends({},state,{appStartCount:0,appStartResetCount:0});}case PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT:{return _extends({},state,{ordersPlacedCount:state.ordersPlacedCount+1});}case PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT:{return _extends({},state,{ordersPlacedCount:0,ordersPlacedResetCount:state.ordersPlacedResetCount+1});}case PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE:{return _extends({},state,{ordersPlacedCount:0,ordersPlacedResetCount:0});}case PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP:{return _extends({},state,{lastPopupAt:Date.now()});}case PUSH_OPT_IN_INCREASE_REJECTION_COUNT:{return _extends({},state,{rejectionCount:state.rejectionCount+1});}default:return state;}};export default pushOptInReducer;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"./optInTrigger";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Selects the push opt in information.
|
|
3
|
+
* @param {Object} state The current state.
|
|
4
|
+
* @returns {Object} The push opt in information.
|
|
5
|
+
*/export var getPushOptInTriggerState=function getPushOptInTriggerState(state){var _state$pushOptIn;return(state===null||state===void 0?void 0:(_state$pushOptIn=state.pushOptIn)===null||_state$pushOptIn===void 0?void 0:_state$pushOptIn.optInTrigger)||{};};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import optInTrigger from"./optInTrigger";export default(function(subscribe){optInTrigger(subscribe);});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import _regeneratorRuntime from"@babel/runtime/regenerator";function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_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{appConfig}from'@shopgate/engage';import{main$,event,appDidStart$,getAppPermissions,PERMISSION_ID_PUSH,PERMISSION_STATUS_NOT_DETERMINED}from'@shopgate/engage/core';import{increaseAppStartCount,resetAppStartCount,increaseOrdersPlacedCount,resetOrdersPlacedCount,setLastPopupTimestamp,increaseRejectionCount}from"../action-creators";import{PUSH_OPT_IN_OPT_IN_POSTPONED}from"../constants";import{getPushOptInTriggerState}from"../selectors";import{showOptIn}from"../actions";var DAY_IN_MS=1000*60*60*24;var increaseRejectionCount$=main$.filter(function(_ref){var action=_ref.action;return action.type===PUSH_OPT_IN_OPT_IN_POSTPONED;});/**
|
|
2
|
+
* Push opt in subscriptions
|
|
3
|
+
* @param {Function} subscribe The subscribe function
|
|
4
|
+
*/export default function pushOptIn(subscribe){/**
|
|
5
|
+
* @param {Object} subscriptionParams Params from the subscription callback
|
|
6
|
+
* @param {string} configKey The "pushOptIn" key to be used
|
|
7
|
+
* @param {Function} increaseCountAction Action to increase the count in Redux for the configKey
|
|
8
|
+
* @returns {void}
|
|
9
|
+
*/var showOptInAfterChecks=/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2,configKey,increaseCountAction){var dispatch,getState,_appConfig$pushOptIn,appStarts,ordersPlaced,rejectionMaxCount,minDaysBetweenOptIns,_yield$getAppPermissi,_yield$getAppPermissi2,pushStatus,state,configValue,resetAction,resetCountState,configCountState,mustShowModal,hasRepeats,minDaysElapsed;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:dispatch=_ref2.dispatch,getState=_ref2.getState;_appConfig$pushOptIn=appConfig.pushOptIn,appStarts=_appConfig$pushOptIn.appStarts,ordersPlaced=_appConfig$pushOptIn.ordersPlaced,rejectionMaxCount=_appConfig$pushOptIn.rejectionMaxCount,minDaysBetweenOptIns=_appConfig$pushOptIn.minDaysBetweenOptIns;// TODO add check to determine if the app supports push-opt-in
|
|
10
|
+
_context.next=4;return getAppPermissions([PERMISSION_ID_PUSH]);case 4:_yield$getAppPermissi=_context.sent;_yield$getAppPermissi2=_slicedToArray(_yield$getAppPermissi,1);pushStatus=_yield$getAppPermissi2[0].status;if(!(pushStatus!==PERMISSION_STATUS_NOT_DETERMINED)){_context.next=9;break;}return _context.abrupt("return");case 9:dispatch(increaseCountAction());state=getPushOptInTriggerState(getState());configValue=appStarts;resetAction=resetAppStartCount;resetCountState=state.appStartResetCount;configCountState=state.appStartCount;if(configKey==='ordersPlaced'){configValue=ordersPlaced;resetAction=resetOrdersPlacedCount;resetCountState=state.ordersPlacedResetCount;configCountState=state.ordersPlacedCount;}if(!(state.rejectionCount>=rejectionMaxCount)){_context.next=18;break;}return _context.abrupt("return");case 18:mustShowModal=Number(configValue.value)>0&&configCountState>=configValue.value;hasRepeats=configValue.repeats===null||resetCountState<=configValue.repeats;minDaysElapsed=Date.now()-state.lastPopupAt>=minDaysBetweenOptIns*DAY_IN_MS;if(mustShowModal&&hasRepeats&&minDaysElapsed){dispatch(setLastPopupTimestamp());dispatch(resetAction());dispatch(showOptIn());}case 22:case"end":return _context.stop();}}},_callee);}));return function showOptInAfterChecks(_x,_x2,_x3){return _ref3.apply(this,arguments);};}();// event subscriber to handle app start based push opt in
|
|
11
|
+
subscribe(appDidStart$,/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4){var dispatch,getState;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:dispatch=_ref4.dispatch,getState=_ref4.getState;_context2.next=3;return showOptInAfterChecks({dispatch:dispatch,getState:getState},'appStarts',increaseAppStartCount);case 3:case"end":return _context2.stop();}}},_callee2);}));return function(_x4){return _ref5.apply(this,arguments);};}());// event subscriber to handle order based push opt in
|
|
12
|
+
subscribe(appDidStart$,function(_ref6){var dispatch=_ref6.dispatch,getState=_ref6.getState;event.addCallback('checkoutSuccess',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_context3.next=2;return showOptInAfterChecks({dispatch:dispatch,getState:getState},'ordersPlaced',increaseOrdersPlacedCount);case 2:case"end":return _context3.stop();}}},_callee3);})));});subscribe(increaseRejectionCount$,function(_ref8){var dispatch=_ref8.dispatch;dispatch(increaseRejectionCount());});}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import _regeneratorRuntime from"@babel/runtime/regenerator";function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_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{combineReducers}from'redux';import merge from'lodash/merge';import{createMockStore}from'@shopgate/pwa-common/store';import{event,getAppPermissions,PERMISSION_ID_PUSH,PERMISSION_STATUS_DENIED,APP_DID_START}from'@shopgate/engage/core';import{increaseAppStartCount,setLastPopupTimestamp,resetAppStartCount,increaseRejectionCount,increaseOrdersPlacedCount,resetOrdersPlacedCount,optInPostponed}from"../action-creators";import{showOptIn}from"../actions";import pushReducers from"../reducers";import subscriptions from"./optInTrigger";/**
|
|
2
|
+
* @typedef {Object} MockedConfigSetting
|
|
3
|
+
* @property {number} value
|
|
4
|
+
* @property {number|null} repeats
|
|
5
|
+
*/ /**
|
|
6
|
+
* @typedef {Object} MockedConfig
|
|
7
|
+
* @property {MockedConfigSetting} appStarts
|
|
8
|
+
* @property {MockedConfigSetting} ordersPlaced
|
|
9
|
+
* @property {number} rejectionMaxCount
|
|
10
|
+
* @property {number} minDaysBetweenOptIns
|
|
11
|
+
*/var mockedPushOptInConfig;/**
|
|
12
|
+
* Updates the mocked pushOptIn config with custom values.
|
|
13
|
+
* @param {MockedConfig} update The custom config values
|
|
14
|
+
*/var setMockedConfig=function setMockedConfig(){var update=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};mockedPushOptInConfig=merge({appStarts:{value:1,repeats:null},ordersPlaced:{value:1,repeats:null},rejectionMaxCount:2,minDaysBetweenOptIns:1},update);};jest.mock("../actions/optInTrigger.js",function(){return{showOptIn:jest.fn()};});jest.mock('@shopgate/engage',function(){return{appConfig:{get pushOptIn(){return mockedPushOptInConfig;}}};});jest.mock('@shopgate/engage/core',function(){/* eslint-disable no-shadow */var _jest$requireActual=jest.requireActual('@shopgate/engage/core'),appDidStart$=_jest$requireActual.appDidStart$,main$=_jest$requireActual.main$,PERMISSION_ID_PUSH=_jest$requireActual.PERMISSION_ID_PUSH,PERMISSION_STATUS_NOT_DETERMINED=_jest$requireActual.PERMISSION_STATUS_NOT_DETERMINED,PERMISSION_STATUS_GRANTED=_jest$requireActual.PERMISSION_STATUS_GRANTED,PERMISSION_STATUS_DENIED=_jest$requireActual.PERMISSION_STATUS_DENIED,APP_DID_START=_jest$requireActual.APP_DID_START;/* eslint-enable no-shadow */return{main$:main$,appDidStart$:appDidStart$,PERMISSION_ID_PUSH:PERMISSION_ID_PUSH,PERMISSION_STATUS_NOT_DETERMINED:PERMISSION_STATUS_NOT_DETERMINED,PERMISSION_STATUS_GRANTED:PERMISSION_STATUS_GRANTED,PERMISSION_STATUS_DENIED:PERMISSION_STATUS_DENIED,APP_DID_START:APP_DID_START,getAppPermissions:jest.fn().mockResolvedValue([{status:PERMISSION_STATUS_NOT_DETERMINED}]),event:{addCallback:jest.fn()}};});describe('Push OptIn Subscriptions',function(){var subscribe=jest.fn();var dispatch;var getState;var callbackParams;var mockedTS=new Date('2024-01-31T12:00:00.000Z').getTime();var dateMock;beforeEach(function(){setMockedConfig();jest.clearAllMocks();var store=createMockStore(combineReducers({pushOptIn:pushReducers}),subscriptions);jest.spyOn(store,'dispatch');jest.spyOn(store,'getState');dateMock=jest.spyOn(Date,'now').mockImplementation(function(){return mockedTS;});dispatch=store.dispatch;getState=store.getState;callbackParams={dispatch:dispatch,getState:getState};subscriptions(subscribe);// By default dispatching the showOptIn action results into dispatching the optInPostponed
|
|
15
|
+
// action
|
|
16
|
+
showOptIn.mockImplementation(function(){return function(thunkDispatch){thunkDispatch(optInPostponed());};});});/**
|
|
17
|
+
* Since subscriptions for handling appStarts and ordersPlaced settings share the same logic and
|
|
18
|
+
* just operate on different properties of the related app config, both test blocks are equal
|
|
19
|
+
* can can be executed in a loop.
|
|
20
|
+
*/describe.each(['appStarts','ordersPlaced'])('Counter tests',function(configType){describe("Logic for ".concat(configType),function(){var callback;var eventName;var increaseCountAction;var resetCountAction;beforeEach(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var _subscribe$mock$calls,_subscribe$mock$calls2,_subscribe$mock$calls3,_subscribe$mock$calls4,subscribeCallback,_event$addCallback$mo,_event$addCallback$mo2;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:if(!(configType==='appStarts')){_context.next=8;break;}// Pick the callback of the subscriptions for handling of the appStarts setting
|
|
21
|
+
_subscribe$mock$calls=_slicedToArray(subscribe.mock.calls,1);_subscribe$mock$calls2=_slicedToArray(_subscribe$mock$calls[0],2);callback=_subscribe$mock$calls2[1];increaseCountAction=increaseAppStartCount;resetCountAction=resetAppStartCount;_context.next=18;break;case 8:if(!(configType==='ordersPlaced')){_context.next=18;break;}// Pick the callback of the subscriptions for handling of the ordersPlaced setting
|
|
22
|
+
_subscribe$mock$calls3=_slicedToArray(subscribe.mock.calls,2),_subscribe$mock$calls4=_slicedToArray(_subscribe$mock$calls3[1],2),subscribeCallback=_subscribe$mock$calls4[1];// Invoke the callback, so that an event handler for "checkoutSuccess" is registered
|
|
23
|
+
_context.next=12;return subscribeCallback(callbackParams);case 12:_event$addCallback$mo=_slicedToArray(event.addCallback.mock.calls,1);_event$addCallback$mo2=_slicedToArray(_event$addCallback$mo[0],2);eventName=_event$addCallback$mo2[0];callback=_event$addCallback$mo2[1];increaseCountAction=increaseOrdersPlacedCount;resetCountAction=resetOrdersPlacedCount;case 18:case"end":return _context.stop();}}},_callee);})));if(configType==='ordersPlaced'){it('should register for the expected event',function(){expect(eventName).toBe('checkoutSuccess');});}it('should not trigger opt-in when push permission has not status "notDetermined" anymore',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:setMockedConfig(_defineProperty({},configType,{value:1}));getAppPermissions.mockResolvedValueOnce([{status:PERMISSION_STATUS_DENIED}]);_context2.next=4;return callback(callbackParams);case 4:expect(getAppPermissions).toHaveBeenCalled();expect(getAppPermissions).toHaveBeenCalledWith([PERMISSION_ID_PUSH]);expect(dispatch).not.toHaveBeenCalled();case 7:case"end":return _context2.stop();}}},_callee2);})));it('should not trigger opt-in when config key is set to 0',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:setMockedConfig(_defineProperty({},configType,{value:0}));_context3.next=3;return callback(callbackParams);case 3:expect(getAppPermissions).toHaveBeenCalled();expect(getAppPermissions).toHaveBeenCalledWith([PERMISSION_ID_PUSH]);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(increaseCountAction());expect(showOptIn).not.toHaveBeenCalled();case 8:case"end":return _context3.stop();}}},_callee3);})));it('should trigger opt-in at the first counter increase',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:setMockedConfig(_defineProperty({},configType,{value:1}));_context4.next=3;return callback(callbackParams);case 3:expect(getAppPermissions).toHaveBeenCalled();expect(getAppPermissions).toHaveBeenCalledWith([PERMISSION_ID_PUSH]);expect(dispatch).toHaveBeenCalledTimes(4);expect(dispatch).toHaveBeenCalledWith(increaseCountAction());expect(dispatch).toHaveBeenCalledWith(setLastPopupTimestamp());expect(dispatch).toHaveBeenCalledWith(resetCountAction());expect(showOptIn).toHaveBeenCalledTimes(1);case 10:case"end":return _context4.stop();}}},_callee4);})));it('should trigger opt-in at the 3rd counter increase',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:setMockedConfig(_defineProperty({},configType,{value:3}));// 1st counter increase -> do not show opt-in
|
|
24
|
+
_context5.next=3;return callback(callbackParams);case 3:expect(dispatch).toHaveBeenCalledTimes(1);expect(showOptIn).not.toHaveBeenCalled();// 2nd counter increase -> do not show opt-in
|
|
25
|
+
_context5.next=7;return callback(callbackParams);case 7:expect(dispatch).toHaveBeenCalledTimes(2);expect(showOptIn).not.toHaveBeenCalled();// 3rd counter increase -> show opt-in
|
|
26
|
+
_context5.next=11;return callback(callbackParams);case 11:expect(dispatch).toHaveBeenCalledTimes(6);expect(showOptIn).toHaveBeenCalledTimes(1);case 13:case"end":return _context5.stop();}}},_callee5);})));it('should not trigger opt-in again till "minDaysBetweenOptIns" elapsed',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var _setMockedConfig5;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:setMockedConfig((_setMockedConfig5={},_defineProperty(_setMockedConfig5,configType,{value:1}),_defineProperty(_setMockedConfig5,"minDaysBetweenOptIns",1),_setMockedConfig5));// 1st counter increase -> show opt-in
|
|
27
|
+
_context6.next=3;return callback(callbackParams);case 3:expect(showOptIn).toHaveBeenCalledTimes(1);// fast forward time by 1/2 day
|
|
28
|
+
dateMock.mockImplementation(function(){return mockedTS+1000*60*60*12;});// 2nd counter increase -> do not show opt due to min days setting
|
|
29
|
+
_context6.next=7;return callback(callbackParams);case 7:expect(showOptIn).toHaveBeenCalledTimes(1);// 3rd counter increase -> do not show opt due to min days setting
|
|
30
|
+
_context6.next=10;return callback(callbackParams);case 10:expect(showOptIn).toHaveBeenCalledTimes(1);// fast forward time by 1 day
|
|
31
|
+
dateMock.mockImplementation(function(){return mockedTS+1000*60*60*24;});// 4th counter increase -> show opt-in again
|
|
32
|
+
_context6.next=14;return callback(callbackParams);case 14:expect(showOptIn).toHaveBeenCalledTimes(2);case 15:case"end":return _context6.stop();}}},_callee6);})));it('should not trigger opt-in when max rejection count is reached',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var _setMockedConfig6;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:setMockedConfig((_setMockedConfig6={},_defineProperty(_setMockedConfig6,configType,{value:1}),_defineProperty(_setMockedConfig6,"minDaysBetweenOptIns",0),_defineProperty(_setMockedConfig6,"rejectionMaxCount",2),_setMockedConfig6));// 1st counter increase -> show opt-in
|
|
33
|
+
_context7.next=3;return callback(callbackParams);case 3:expect(showOptIn).toHaveBeenCalledTimes(1);// 2nd counter increase -> show opt-in
|
|
34
|
+
_context7.next=6;return callback(callbackParams);case 6:expect(showOptIn).toHaveBeenCalledTimes(2);// 3rd counter increase -> no opt-in due to rejection count
|
|
35
|
+
_context7.next=9;return callback(callbackParams);case 9:expect(showOptIn).toHaveBeenCalledTimes(2);case 10:case"end":return _context7.stop();}}},_callee7);})));it('should not trigger opt-in when max repeats are reached',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){var _setMockedConfig7;return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:setMockedConfig((_setMockedConfig7={},_defineProperty(_setMockedConfig7,configType,{value:2,repeats:2}),_defineProperty(_setMockedConfig7,"minDaysBetweenOptIns",0),_defineProperty(_setMockedConfig7,"rejectionMaxCount",4),_setMockedConfig7));_context8.next=3;return callback(callbackParams);case 3:_context8.next=5;return callback(callbackParams);case 5:expect(showOptIn).toHaveBeenCalledTimes(1);_context8.next=8;return callback(callbackParams);case 8:_context8.next=10;return callback(callbackParams);case 10:expect(showOptIn).toHaveBeenCalledTimes(2);_context8.next=13;return callback(callbackParams);case 13:_context8.next=15;return callback(callbackParams);case 15:expect(showOptIn).toHaveBeenCalledTimes(3);_context8.next=18;return callback(callbackParams);case 18:_context8.next=20;return callback(callbackParams);case 20:expect(showOptIn).toHaveBeenCalledTimes(3);case 21:case"end":return _context8.stop();}}},_callee8);})));});});describe('Combined counter tests',function(){var appStartsSubscriberCallback;var ordersPlacedSubscriberCallback;beforeEach(function(){var _subscribe$mock$calls5=_slicedToArray(subscribe.mock.calls,2);var _subscribe$mock$calls6=_slicedToArray(_subscribe$mock$calls5[0],2);appStartsSubscriberCallback=_subscribe$mock$calls6[1];var _subscribe$mock$calls7=_slicedToArray(_subscribe$mock$calls5[1],2);ordersPlacedSubscriberCallback=_subscribe$mock$calls7[1];});it('should trigger opt-in for ordersPlaced when max views for appStarts already exceeded',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var _event$addCallback$mo3,_event$addCallback$mo4,checkoutSuccessCallback;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:setMockedConfig({appStarts:{value:1,repeats:2},ordersPlaced:{value:1,repeats:1},minDaysBetweenOptIns:0,rejectionMaxCount:4});// 3 opt-ins can be triggered before opt-in by appStart is exceeded (initial + 2 repeats)
|
|
36
|
+
_context9.next=3;return appStartsSubscriberCallback(callbackParams);case 3:expect(showOptIn).toHaveBeenCalledTimes(1);_context9.next=6;return appStartsSubscriberCallback(callbackParams);case 6:expect(showOptIn).toHaveBeenCalledTimes(2);_context9.next=9;return appStartsSubscriberCallback(callbackParams);case 9:expect(showOptIn).toHaveBeenCalledTimes(3);// Opt-in does't show anymore for 4th app start since repeats exceeded
|
|
37
|
+
_context9.next=12;return appStartsSubscriberCallback(callbackParams);case 12:expect(showOptIn).toHaveBeenCalledTimes(3);ordersPlacedSubscriberCallback(callbackParams);_event$addCallback$mo3=_slicedToArray(event.addCallback.mock.calls,1),_event$addCallback$mo4=_slicedToArray(_event$addCallback$mo3[0],2),checkoutSuccessCallback=_event$addCallback$mo4[1];// Opt-in shows again since max rejection count is not reached yet
|
|
38
|
+
_context9.next=17;return checkoutSuccessCallback();case 17:expect(showOptIn).toHaveBeenCalledTimes(4);// Opt-in doesn't show anymore for the 2nd order placement, since max rejection count exceeded
|
|
39
|
+
_context9.next=20;return checkoutSuccessCallback();case 20:expect(showOptIn).toHaveBeenCalledTimes(4);case 21:case"end":return _context9.stop();}}},_callee9);})));});describe('appDidStart$',function(){it('should run expected logic when appDidStart$ stream emits',function(){setMockedConfig({appStarts:{value:1,repeats:1},ordersPlaced:{value:1,repeats:1},minDaysBetweenOptIns:0});dispatch({type:APP_DID_START});// getAppPermissions should have been called 1st time for appDidStart
|
|
40
|
+
expect(getAppPermissions).toHaveBeenCalledTimes(1);var _event$addCallback$mo5=_slicedToArray(event.addCallback.mock.calls,1),_event$addCallback$mo6=_slicedToArray(_event$addCallback$mo5[0],2),eventName=_event$addCallback$mo6[0],eventCallback=_event$addCallback$mo6[1];expect(eventName).toBe('checkoutSuccess');eventCallback();// getAppPermissions should have been called 2nd time for checkoutSuccess event
|
|
41
|
+
expect(getAppPermissions).toHaveBeenCalledTimes(2);});});describe('increaseRejectionCount$',function(){var callback;beforeEach(function(){var _subscribe$mock$calls8=_slicedToArray(subscribe.mock.calls,3);var _subscribe$mock$calls9=_slicedToArray(_subscribe$mock$calls8[2],2);callback=_subscribe$mock$calls9[1];});it('should dispatch the increaseRejectionCount action when subscription emits',function(){callback(callbackParams);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(increaseRejectionCount());});});});
|