<commit_before>'use strict';

(function (angular, buildfire) {
  angular
    .module('loyaltyPluginWidget')
    .controller('WidgetHomeCtrl', ['$scope', 'ViewStack', 'LoyaltyAPI', 'STATUS_CODE', 'TAG_NAMES', 'LAYOUTS', 'DataStore', 'RewardCache', '$rootScope', '$sce', 'Context',
      function ($scope, ViewStack, LoyaltyAPI, STATUS_CODE, TAG_NAMES, LAYOUTS, DataStore, RewardCache, $rootScope, $sce, Context) {
        var WidgetHome = this;

        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;
        $rootScope.itemListbackgroundImage = "";
        $rootScope.itemDetailsBackgroundImage = "";

        $scope.setWidth = function () {
            $rootScope.deviceWidth = window.innerWidth > 0 ? window.innerWidth : '320';
        };

          //Refresh list of items on pulling the tile bar

          buildfire.datastore.onRefresh(function () {
              init();
          });

        //create new instance of buildfire carousel viewer
        WidgetHome.view = null;

        WidgetHome.listeners = {};
        $rootScope.deviceratio = window.devicePixelRatio;
        WidgetHome.PlaceHolderImageWidth = 60*window.devicePixelRatio + 'px';
        WidgetHome.PlaceHolderImageHeight = 60*window.devicePixelRatio + 'px';
        WidgetHome.PlaceHolderImageWidth3 = 110*window.devicePixelRatio + 'px';
        WidgetHome.PlaceHolderImageHeight3 = 60*window.devicePixelRatio + 'px';
        /**
         * Initialize current logged in user as null. This field is re-initialized if user is already logged in or user login user auth api.
         */
        WidgetHome.currentLoggedInUser = null;

        /**
         * Method to open a reward details page.
         */
        WidgetHome.openReward = function (reward, index) {
          RewardCache.setReward(reward);
          ViewStack.push({
            template: 'Item_Details',
            totalPoints: $rootScope.loyaltyPoints
          });
          buildfire.messaging.sendMessageToControl({
            type: 'OpenItem',
            data: reward,
            index: index
          });
        };

        /**
         * Method to fetch logged in user's loyalty points
         */
        WidgetHome.getLoyaltyPoints = function (userId) {
          var success = function (result) {
              $rootScope.loyaltyPoints = result.totalPoints;
            }
            , error = function (err) {
              if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting points data----------------------------------------', err);
              }
            };
            if (userId)
                LoyaltyAPI.getLoyaltyPoints(userId, WidgetHome.currentLoggedInUser.userToken, WidgetHome.context.instanceId).then(success, error);
        };

        /**
         * Method to fetch loyalty application and list of rewards
         */
        WidgetHome.getApplicationAndRewards = function () {
          var successLoyaltyRewards = function (result) {
              WidgetHome.loyaltyRewards = result;
              if (!WidgetHome.loyaltyRewards)
                WidgetHome.loyaltyRewards = [];
            }
            , errorLoyaltyRewards = function (err) {
                if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting data loyaltyRewards--------------------------------------', err);
              }
            };
          var successApplication = function (result) {
            if (result.image)
              WidgetHome.carouselImages = result.image;
              else
            WidgetHome.carouselImages = [];
            if (result.content && result.content.description)
              WidgetHome.description = result.content.description;
            RewardCache.setApplication(result);
          };

          var errorApplication = function (error) {
            WidgetHome.carouselImages = [];
            console.error('Error fetching loyalty application---------------------------------------------------',error);
          };

          if(WidgetHome.context && WidgetHome.context.instanceId){
            LoyaltyAPI.getApplication(WidgetHome.context.instanceId).then(successApplication, errorApplication);
            LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
          }
          else{
            Context.getContext(function (ctx) {
              console.log('COntext got successfully-----------------' +
                  '');
              WidgetHome.context = ctx;
              LoyaltyAPI.getApplication(WidgetHome.context.instanceId).then(successApplication, errorApplication);
              LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
            });
          }
        };

        /**
         * Method to show amount page where user can fill in the amount they have made purchase of.
         */
        WidgetHome.openGetPoints = function () {
          console.log(">>>>>>>>>>>>>>-----------------------");
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Amount',
              loyaltyPoints: $rootScope.loyaltyPoints

            });
          }
          else {
            WidgetHome.openLogin();
          }
        };

        /**
         * Method to open buildfire auth login pop up and allow user to login using credentials.
         */
        WidgetHome.openLogin = function () {
          buildfire.auth.login({}, function () {

          });
        };

        /**
         * This event listener is bound for "POINTS_REDEEMED" event broadcast
         */
        WidgetHome.listeners['POINTS_REDEEMED'] = $rootScope.$on('POINTS_REDEEMED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints - points;
        });

        /**
         * This event listener is bound for "POINTS_ADDED" event broadcast
         */
        WidgetHome.listeners['POINTS_ADDED'] = $rootScope.$on('POINTS_ADDED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints + points;
        });

        /**
         * This event listener is bound for "REWARD_DELETED" event broadcast
         */
        WidgetHome.listeners['REWARD_DELETED'] = $rootScope.$on('REWARD_DELETED', function (e, index) {
          if (index != -1)
            WidgetHome.loyaltyRewards.splice(index, 1);
        });

        /**
         * This event listener is bound for "REWARDS_SORTED" event broadcast
         */
        WidgetHome.listeners['REWARDS_SORTED'] = $rootScope.$on('REWARDS_SORTED', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        WidgetHome.listeners['Carousel:LOADED'] = $rootScope.$on("Carousel:LOADED", function () {
          WidgetHome.view = null;
          if (!WidgetHome.view) {
            WidgetHome.view = new buildfire.components.carousel.view("#carousel", [], "WideScreen");
          }
          if (WidgetHome.carouselImages) {
            WidgetHome.view.loadItems(WidgetHome.carouselImages, null, "WideScreen");
          } else {
            WidgetHome.view.loadItems([]);
          }
        });

        /**
         * This event listener is bound for "REWARD_ADDED" event broadcast
         */
        WidgetHome.listeners['REWARD_ADDED'] = $rootScope.$on('REWARD_ADDED', function (e, item) {
            var successLoyaltyRewards = function (result) {
                    WidgetHome.loyaltyRewards = result;
                    if (!WidgetHome.loyaltyRewards)
                        WidgetHome.loyaltyRewards = [];
                }
                , errorLoyaltyRewards = function (err) {
                    if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                        console.error('Error while getting data loyaltyRewards--------------------------------------', err);
                    }
                };
            LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
        });

        /**
         * This event listener is bound for "GOTO_HOME" event broadcast
         */
        WidgetHome.listeners['GOTO_HOME'] = $rootScope.$on('GOTO_HOME', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "APPLICATION_UPDATED" event broadcast
         */
        WidgetHome.listeners['APPLICATION_UPDATED'] = $rootScope.$on('APPLICATION_UPDATED', function (e, app) {
          if (app.image) {
            WidgetHome.carouselImages = app.image;
            if (WidgetHome.view) {
              WidgetHome.view.loadItems(WidgetHome.carouselImages);
            }
          }
          if (app.content && (app.content.description || app.content.description == ''))
            WidgetHome.description = app.content.description;
          RewardCache.setApplication(app);
        });

        /**
         * This event listener is bound for "REFRESH_APP" event broadcast
         */
        WidgetHome.listeners['REFRESH_APP'] = $rootScope.$on('REFRESH_APP', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        WidgetHome.showDescription = function (description) {
          return !((description == '

') || (description == '

'));
        };

        /**
         * Method to parse and show description in html format
         */
        WidgetHome.safeHtml = function (html) {
            if (html) {
                var $html = $('
', {html: html});
                $html.find('iframe').each(function (index, element) {
                    var src = element.src;
                    console.log('element is: ', src, src.indexOf('http'));
                    src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
                    element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
                });
                return $sce.trustAsHtml($html.html());
            }
        };

        /*
         * Fetch user's data from datastore
         */

        var init = function () {
          var success = function (result) {
                if(result && result.data){
                  console.log('BUILDFIRE GET--------------------------LOYALTY---------RESULT',result);
                  WidgetHome.data = result.data;
                }
                else{
                  WidgetHome.data={
                    design:{
                      listLayout:LAYOUTS.listLayout[0].name
                    }
                  };
                }
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.settings)
                WidgetHome.data.settings = {};
              if (!WidgetHome.data.design.listLayout) {
                WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
              }
              if (!WidgetHome.data.design.itemListbackgroundImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
              }
              if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                $rootScope.itemDetailsBackgroundImage = "";
              } else {
                $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
              }
            }
            , error = function (err) {
                WidgetHome.data={design:{listLayout:LAYOUTS.listLayout[0].name}};
              console.error('Error while getting data', err);
              };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(success, error);
          WidgetHome.getApplicationAndRewards();
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("_______________________", user);
            if (user) {
              WidgetHome.currentLoggedInUser = user;
              WidgetHome.getLoyaltyPoints(user._id);
              $scope.$digest();
            }
          });
        };

        var logoutCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("_______________________", user);
           // if (user) {
              WidgetHome.currentLoggedInUser = null;
             // WidgetHome.getLoyaltyPoints(user._id);
              $scope.$digest();
           // }
          });
        };

        var onUpdateCallback = function (event) {
          console.log("++++++++++++++++++++++++++", event);
          setTimeout(function () {
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.LOYALTY_INFO:
                  WidgetHome.data = event.data;
                  if (!WidgetHome.data.design)
                    WidgetHome.data.design = {};
                  if (!WidgetHome.data.design.listLayout) {
                    WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
                  }
                  if (!WidgetHome.data.design.itemListbackgroundImage) {
                    $rootScope.itemListbackgroundImage = "";
                  } else {
                    $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
                  }
                  if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                    $rootScope.itemDetailsBackgroundImage = "";
                  } else {
                    $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
                  }
                  break;
              }
              $scope.$digest();
              $rootScope.$digest();
            }
          }, 0);
        };

        /**
         * DataStore.onUpdate() is bound to listen any changes in datastore
         */
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        /**
         * onLogin() listens when user logins using buildfire.auth api.
         */
        buildfire.auth.onLogin(loginCallback);
        buildfire.auth.onLogout(logoutCallback);

        /**
         * Check for current logged in user, if yes fetch its loyalty points
         */
        buildfire.auth.getCurrentUser(function (err, user) {
          console.log("_______________________", user);
          if (user) {
            WidgetHome.currentLoggedInUser = user;
            if (!WidgetHome.context) {
              Context.getContext(function (ctx) {
                console.log('Context     ==============================================================',ctx);
                WidgetHome.context = ctx;
                WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
                $scope.$digest();
              });
            } else {
              WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
              $scope.$digest();
            }
          }
        });

          WidgetHome.listeners['REWARD_UPDATED'] = $rootScope.$on('REWARD_UPDATED', function (e, item, index) {
              if (item && WidgetHome.loyaltyRewards && WidgetHome.loyaltyRewards.length) {
                  WidgetHome.loyaltyRewards.some(function (reward, index) {
                      if (reward._id == item._id) {
                          WidgetHome.loyaltyRewards[index] = item;
                          return true;
                      }
                  })
              }
          });

        $scope.$on("$destroy", function () {
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>destroyed");
          for (var i in WidgetHome.listeners) {
            if (WidgetHome.listeners.hasOwnProperty(i)) {
              WidgetHome.listeners[i]();
            }
          }
        });

        Context.getContext(function (ctx) {
          console.log('COntext got successfully-----------------' +
              '');
          WidgetHome.context = ctx;
        });
        init();

          WidgetHome.listeners['CHANGED'] = $rootScope.$on('VIEW_CHANGED', function (e, type, view) {
              if (!ViewStack.hasViews()) {
                  // bind on refresh again
                  buildfire.datastore.onRefresh(function () {
                      init();
                  });
              }
          });
      }]);
})(window.angular, window.buildfire);

<commit_msg>fix adding reward points in emulator<commit_after>'use strict';

(function (angular, buildfire) {
  angular
    .module('loyaltyPluginWidget')
    .controller('WidgetHomeCtrl', ['$scope', 'ViewStack', 'LoyaltyAPI', 'STATUS_CODE', 'TAG_NAMES', 'LAYOUTS', 'DataStore', 'RewardCache', '$rootScope', '$sce', 'Context',
      function ($scope, ViewStack, LoyaltyAPI, STATUS_CODE, TAG_NAMES, LAYOUTS, DataStore, RewardCache, $rootScope, $sce, Context) {
        var WidgetHome = this;

        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;
        $rootScope.itemListbackgroundImage = "";
        $rootScope.itemDetailsBackgroundImage = "";

        $scope.setWidth = function () {
            $rootScope.deviceWidth = window.innerWidth > 0 ? window.innerWidth : '320';
        };

          //Refresh list of items on pulling the tile bar

          buildfire.datastore.onRefresh(function () {
              init();
          });

        //create new instance of buildfire carousel viewer
        WidgetHome.view = null;

        WidgetHome.listeners = {};
        $rootScope.deviceratio = window.devicePixelRatio;
        WidgetHome.PlaceHolderImageWidth = 60*window.devicePixelRatio + 'px';
        WidgetHome.PlaceHolderImageHeight = 60*window.devicePixelRatio + 'px';
        WidgetHome.PlaceHolderImageWidth3 = 110*window.devicePixelRatio + 'px';
        WidgetHome.PlaceHolderImageHeight3 = 60*window.devicePixelRatio + 'px';
        /**
         * Initialize current logged in user as null. This field is re-initialized if user is already logged in or user login user auth api.
         */
        WidgetHome.currentLoggedInUser = null;

        /**
         * Method to open a reward details page.
         */
        WidgetHome.openReward = function (reward, index) {
          RewardCache.setReward(reward);
          ViewStack.push({
            template: 'Item_Details',
            totalPoints: $rootScope.loyaltyPoints
          });
          buildfire.messaging.sendMessageToControl({
            type: 'OpenItem',
            data: reward,
            index: index
          });
        };

        /**
         * Method to fetch logged in user's loyalty points
         */
        WidgetHome.getLoyaltyPoints = function (userId) {
          var success = function (result) {
              $rootScope.loyaltyPoints = result.totalPoints;
            }
            , error = function (err) {
              if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting points data----------------------------------------', err);
              }
            };
            if (userId)
                LoyaltyAPI.getLoyaltyPoints(userId, WidgetHome.currentLoggedInUser.userToken, WidgetHome.context.instanceId).then(success, error);
        };

        /**
         * Method to fetch loyalty application and list of rewards
         */
        WidgetHome.getApplicationAndRewards = function () {
          var successLoyaltyRewards = function (result) {
              WidgetHome.loyaltyRewards = result;
              if (!WidgetHome.loyaltyRewards)
                WidgetHome.loyaltyRewards = [];
            }
            , errorLoyaltyRewards = function (err) {
                if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting data loyaltyRewards--------------------------------------', err);
              }
            };
          var successApplication = function (result) {
            if (result.image)
              WidgetHome.carouselImages = result.image;
              else
            WidgetHome.carouselImages = [];
            if (result.content && result.content.description)
              WidgetHome.description = result.content.description;
            RewardCache.setApplication(result);
          };

          var errorApplication = function (error) {
            WidgetHome.carouselImages = [];
            console.error('Error fetching loyalty application---------------------------------------------------',error);
          };
          WidgetHome.getLoyaltyPoints();
          if(WidgetHome.context && WidgetHome.context.instanceId){
            getLoggedInUser();
            LoyaltyAPI.getApplication(WidgetHome.context.instanceId).then(successApplication, errorApplication);
            LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
          }
          else{
            Context.getContext(function (ctx) {
              console.log('COntext got successfully-----------------' +
                  '');
              WidgetHome.context = ctx;
              LoyaltyAPI.getApplication(WidgetHome.context.instanceId).then(successApplication, errorApplication);
              LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
            });
          }
        };

        /**
         * Method to show amount page where user can fill in the amount they have made purchase of.
         */
        WidgetHome.openGetPoints = function () {
          console.log(">>>>>>>>>>>>>>-----------------------");
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Amount',
              loyaltyPoints: $rootScope.loyaltyPoints

            });
          }
          else {
            WidgetHome.openLogin();
          }
        };

        /**
         * Method to open buildfire auth login pop up and allow user to login using credentials.
         */
        WidgetHome.openLogin = function () {
          buildfire.auth.login({}, function () {

          });
        };

        /**
         * This event listener is bound for "POINTS_REDEEMED" event broadcast
         */
        WidgetHome.listeners['POINTS_REDEEMED'] = $rootScope.$on('POINTS_REDEEMED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints - points;
        });

        /**
         * This event listener is bound for "POINTS_ADDED" event broadcast
         */
        WidgetHome.listeners['POINTS_ADDED'] = $rootScope.$on('POINTS_ADDED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints + points;
        });

        /**
         * This event listener is bound for "REWARD_DELETED" event broadcast
         */
        WidgetHome.listeners['REWARD_DELETED'] = $rootScope.$on('REWARD_DELETED', function (e, index) {
          if (index != -1)
            WidgetHome.loyaltyRewards.splice(index, 1);
        });

        /**
         * This event listener is bound for "REWARDS_SORTED" event broadcast
         */
        WidgetHome.listeners['REWARDS_SORTED'] = $rootScope.$on('REWARDS_SORTED', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        WidgetHome.listeners['Carousel:LOADED'] = $rootScope.$on("Carousel:LOADED", function () {
          WidgetHome.view = null;
          if (!WidgetHome.view) {
            WidgetHome.view = new buildfire.components.carousel.view("#carousel", [], "WideScreen");
          }
          if (WidgetHome.carouselImages) {
            WidgetHome.view.loadItems(WidgetHome.carouselImages, null, "WideScreen");
          } else {
            WidgetHome.view.loadItems([]);
          }
        });

        /**
         * This event listener is bound for "REWARD_ADDED" event broadcast
         */
        WidgetHome.listeners['REWARD_ADDED'] = $rootScope.$on('REWARD_ADDED', function (e, item) {
            var successLoyaltyRewards = function (result) {
                    WidgetHome.loyaltyRewards = result;
                    if (!WidgetHome.loyaltyRewards)
                        WidgetHome.loyaltyRewards = [];
                }
                , errorLoyaltyRewards = function (err) {
                    if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                        console.error('Error while getting data loyaltyRewards--------------------------------------', err);
                    }
                };
            LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
        });

        /**
         * This event listener is bound for "GOTO_HOME" event broadcast
         */
        WidgetHome.listeners['GOTO_HOME'] = $rootScope.$on('GOTO_HOME', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "APPLICATION_UPDATED" event broadcast
         */
        WidgetHome.listeners['APPLICATION_UPDATED'] = $rootScope.$on('APPLICATION_UPDATED', function (e, app) {
          if (app.image) {
            WidgetHome.carouselImages = app.image;
            if (WidgetHome.view) {
              WidgetHome.view.loadItems(WidgetHome.carouselImages);
            }
          }
          if (app.content && (app.content.description || app.content.description == ''))
            WidgetHome.description = app.content.description;
          RewardCache.setApplication(app);
        });

        /**
         * This event listener is bound for "REFRESH_APP" event broadcast
         */
        WidgetHome.listeners['REFRESH_APP'] = $rootScope.$on('REFRESH_APP', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        WidgetHome.showDescription = function (description) {
          return !((description == '

') || (description == '

'));
        };

        /**
         * Method to parse and show description in html format
         */
        WidgetHome.safeHtml = function (html) {
            if (html) {
                var $html = $('
', {html: html});
                $html.find('iframe').each(function (index, element) {
                    var src = element.src;
                    console.log('element is: ', src, src.indexOf('http'));
                    src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
                    element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
                });
                return $sce.trustAsHtml($html.html());
            }
        };

        /*
         * Fetch user's data from datastore
         */

        var init = function () {
          var success = function (result) {
                if(result && result.data){
                  console.log('BUILDFIRE GET--------------------------LOYALTY---------RESULT',result);
                  WidgetHome.data = result.data;
                }
                else{
                  WidgetHome.data={
                    design:{
                      listLayout:LAYOUTS.listLayout[0].name
                    }
                  };
                }
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.settings)
                WidgetHome.data.settings = {};
              if (!WidgetHome.data.design.listLayout) {
                WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
              }
              if (!WidgetHome.data.design.itemListbackgroundImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
              }
              if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                $rootScope.itemDetailsBackgroundImage = "";
              } else {
                $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
              }
            }
            , error = function (err) {
                WidgetHome.data={design:{listLayout:LAYOUTS.listLayout[0].name}};
              console.error('Error while getting data', err);
              };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(success, error);
          WidgetHome.getApplicationAndRewards();
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("_______________________", user);
            if (user) {
              WidgetHome.currentLoggedInUser = user;
              WidgetHome.getLoyaltyPoints(user._id);
              $scope.$digest();
            }
          });
        };

        var logoutCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("_______________________", user);
           // if (user) {
              WidgetHome.currentLoggedInUser = null;
             // WidgetHome.getLoyaltyPoints(user._id);
              $scope.$digest();
           // }
          });
        };

        var onUpdateCallback = function (event) {
          console.log("++++++++++++++++++++++++++", event);
          setTimeout(function () {
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.LOYALTY_INFO:
                  WidgetHome.data = event.data;
                  if (!WidgetHome.data.design)
                    WidgetHome.data.design = {};
                  if (!WidgetHome.data.design.listLayout) {
                    WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
                  }
                  if (!WidgetHome.data.design.itemListbackgroundImage) {
                    $rootScope.itemListbackgroundImage = "";
                  } else {
                    $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
                  }
                  if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                    $rootScope.itemDetailsBackgroundImage = "";
                  } else {
                    $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
                  }
                  break;
              }
              $scope.$digest();
              $rootScope.$digest();
            }
          }, 0);
        };

        /**
         * DataStore.onUpdate() is bound to listen any changes in datastore
         */
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        /**
         * onLogin() listens when user logins using buildfire.auth api.
         */
        buildfire.auth.onLogin(loginCallback);
        buildfire.auth.onLogout(logoutCallback);

        /**
         * Check for current logged in user, if yes fetch its loyalty points
         */
        var getLoggedInUser = function(){
          buildfire.auth.getCurrentUser(function (err, user) {
          console.log("_______________________", user);
          if (user) {
            WidgetHome.currentLoggedInUser = user;
            if (!WidgetHome.context) {
              Context.getContext(function (ctx) {
                console.log('Context     ==============================================================',ctx);
                WidgetHome.context = ctx;
                WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
                $scope.$digest();
              });
            } else {
              WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
              $scope.$digest();
            }
          }
        });
        };
        getLoggedInUser();
          WidgetHome.listeners['REWARD_UPDATED'] = $rootScope.$on('REWARD_UPDATED', function (e, item, index) {
              if (item && WidgetHome.loyaltyRewards && WidgetHome.loyaltyRewards.length) {
                  WidgetHome.loyaltyRewards.some(function (reward, index) {
                      if (reward._id == item._id) {
                          WidgetHome.loyaltyRewards[index] = item;
                          return true;
                      }
                  })
              }
          });

        $scope.$on("$destroy", function () {
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>destroyed");
          for (var i in WidgetHome.listeners) {
            if (WidgetHome.listeners.hasOwnProperty(i)) {
              WidgetHome.listeners[i]();
            }
          }
        });

        Context.getContext(function (ctx) {
          console.log('COntext got successfully-----------------' +
              '');
          WidgetHome.context = ctx;
        });
        init();

          WidgetHome.listeners['CHANGED'] = $rootScope.$on('VIEW_CHANGED', function (e, type, view) {
              if (!ViewStack.hasViews()) {
                  // bind on refresh again
                  buildfire.datastore.onRefresh(function () {
                      init();
                  });
              }
          });
      }]);
})(window.angular, window.buildfire);

<|endoftext|>


<commit_before>process.env.BLUEBIRD_DEBUG = true;
process.env.BLUEBIRD_LONG_STACK_TRACES = true;

// var Promise   = require('bluebird');
require('tapdate')();
var suite     = require('../../../suite');
var bootstrap = require('../../../bootstrap');
var neo4j     = require('../../../../io/neo4j');
var agent     = bootstrap.agent;
var joi       = require('joi');
var schemas   = require('../../../../schemas');

var DATE_TOLERANCE = 5;
var VALID_RESPONSE_SCHEMA = joi.object().keys({
	message: schemas.model.message,
});

suite('POST /message', (s) => {

	s.after(() => neo4j.end());

	s.test('post a new topic', (t) => bootstrap({ users: 2 }).then((conditions) => {
		var user = conditions.users[1];
		return agent
			.post('/message')
			.set('Authorization', `Bearer ${user.token}`)
			.send({
				body: ' Hello, **this** is a _new_ message.\n\nThis [message](http://google.com) should become a topic. ',
			})
			.then((res) => {
				t.equal(res.status, 202, 'http accepted');
				return schemas.validate(res.body, VALID_RESPONSE_SCHEMA);
			})
			.then(() => neo4j.run('MATCH (m:Message)-[r]->(u:User) RETURN *'))
			.then((results) => {
				results = results[0];
				t.equal(results.m.properties.body, 'Hello, **this** is a _new_ message.\n\nThis [message](http://google.com) should become a topic.', 'message body is trimmed');
				t.equal(results.m.properties.content, 'Hello, this is a new message.\nThis message should become a topic.', 'message content contains no html');
				t.dateNear(results.m.properties.create_time, new Date(), DATE_TOLERANCE, 'create time is set');
				t.dateNear(results.m.properties.update_time, new Date(), DATE_TOLERANCE, 'update time is set');
				t.dateSame(results.m.properties.create_time, results.m.properties.update_time, 'second', 'create time and update time are identical');
				t.equal(results.r.type, 'CREATED_BY', 'CREATED_BY relationship exists');
				t.equal(results.r.start.low, results.m.identity.low, 'between the message');
				t.equal(results.r.end.low, results.u.identity.low, 'and the user');
				t.equal(results.u.properties.username, user.username, 'bound to the correct user');
				// console.log(require('util').inspect(results, { colors: true, depth: 6 }));
			});
	}));

	s.test('post a new topic with a body of only whitespace', (t) => bootstrap({ users: 1 }).then((conditions) => {
		var user = conditions.users[0];
		return agent
			.post('/message')
			.set('Authorization', `Bearer ${user.token}`)
			.send({
				body: '    ',
			})
			.then((res) => {
				t.equal(res.status, 400, 'http bad request');
				t.deepEqual(res.body, {
					errors: [
						{
							title: 'Request data is missing or in the incorrect format.',
							detail: '"body" is not allowed to be empty',
							path: 'body',
						},
						{
							title: 'Request data is missing or in the incorrect format.',
							detail: '"body" length must be at least 1 characters long',
							path: 'body',
						},
					],
				}, 'correct error output');
				return schemas.validate(res.body, schemas.response.validationError);
			})
			.then(() => neo4j.run('MATCH (m:Message) RETURN m'))
			.then((results) => {
				t.equal(results.length, 0, 'No messages were created');
			});
	}));

});
<commit_msg>Added test for message post without body<commit_after>process.env.BLUEBIRD_DEBUG = true;
process.env.BLUEBIRD_LONG_STACK_TRACES = true;

// var Promise   = require('bluebird');
require('tapdate')();
var suite     = require('../../../suite');
var bootstrap = require('../../../bootstrap');
var neo4j     = require('../../../../io/neo4j');
var agent     = bootstrap.agent;
var joi       = require('joi');
var schemas   = require('../../../../schemas');

var DATE_TOLERANCE = 5;
var VALID_RESPONSE_SCHEMA = joi.object().keys({
	message: schemas.model.message,
});

suite('POST /message', (s) => {

	s.after(() => neo4j.end());

	s.test('post a new topic', (t) => bootstrap({ users: 2 }).then((conditions) => {
		var user = conditions.users[1];
		return agent
			.post('/message')
			.set('Authorization', `Bearer ${user.token}`)
			.send({
				body: ' Hello, **this** is a _new_ message.\n\nThis [message](http://google.com) should become a topic. ',
			})
			.then((res) => {
				t.equal(res.status, 202, 'http accepted');
				return schemas.validate(res.body, VALID_RESPONSE_SCHEMA);
			})
			.then(() => neo4j.run('MATCH (m:Message)-[r]->(u:User) RETURN *'))
			.then((results) => {
				results = results[0];
				t.equal(results.m.properties.body, 'Hello, **this** is a _new_ message.\n\nThis [message](http://google.com) should become a topic.', 'message body is trimmed');
				t.equal(results.m.properties.content, 'Hello, this is a new message.\nThis message should become a topic.', 'message content contains no html');
				t.dateNear(results.m.properties.create_time, new Date(), DATE_TOLERANCE, 'create time is set');
				t.dateNear(results.m.properties.update_time, new Date(), DATE_TOLERANCE, 'update time is set');
				t.dateSame(results.m.properties.create_time, results.m.properties.update_time, 'second', 'create time and update time are identical');
				t.equal(results.r.type, 'CREATED_BY', 'CREATED_BY relationship exists');
				t.equal(results.r.start.low, results.m.identity.low, 'between the message');
				t.equal(results.r.end.low, results.u.identity.low, 'and the user');
				t.equal(results.u.properties.username, user.username, 'bound to the correct user');
				// console.log(require('util').inspect(results, { colors: true, depth: 6 }));
			});
	}));

	s.test('post a new topic with a body of only whitespace', (t) => bootstrap({ users: 1 }).then((conditions) => {
		var user = conditions.users[0];
		return agent
			.post('/message')
			.set('Authorization', `Bearer ${user.token}`)
			.send({
				body: '    ',
			})
			.then((res) => {
				t.equal(res.status, 400, 'http bad request');
				t.deepEqual(res.body, {
					errors: [
						{
							title: 'Request data is missing or in the incorrect format.',
							detail: '"body" is not allowed to be empty',
							path: 'body',
						},
						{
							title: 'Request data is missing or in the incorrect format.',
							detail: '"body" length must be at least 1 characters long',
							path: 'body',
						},
					],
				}, 'correct error output');
				return schemas.validate(res.body, schemas.response.validationError);
			})
			.then(() => neo4j.run('MATCH (m:Message) RETURN m'))
			.then((results) => {
				t.equal(results.length, 0, 'No messages were created');
			});
	}));

	s.test('post a new topic with no body', (t) => bootstrap({ users: 1 }).then((conditions) => {
		var user = conditions.users[0];
		return agent
			.post('/message')
			.set('Authorization', `Bearer ${user.token}`)
			.send({})
			.then((res) => {
				t.equal(res.status, 400, 'http bad request');
				t.deepEqual(res.body, {
					errors: [
						{
							title: 'Request data is missing or in the incorrect format.',
							detail: '"body" is required',
							path: 'body',
						},
					],
				}, 'correct error output');
				return schemas.validate(res.body, schemas.response.validationError);
			})
			.then(() => neo4j.run('MATCH (m:Message) RETURN m'))
			.then((results) => {
				t.equal(results.length, 0, 'No messages were created');
			});
	}));

});
<|endoftext|>


<commit_before>function make_group(data) {
  data = data || {};

  return {
    id: data.id || 1,
    score: data.score || 5,
    count: 1,
    permalink: 'http://example.com',
    title: 'test',
    message: 'test message',
    lastSeen: '2012-01-13T08:15:36Z',
    timeSpent: 0,
    project: 'default',
    canResolve: false,
    logger: 'root',
    versions: [],
    tags: [],
    version: data.version || 0
  };
}

describe("OrderedElementsView", function() {
  var view;
  var group1;
  var group2;
  var group3;
  var group4;
  var member;
  var TestModel;

  it("maintains correct models", function() {
      TestModel = Backbone.Model.extend({
          defaults: {foo: "bar"}
      });

      view = new app.views.OrderedElementsView({
          id: 'foo',
          model: TestModel
      });
      view.$parent = $('

');

      view.addMember({
        id: 1,
        biz: "baz"
      });

      member = view.collection.get(1)
      assert.equal(member.get("biz"), "baz");
      assert.equal(member.get("foo"), "bar");
  });

  describe("without initial members", function() {
    beforeEach(function() {
      view = new app.views.OrderedElementsView({
          id: 'foo'
      });
      view.$parent = $('

');
    });

    it("should suggest its not loaded", function() {
      assert.isFalse(view.loaded);
    });

    it("has status text to loading", function() {
      assert.equal(view.$empty.html(), view.loadingMessage);
    });
  });

  describe("with initial members", function() {
    beforeEach(function() {
      group1 = make_group({id: 1, score: 3});
      view = new app.views.OrderedElementsView({
          id: 'foo',
          members: [group1]
      });
    });

    it("should suggest its loaded", function() {
      assert.isTrue(view.loaded);
    });

    it("has status text to loading", function() {
      assert.notEqual(view.$empty.html(), view.loadingMessage);
    });
  });

  describe(".reset", function() {

    describe("with data", function(){
      beforeEach(function(){
        group1 = make_group({id: 1, score: 3});
        view = new app.views.OrderedElementsView({
            id: 'foo'
        });
        view.collection.reset = sinon.spy();
        view.reset([group1]);
      });

      it("calls collection.reset with data", function() {
        assert.isTrue(view.collection.reset.calledOnce);
      });

      it("suggests its loaded", function() {
        assert.isTrue(view.loaded);
      });

      it("changes status text to empty", function() {
        assert.equal(view.$empty.html(), view.emptyMessage);
      });
    });

    describe("with empty list of data", function(){
      beforeEach(function(){
        view = new app.views.OrderedElementsView({
            id: 'foo'
        });
        group1 = make_group({id: 1, score: 3});
        view.collection.reset = sinon.spy();
        view.reset([]);
      });

      it("calls collection.reset with data", function() {
        assert.isTrue(view.collection.reset.called);
        assert.isTrue(view.collection.reset.calledWithExactly([]));
      });

      it("suggests its loaded", function() {
        assert.isTrue(view.loaded);
      });

      it("changes status text to empty", function() {
        assert.equal(view.$empty.html(), view.emptyMessage);
      });
    });

    describe("with no data value", function(){
      beforeEach(function(){
        view = new app.views.OrderedElementsView({
            id: 'foo'
        });
        group1 = make_group({id: 1, score: 3});
        view.collection.reset = sinon.spy();
        view.reset();
      });

      it("calls collection.reset with no value", function() {
        assert.isTrue(view.collection.reset.called);
        assert.isTrue(view.collection.reset.calledWithExactly());
      });

      it("suggests its not loaded", function() {
        assert.isFalse(view.loaded);
      });

      it("changes status text to loading", function() {
        assert.equal(view.$empty.html(), view.loadingMessage);
      });
    });
  });

  describe(".extend", function() {
    beforeEach(function(){
      view = new app.views.OrderedElementsView({
          id: 'foo'
      });
      view.addMember = sinon.spy();
    });

    it("calls addMember for each item", function() {
      group1 = make_group({id: 1, score: 3});
      group2 = make_group({id: 2, score: 5});

      view.extend([group1, group2]);
      assert.equal(view.addMember.callCount, 2);
      assert.isTrue(view.addMember.calledWithExactly(group1));
      assert.isTrue(view.addMember.calledWithExactly(group2));
    });
  });

  describe(".addMember", function() {
    beforeEach(function(){
      view = new app.views.OrderedElementsView({
          id: 'foo',
          maxItems: 3
      });
    });

    it("adds to collection", function() {
      group = make_group();
      view.addMember(group);
      assert.strictEqual(view.collection.models[0].get('id'), group.id);
    });

    it("replaces in collection", function() {
      group = make_group();
      view.addMember(group);
      view.addMember(group);
      view.addMember(group);
      assert.strictEqual(view.collection.length, 1);
    });

    it("truncated to max items", function(){
      group1 = make_group({id: 1, score: 3});
      group2 = make_group({id: 2, score: 5});
      group3 = make_group({id: 3, score: 2});
      group4 = make_group({id: 4, score: 6});

      view.addMember(group1);
      view.addMember(group2);
      view.addMember(group3);
      view.addMember(group4);

      assert.strictEqual(view.collection.length, 3);
    });

    it("sorts members by score after insert", function(){
      view.addMember(make_group({id: 1, score: 3}));
      view.addMember(make_group({id: 2, score: 5}));

      assert.strictEqual(view.collection.models[0].get('id'), 2);
      assert.strictEqual(view.collection.models[1].get('id'), 1);
    });

    it("doesnt move members that didnt re-rank", function(){
      view.addMember(make_group({id: 1, score: 1}));
      view.addMember(make_group({id: 2, score: 10}));
      view.addMember(make_group({id: 3, score: 100}));
      // change the score, but keep it in the same rank
      view.addMember(make_group({id: 2, score: 50}));

      assert.strictEqual(view.collection.models[0].get('id'), 3);
      assert.strictEqual(view.collection.models[1].get('id'), 2);
      assert.strictEqual(view.collection.models[2].get('id'), 1);
    });

    it("resorts members when they change", function(){
      view.addMember(make_group({id: 1, score: 1, version: 1}));
      view.addMember(make_group({id: 2, score: 10, version: 1}));
      view.addMember(make_group({id: 3, score: 100, version: 1}));
      // change the score so it should be at the top
      view.addMember(make_group({id: 1, score: 1000, version: 2}));

      assert.strictEqual(view.collection.models[0].get('id'), 1);
      assert.strictEqual(view.collection.models[1].get('id'), 3);
      assert.strictEqual(view.collection.models[2].get('id'), 2);
    });

    it("correctly handles truncating lowest score values", function(){
      view.addMember(make_group({id: 1, score: 1}));
      view.addMember(make_group({id: 2, score: 10}));
      view.addMember(make_group({id: 3, score: 100}));
      view.addMember(make_group({id: 4, score: 52}));
      view.addMember(make_group({id: 5, score: 51}));
      view.addMember(make_group({id: 2, score: 50}));

      assert.strictEqual(view.collection.length, 3);
      assert.strictEqual(view.collection.models[0].get('id'), 3);
      assert.strictEqual(view.collection.models[1].get('id'), 4);
      assert.strictEqual(view.collection.models[2].get('id'), 5);
    });

  });

  describe(".renderMemberInContainer", function() {
    var TestView = Backbone.View.extend({
      render: function(){
        var node = $('

');
        node.attr('id', 'test-' + this.model.get('id'));
        this.$el.html(node);
      }
    });

    beforeEach(function(){
      view = new app.views.OrderedElementsView({
          id: 'test-',
          maxItems: 3,
          view: TestView
      });
      view.$parent = $('

');

      group1 = make_group({id: 1, score: 3});
      group2 = make_group({id: 2, score: 5});
      group3 = make_group({id: 3, score: 2});

      view.addMember(group1);
      view.addMember(group2);
      view.addMember(group3);
    });

    it("pushes highest scored elements to the top on change", function(){
      group3.score = 100;
      view.addMember(group3);
      group4 = make_group({id: 4, score: 500});
      view.addMember(group4);
      assert.strictEqual(view.$parent.find('li').length, view.collection.length);
    });

    it("has the correct number of elements", function(){
      assert.strictEqual(view.$parent.find('li').length, view.collection.length);
    });

    it("has list elements sorted correctly", function(){
      view.$parent.find('li').each(function(_, el){
        assert.strictEqual(this.id, 'test-' + view.collection.models[_].id);
      });
    });
  });
});
<commit_msg>Remove no longer valid test<commit_after><|endoftext|>


<commit_before>'use strict';

var util = require('util');
var common = require('../modules/common-functions');
var constants = require('../modules/constants');

var OUTGOINGS_QUESTIONS = constants.OUTGOINGS_QUESTIONS;
var OUTGOINGS_QUESTION_ERRORS = {
  'rent': 'Enter 0 if you don’t pay rent',
  'maintenance': 'Enter 0 if this doesn’t apply to you',
  'childcare': 'Please provide an amount'
};

module.exports = {
  'Start page': function(client) {
    client.startService();
  },

  'Scope diagnosis': function(client) {
    client.scopeDiagnosis(constants.SCOPE_PATHS.debtInScope);
  },

  'Interstitial page': function(client) {
    client.interstitialPage();
  },

  'About you': function(client) {
    client.aboutSetAllToNo(true);
  },

  'Income': function(client) {
    client
      .waitForElementVisible('input[name="your_income-other_income-per_interval_value"]', 5000)
      .assert.urlContains('/income')
      .assert.containsText('h1', 'Your money coming in')
      .setValue('input[name="your_income-maintenance-per_interval_value"]', 0)
      .setValue('input[name="your_income-pension-per_interval_value"]', 0)
      .setValue('input[name="your_income-other_income-per_interval_value"]', 0)
      .submitForm('form')
    ;
  },

  'Outgoings': function(client) {
    client
      .waitForElementVisible('input[name="income_contribution"]', 5000)
      .assert.urlContains('/outgoings')
      .assert.containsText('h1', 'Your outgoings')
    ;
  },

  'Childcare fields': function(client) {
    client
      .back()
      .waitForElementPresent('input[name="your_income-other_income-per_interval_value"]', 5000)
      .back()
      .waitForElementPresent('input[name="have_partner"]', 5000)
      .setYesNoFields('have_children', 1)
      .setValue('input[name="num_children"]', 1)
      .submitForm('form')
      .waitForElementVisible('input[name="your_income-other_income-per_interval_value"]', 5000)
      .clearValue('input[name="your_income-maintenance-per_interval_value"]')
      .clearValue('input[name="your_income-pension-per_interval_value"]')
      .clearValue('input[name="your_income-other_income-per_interval_value"]')
      .setValue('input[name="your_income-child_tax_credit-per_interval_value"]', 0)
      .setValue('input[name="your_income-maintenance-per_interval_value"]', 0)
      .setValue('input[name="your_income-pension-per_interval_value"]', 0)
      .setValue('input[name="your_income-other_income-per_interval_value"]', 0)
      .submitForm('form')
      .waitForElementVisible('input[name="income_contribution"]', 5000)
      .assert.visible('input[name="childcare-per_interval_value"]')
      .assert.visible('select[name="childcare-interval_period"]')
    ;
  },

  'Context-dependent text for partner': function(client) {
    client
      .assert.containsText('body', 'Money you pay your landlord')
      .assert.containsText('body', 'Money you pay to an ex-partner for their living costs')
      .assert.containsText('body', 'Money you pay per month towards your criminal legal aid')
      .assert.containsText('body', 'Money you pay for your child to be looked after while you work or study')
      .back()
      .waitForElementVisible('input[name="your_income-other_income-per_interval_value"]', 5000)
      .back()
      .waitForElementPresent('input[name="have_partner"]', 5000)
      .setYesNoFields('have_partner', 1)
      .setYesNoFields(['in_dispute', 'partner_is_employed', 'partner_is_self_employed'], 0)
      .submitForm('form')
      .waitForElementPresent('input[name="your_income-other_income-per_interval_value"]', 5000)

      .setValue('input[name="your_income-maintenance-per_interval_value"]', 0)
      .setValue('input[name="your_income-pension-per_interval_value"]', 0)
      .setValue('input[name="your_income-other_income-per_interval_value"]', 0)
      .setValue('input[name="partner_income-maintenance-per_interval_value"]', 0)
      .setValue('input[name="partner_income-pension-per_interval_value"]', 0)
      .setValue('input[name="partner_income-other_income-per_interval_value"]', 0)

      .submitForm('form')
      .waitForElementPresent('input[name="income_contribution"]', 5000)
      .assert.urlContains('/outgoings')
      .assert.containsText('h1', 'You and your partner’s outgoings')
      .assert.containsText('body', 'Money you and your partner pay your landlord')
      .assert.containsText('body', 'Money you and/or your partner pay to an ex-partner for their living costs')
      .assert.containsText('body', 'Money you and/or your partner pay per month towards your criminal legal aid')
      .assert.containsText('body', 'Money you and your partner pay for your child to be looked after while you work or study')
    ;
  },

  'Validation': function(client) {
    OUTGOINGS_QUESTIONS.forEach(function(item) {
      client.setValue(util.format('input[name=%s-per_interval_value]', item), '500');
      common.submitAndCheckForFieldError(client, [{
        name: item + '-per_interval_value',
        errorText: 'Please select a time period from the drop down'
      }]);
      client.clearValue(util.format('input[name=%s-per_interval_value]', item));
      common.setDropdownValue(client, item + '-interval_period', 'per_month');
      common.submitAndCheckForFieldError(client, [{
        name: item + '-per_interval_value',
        errorText: OUTGOINGS_QUESTION_ERRORS[item]
      }]);
    });

    common.submitAndCheckForFieldError(client, [{
      name: 'income_contribution',
      errorText: 'Enter 0 if this doesn’t apply to you'
    }]);

    OUTGOINGS_QUESTIONS.forEach(function(item) {
      client.setValue(util.format('input[name=%s-per_interval_value]', item), '500');
    });
    client
      .setValue('input[name="income_contribution"]', 0)
      .submitForm('form')
      .waitForElementVisible('.answers-summary', 5000)
      .submitForm('form')
      .waitForElementPresent('input[name="callback-contact_number"]', 5000)
      .assert.urlContains('/result/eligible')
    ;

    client.end();
  }

};
<commit_msg>TEST: Fix outgoings page in Firefox/Chrome<commit_after>'use strict';

var util = require('util');
var common = require('../modules/common-functions');
var constants = require('../modules/constants');

var OUTGOINGS_QUESTIONS = constants.OUTGOINGS_QUESTIONS;
var OUTGOINGS_QUESTION_ERRORS = {
  'rent': 'Enter 0 if you don’t pay rent',
  'maintenance': 'Enter 0 if this doesn’t apply to you',
  'childcare': 'Please provide an amount'
};

module.exports = {
  'Start page': function(client) {
    client.startService();
  },

  'Scope diagnosis': function(client) {
    client.scopeDiagnosis(constants.SCOPE_PATHS.debtInScope);
  },

  'Interstitial page': function(client) {
    client.interstitialPage();
  },

  'About you': function(client) {
    client.aboutSetAllToNo(true);
  },

  'Income': function(client) {
    client
      .waitForElementVisible('input[name="your_income-other_income-per_interval_value"]', 5000)
      .assert.urlContains('/income')
      .assert.containsText('h1', 'Your money coming in')
      .setValue('input[name="your_income-maintenance-per_interval_value"]', 0)
      .setValue('input[name="your_income-pension-per_interval_value"]', 0)
      .setValue('input[name="your_income-other_income-per_interval_value"]', 0)
      .submitForm('form')
    ;
  },

  'Outgoings': function(client) {
    client
      .waitForElementVisible('input[name="income_contribution"]', 5000)
      .assert.urlContains('/outgoings')
      .assert.containsText('h1', 'Your outgoings')
    ;
  },

  'Childcare fields': function(client) {
    client
      .back()
      .waitForElementPresent('input[name="your_income-other_income-per_interval_value"]', 5000)
      .back()
      .waitForElementPresent('input[name="have_partner"]', 5000)
      .setYesNoFields('have_children', 1)
      .setValue('input[name="num_children"]', 1)
      .submitForm('form')
      .waitForElementVisible('input[name="your_income-other_income-per_interval_value"]', 5000)
      .clearValue('input[name="your_income-maintenance-per_interval_value"]')
      .clearValue('input[name="your_income-pension-per_interval_value"]')
      .clearValue('input[name="your_income-other_income-per_interval_value"]')
      .setValue('input[name="your_income-child_tax_credit-per_interval_value"]', 0)
      .setValue('input[name="your_income-maintenance-per_interval_value"]', 0)
      .setValue('input[name="your_income-pension-per_interval_value"]', 0)
      .setValue('input[name="your_income-other_income-per_interval_value"]', 0)
      .submitForm('form')
      .waitForElementVisible('input[name="income_contribution"]', 5000)
      .assert.visible('input[name="childcare-per_interval_value"]')
      .assert.visible('select[name="childcare-interval_period"]')
    ;
  },

  'Context-dependent text for partner': function(client) {
    client
      .assert.containsText('body', 'Money you pay your landlord')
      .assert.containsText('body', 'Money you pay to an ex-partner for their living costs')
      .assert.containsText('body', 'Money you pay per month towards your criminal legal aid')
      .assert.containsText('body', 'Money you pay for your child to be looked after while you work or study')
      .back()
      .waitForElementVisible('input[name="your_income-other_income-per_interval_value"]', 5000)
      .back()
      .waitForElementPresent('input[name="have_partner"]', 5000)
      .setYesNoFields('have_partner', 1)
      .pause(200)
      .setYesNoFields(['in_dispute', 'partner_is_employed', 'partner_is_self_employed'], 0)
      .submitForm('form')

      .fillInIncome(true, true, true)

      .assert.urlContains('/outgoings')
      .waitForElementPresent('input[name="income_contribution"]', 5000)
      .assert.containsText('h1', 'You and your partner’s outgoings')
      .assert.containsText('body', 'Money you and your partner pay your landlord')
      .assert.containsText('body', 'Money you and/or your partner pay to an ex-partner for their living costs')
      .assert.containsText('body', 'Money you and/or your partner pay per month towards your criminal legal aid')
      .assert.containsText('body', 'Money you and your partner pay for your child to be looked after while you work or study')
    ;
  },

  'Validation': function(client) {
    OUTGOINGS_QUESTIONS.forEach(function(item) {
      client.setValue(util.format('input[name=%s-per_interval_value]', item), '500');
      common.submitAndCheckForFieldError(client, [{
        name: item + '-per_interval_value',
        errorText: 'Please select a time period from the drop down'
      }]);
      client.clearValue(util.format('input[name=%s-per_interval_value]', item));
      common.setDropdownValue(client, item + '-interval_period', 'per_month');
      common.submitAndCheckForFieldError(client, [{
        name: item + '-per_interval_value',
        errorText: OUTGOINGS_QUESTION_ERRORS[item]
      }]);
    });

    common.submitAndCheckForFieldError(client, [{
      name: 'income_contribution',
      errorText: 'Enter 0 if this doesn’t apply to you'
    }]);

    OUTGOINGS_QUESTIONS.forEach(function(item) {
      client.setValue(util.format('input[name=%s-per_interval_value]', item), '500');
    });
    client
      .setValue('input[name="income_contribution"]', 0)
      .submitForm('form')
      .waitForElementVisible('.answers-summary', 5000)
      .submitForm('form')
      .waitForElementPresent('input[name="callback-contact_number"]', 5000)
      .assert.urlContains('/result/eligible')
    ;

    client.end();
  }

};
<|endoftext|>


<commit_before>var global_config = {
    isPredict: false,
    canKill: false,
    canExport: false,
    isP5:false,
    config3: {
        isGroup: true,
        isDirect: true
    }
}

var app = new Vue({
    el:'#app',
    data:{
        sequence1:'',
        sequence2:'',
        sequence3:'',
        sequence4:'',
        sumValue:null,
        boldCode:null,
        rangeCode:null,
        gossipCode:null,
        wyfMessage:'这一行是统计数据展示区域',
        codesCount: 0,
        wyfCodes:[],
        config:global_config,
        welfareCode: null,
        boldCodeFive: null,
        myriabit: null,
        kilobit: null,
        hundred: null,
        decade:null,
        unit:null,
        p3Code:null,
        isRandomKill:null,
        randomKillCodes:null
    },
    methods:{
        doPermutate: function () {
            var paramArray = [];
            paramArray.push(this.sequence1);
            paramArray.push(this.sequence2);
            paramArray.push(this.sequence3);
            paramArray.push(this.sequence4);
            console.log('input:'+ JSON.stringify(paramArray));
            var args = {
                "riddles": paramArray,
                "targetCodeType": 3
            };
            this.wyfMessage = "正在计算...";
            axios({
              method: 'post',
              url: '/api/welfare/codes/predict',
              data: args
            }).then(function(response) {
                    app.handleThreeCodeResponse(response.data.data);
                })
                .catch(function(error){
                    console.log(error)
                });

        },
        handleThreeCodeResponse:function (data) {
            if(!data){
                this.wyfMessage='远程服务返回数据为空';
                console.log('请求数据为空');
                return;
            }
            this.welfareCode = data;
            this.wyfCodes = this.welfareCode.codes;
            this.config.isPredict=true;
            this.config.canKill=true;
            this.config.canExport=true;
            app.config.isP5 = false;
            console.log('isP5:' + this.config.isP5);
            if(this.welfareCode.codeTypeEnum == "DIRECT"){
                this.config.config3.isGroup = false;
                this.config.config3.isDirect = true;
                this.wyfMessage = "本次直选预测3D码: " + this.welfareCode.w3DCodes.length + " 注";
            }else {
                this.config.config3.isGroup = true;
                this.config.config3.isDirect = false;
                this.wyfMessage = "本次组选预测3D码: " + this.welfareCode.w3DCodes.length + " 注";
            }
        },

        handleFiveCodeResponse: function (data, msg, processId) {
            this.config.isP5 = true;
            this.welfareCode = data.wCodes;
            console.log('返回值:' + JSON.stringify(data.isRandomKill, null, 2));
            if(data.randomKill) {
                this.isRandomKill = data.randomKill;
            }

            var printCodes = [];
            for( idx in this.welfareCode){
                code = this.welfareCode[idx];
                // code.codes.reverse();
                var codeString = code.codes.join("");
                if(this.isRandomKill){
                    codeString = '[' + code.freq + ']' + codeString;
                }
                printCodes.push(codeString);
            }
            this.wyfCodes = printCodes;
            this.wyfMessage = "排5 " + msg + " 生成: "  + this.wyfCodes.length + " 注" + '(对子: ' + data.pairCodes + ' 注, 非对子: ' + data.nonPairCodes + ' 注)';
        },

        handleDownload: function(data) {
            console.log("downloads:"+data);
            if(data == null){
                console.log("request error.");
                return;
            }
            window.location = "/api/welfare/download?fileName=" + data;
        }
        ,

        transfer2Direct: function () {
            if(!this.config.isPredict){
                this.handleException("请先完成预测");
                return;
            }

            if(this.config.config3.isDirect){
                this.handleException("已经是直选");
                return;
            }

            axios({
                method:"POST",
                url:"/api/welfare/codes/transfer",
                data: app.welfareCode,
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function (response) {
                console.log("转码成功返回");
                app.handleThreeCodeResponse(response.data.data);
                console.log("转码完成");
                app.p3Code = app.welfareCode.w3DCodes;
                app.wyfMessage = "转码成功, 共计 " + app.welfareCode.w3DCodes.length + " 注.";
            }).catch(function(error){
                console.log("resp:" + JSON.stringify(error, null, 2));
                app.handleException("转换请求失败!");
            });

        },
        killCode: function () {
            if(!this.config.isPredict){
                this.handleException("请先完成预测");
                return;
            }

            var args = {
                "welfareCode": this.welfareCode,
                "sumValue": this.sumValue,
                "boldCode": this.boldCode,
                "gossip": this.gossipCode,
                "range": this.rangeCode
            };

            var count = this.wyfCodes.length;

            axios({
                method:"POST",
                url:"/api/welfare/codes/filter",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleThreeCodeResponse(response.data.data);
                app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.welfareCode.w3DCodes.length) + " 注, 余 " + app.welfareCode.w3DCodes.length + " 注.";
            }).catch(function(response) {
                console.log("resp:" + JSON.stringify(response.data, null, 2));
                app.handleException("杀码请求失败!");
            });

        },

        doPermutationFive: function () {
            if(!this.config.isPredict){
                this.handleException("请先完成排三组码");
                return;
            }

            if(this.config.isP5){
                this.handleException("已经执行过排5，如需重新排列，请先完成排三组码！")
                return;
            }

            var requestConfig = {
                method: "POST",
                url: "/api/p5/permutation/five",
                data: JSON.stringify(this.welfareCode.w3DCodes),
                headers: {
                    "Content-Type": "application/json; charset=UTF-8"
                }
            };
            app.wyfMessage = "正在计算排列5码...";

            axios(requestConfig).then(function (resp) {
                console.log(JSON.stringify(resp));
                app.handleFiveCodeResponse(resp.data.data, "预测", null);

            }).catch(function (reason) {
                console.log(reason);
            })
        },
        constProcess: function (processorId){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                filterType: processorId,
                wCodes: this.welfareCode
            };

            if(processorId == 9){
                args.p3Code = JSON.stringify(this.p3Code);
            }

            // console.log(JSON.stringify($rootScope.welfareCode, null, 2));
            console.log(JSON.stringify(args, null ,2));
            var count = this.wyfCodes.length;

            axios({
                method:"POST",
                url:"/api/p5/sequence/process",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleFiveCodeResponse(response.data.data, "杀码", processorId);
                app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.wyfCodes.length) + " 注, 余 " + app.wyfCodes.length + " 注."
                    + '(对子: ' + response.data.data.pairCodes + ' 注, 非对子: ' + response.data.data.nonPairCodes + ' 注)';
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("杀码请求失败!");
            });
        },

        boldProcess: function (processorId){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                filterType: processorId,
                wCodes: this.welfareCode,
                boldCodeFive: this.boldCodeFive
            };

            if(processorId == 14 ){
                args.randomCount = this.boldCodeFive;
                if(!this.boldCodeFive){
                    this.handleException("请输入随机杀注数!");
                    return;
                }
            }

            console.log("ddddd:" + JSON.stringify(args, null, 2));

            var count = this.wyfCodes.length;
            this.wyfMessage = "正在进行胆码杀...";
            axios({
                method:"POST",
                url:"/api/p5/sequence/process",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                console.log('收到返回:' + JSON.stringify(response.data.data, null ,2));
                app.handleFiveCodeResponse(response.data.data, "含X码杀", processorId);
                app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.wyfCodes.length) + " 注, 余 " + app.wyfCodes.length + " 注."
                    + '(对子: ' + response.data.data.pairCodes + ' 注, 非对子: ' + response.data.data.nonPairCodes + ' 注)';
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("杀码请求失败!");
            });
        },
        bitsProcess: function(){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var bitsArray = [];
            bitsArray.push(this.myriabit);
            bitsArray.push(this.kilobit);
            bitsArray.push(this.hundred);
            bitsArray.push(this.decade);
            bitsArray.push(this.unit);

            var args = {
                bits: bitsArray,
                wCodes: this.welfareCode
            };

            var count = this.wyfCodes.length;

            app.wyfMessage = "正在执行位杀...";

            axios({
                method:"POST",
                url:"/api/p5/bits/process",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleFiveCodeResponse(response.data.data, "位杀");
                app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.wyfCodes.length) + " 注, 余 " + app.wyfCodes.length + " 注."
                    + '(对子: ' + response.data.data.pairCodes + ' 注, 非对子: ' + response.data.data.nonPairCodes + ' 注)';
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("位杀请求失败!");
            });
        },

        exportCodes: function(){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                wCodes: this.welfareCode ,
                randomCount: this.boldCodeFive,
                randomKill: this.isRandomKill
            };

            console.log('canshu:' + JSON.stringify(args, null, 2));
            axios({
                method:"POST",
                url:"/api/p5/codes/export",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleDownload(response.data.data);
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("导出请求失败!");
            });
        },

        exportCodesHalfPage: function(){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                wCodes: this.welfareCode
            };

            // console.log(JSON.stringify($rootScope.welfareCode, null, 2));
            axios({
                method:"POST",
                url:"/api/p5/codes/export/half",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleDownload(response.data.data);
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("导出请求失败!");
            });
        },

        handleException: function (msg) {
            alert(msg);
        }
    }
});

<commit_msg>modify<commit_after>var global_config = {
    isPredict: false,
    canKill: false,
    canExport: false,
    isP5:false,
    config3: {
        isGroup: true,
        isDirect: true
    }
}

var app = new Vue({
    el:'#app',
    data:{
        sequence1:'',
        sequence2:'',
        sequence3:'',
        sequence4:'',
        sumValue:null,
        boldCode:null,
        rangeCode:null,
        gossipCode:null,
        wyfMessage:'这一行是统计数据展示区域',
        codesCount: 0,
        wyfCodes:[],
        config:global_config,
        welfareCode: null,
        boldCodeFive: null,
        myriabit: null,
        kilobit: null,
        hundred: null,
        decade:null,
        unit:null,
        p3Code:null,
        isRandomKill:null,
        randomKillCodes:null
    },
    methods:{
        doPermutate: function () {
            var paramArray = [];
            paramArray.push(this.sequence1);
            paramArray.push(this.sequence2);
            paramArray.push(this.sequence3);
            paramArray.push(this.sequence4);
            console.log('input:'+ JSON.stringify(paramArray));
            var args = {
                "riddles": paramArray,
                "targetCodeType": 3
            };
            this.wyfMessage = "正在计算...";
            axios({
              method: 'post',
              url: '/api/welfare/codes/predict',
              data: args
            }).then(function(response) {
                    app.handleThreeCodeResponse(response.data.data);
                })
                .catch(function(error){
                    console.log(error)
                });

        },
        handleThreeCodeResponse:function (data) {
            if(!data){
                this.wyfMessage='远程服务返回数据为空';
                console.log('请求数据为空');
                return;
            }
            this.welfareCode = data;
            this.wyfCodes = this.welfareCode.codes;
            this.config.isPredict=true;
            this.config.canKill=true;
            this.config.canExport=true;
            app.config.isP5 = false;
            console.log('isP5:' + this.config.isP5);
            if(this.welfareCode.codeTypeEnum == "DIRECT"){
                this.config.config3.isGroup = false;
                this.config.config3.isDirect = true;
                this.wyfMessage = "本次直选预测3D码: " + this.welfareCode.w3DCodes.length + " 注";
            }else {
                this.config.config3.isGroup = true;
                this.config.config3.isDirect = false;
                this.wyfMessage = "本次组选预测3D码: " + this.welfareCode.w3DCodes.length + " 注";
            }
        },

        handleFiveCodeResponse: function (data, msg, processId) {
            this.config.isP5 = true;
            this.welfareCode = data.wCodes;
            console.log('返回值:' + JSON.stringify(data.isRandomKill, null, 2));
            if(data.randomKill) {
                this.isRandomKill = data.randomKill;
            }

            var printCodes = [];
            for( idx in this.welfareCode){
                code = this.welfareCode[idx];
                // code.codes.reverse();
                var codeString = code.codes.join("");
                if(this.isRandomKill){
                    codeString = '[' + code.freq + ']' + codeString;
                }
                printCodes.push(codeString);
            }
            this.wyfCodes = printCodes;
            this.wyfMessage = "排5 " + msg + " 生成: "  + this.wyfCodes.length + " 注" + '(对子: ' + data.pairCodes + ' 注, 非对子: ' + data.nonPairCodes + ' 注)';
        },

        handleDownload: function(data) {
            console.log("downloads:"+data);
            if(data == null){
                console.log("request error.");
                return;
            }
            window.location = "/api/welfare/download?fileName=" + data;
        }
        ,

        transfer2Direct: function () {
            if(!this.config.isPredict){
                this.handleException("请先完成预测");
                return;
            }

            if(this.config.config3.isDirect){
                this.handleException("已经是直选");
                return;
            }

            axios({
                method:"POST",
                url:"/api/welfare/codes/transfer",
                data: app.welfareCode,
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function (response) {
                console.log("转码成功返回");
                app.handleThreeCodeResponse(response.data.data);
                console.log("转码完成");
                app.p3Code = app.welfareCode.w3DCodes;
                app.wyfMessage = "转码成功, 共计 " + app.welfareCode.w3DCodes.length + " 注.";
            }).catch(function(error){
                console.log("resp:" + JSON.stringify(error, null, 2));
                app.handleException("转换请求失败!");
            });

        },
        killCode: function () {
            if(!this.config.isPredict){
                this.handleException("请先完成预测");
                return;
            }

            var args = {
                "welfareCode": this.welfareCode,
                "sumValue": this.sumValue,
                "boldCode": this.boldCode,
                "gossip": this.gossipCode,
                "range": this.rangeCode
            };

            var count = this.wyfCodes.length;

            axios({
                method:"POST",
                url:"/api/welfare/codes/filter",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleThreeCodeResponse(response.data.data);
                app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.welfareCode.w3DCodes.length) + " 注, 余 " + app.welfareCode.w3DCodes.length + " 注.";
            }).catch(function(response) {
                console.log("resp:" + JSON.stringify(response.data, null, 2));
                app.handleException("杀码请求失败!");
            });

        },

        doPermutationFive: function () {
            if(!this.config.isPredict){
                this.handleException("请先完成排三组码");
                return;
            }

            if(this.config.isP5){
                this.handleException("已经执行过排5，如需重新排列，请先完成排三组码！")
                return;
            }

            var requestConfig = {
                method: "POST",
                url: "/api/p5/permutation/five",
                data: JSON.stringify(this.welfareCode.w3DCodes),
                headers: {
                    "Content-Type": "application/json; charset=UTF-8"
                }
            };
            app.wyfMessage = "正在计算排列5码...";

            axios(requestConfig).then(function (resp) {
                console.log(JSON.stringify(resp));
                app.handleFiveCodeResponse(resp.data.data, "预测", null);

            }).catch(function (reason) {
                console.log(reason);
            })
        },
        constProcess: function (processorId){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                filterType: processorId,
                wCodes: this.welfareCode
            };

            if(processorId == 9){
                args.p3Code = JSON.stringify(this.p3Code);
            }

            // console.log(JSON.stringify($rootScope.welfareCode, null, 2));
            console.log(JSON.stringify(args, null ,2));
            var count = this.wyfCodes.length;

            axios({
                method:"POST",
                url:"/api/p5/sequence/process",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleFiveCodeResponse(response.data.data, "杀码", processorId);
                app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.wyfCodes.length) + " 注, 余 " + app.wyfCodes.length + " 注."
                    + '(对子: ' + response.data.data.pairCodes + ' 注, 非对子: ' + response.data.data.nonPairCodes + ' 注)';
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("杀码请求失败!");
            });
        },

        boldProcess: function (processorId){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                filterType: processorId,
                wCodes: this.welfareCode,
                boldCodeFive: this.boldCodeFive
            };

            if(processorId == 14 ){
                args.randomCount = this.boldCodeFive;
                if(!this.boldCodeFive){
                    this.handleException("请输入随机杀注数!");
                    return;
                }
            }

            console.log("ddddd:" + JSON.stringify(args, null, 2));

            var count = this.wyfCodes.length;
            this.wyfMessage = "正在进行胆码杀...";
            axios({
                method:"POST",
                url:"/api/p5/sequence/process",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                console.log('收到返回:' + JSON.stringify(response.data.data, null ,2));
                app.handleFiveCodeResponse(response.data.data, "含X码杀", processorId);
                if(processorId == 14){
                    app.wyfMessage = "总计 " + count + " 注, 随机杀码 " + args.randomCount + " 注, 已增加频度."
                        + '(对子: ' + response.data.data.pairCodes + ' 注, 非对子: ' + response.data.data.nonPairCodes + ' 注)';
                }else {
                    app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.wyfCodes.length) + " 注, 余 " + app.wyfCodes.length + " 注."
                        + '(对子: ' + response.data.data.pairCodes + ' 注, 非对子: ' + response.data.data.nonPairCodes + ' 注)';
                }
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("杀码请求失败!");
            });
        },
        bitsProcess: function(){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var bitsArray = [];
            bitsArray.push(this.myriabit);
            bitsArray.push(this.kilobit);
            bitsArray.push(this.hundred);
            bitsArray.push(this.decade);
            bitsArray.push(this.unit);

            var args = {
                bits: bitsArray,
                wCodes: this.welfareCode
            };

            var count = this.wyfCodes.length;

            app.wyfMessage = "正在执行位杀...";

            axios({
                method:"POST",
                url:"/api/p5/bits/process",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleFiveCodeResponse(response.data.data, "位杀");
                app.wyfMessage = "总计 " + count + " 注, 杀码 " + (count - app.wyfCodes.length) + " 注, 余 " + app.wyfCodes.length + " 注."
                    + '(对子: ' + response.data.data.pairCodes + ' 注, 非对子: ' + response.data.data.nonPairCodes + ' 注)';
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("位杀请求失败!");
            });
        },

        exportCodes: function(){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                wCodes: this.welfareCode ,
                randomCount: this.boldCodeFive,
                randomKill: this.isRandomKill
            };

            console.log('canshu:' + JSON.stringify(args, null, 2));
            axios({
                method:"POST",
                url:"/api/p5/codes/export",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleDownload(response.data.data);
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("导出请求失败!");
            });
        },

        exportCodesHalfPage: function(){
            if(!this.config.isP5){
                this.handleException("请先完成排5");
                return;
            }

            var args = {
                wCodes: this.welfareCode
            };

            // console.log(JSON.stringify($rootScope.welfareCode, null, 2));
            axios({
                method:"POST",
                url:"/api/p5/codes/export/half",
                data: JSON.stringify(args),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8"
                }
            }).then(function(response) {
                app.handleDownload(response.data.data);
            }).catch(function(reason) {
                console.log(reason);
                app.handleException("导出请求失败!");
            });
        },

        handleException: function (msg) {
            alert(msg);
        }
    }
});

<|endoftext|>


<commit_before>'use strict';

angular.module('agreementsModule', []);

angular.module('agreementsModule').controller('agreementsController', ['$scope', '$state', '$log', 'Loader', function ($scope, $state, $log, Loader)
{
    $scope.currentPage = 1;
    $scope.pageSize    = 6;

    $scope.agreements = [ ];

    this.reload = function ()
    {
        Loader.load().then(function (data)
        {
            $scope.agreements = data.summaries;
            $log.debug("in examine: " + $scope.agreements.toString());
        });
    };

    this.reload();

    this.examine = function (agreement)
    {
        $log.debug("in examine");
        $state.go('agreement', agreement);
    };

    this.setCurrentPage = function (currentIndex)
    {
        $scope.currentPage = currentIndex;
    };

    this.decreaseCurrentPage = function()
    {
        $scope.currentPage--;
    };

    this.increaseCurrentPage = function()
    {
        $scope.currentPage--;
    };

    this.isCurrentPage = function (currentPage)
    {
        return $scope.currentPage == currentPage;
    };

    this.needsPagination = function ()
    {
        return $scope.agreements.length > $scope.pageSize;
    };

    this.havePreviousPage = function ()
    {
        return $scope.currentPage > 1;
    };

    this.haveNextPage = function ()
    {
        return $scope.currentPage < this.numberOfPages();
    };

    this.numberOfPages = function ()
    {
        return Math.ceil($scope.agreements.length / $scope.pageSize);
    };
}]);

angular.module('agreementsModule').filter('onpage', ['$scope', function ($scope)
{
    return function (input)
    {
        return input.slice($scope.currentPage * $scope.pageSize, ($scope.currentPage + 1) * $scope.pageSize);
    }
}]);

angular.module('agreementsModule').factory('Loader', ['$http', '$q', '$log', function ($http, $q, $log)
{
    return {
        load: function ()
        {
            var deferred = $q.defer();

            $http.get('/ws/agreements').
                success(function (data, status, headers, config)
                {
                    deferred.resolve(data);
                }).
                error(function (data, status, headers, config)
                {
                    deferred.resolve([ ]);
                });

            return deferred.promise;
        }
    };
}]);
<commit_msg>Debugging<commit_after>'use strict';

angular.module('agreementsModule', []);

angular.module('agreementsModule').controller('agreementsController', ['$scope', '$state', '$log', 'Loader', function ($scope, $state, $log, Loader)
{
    $scope.currentPage = 1;
    $scope.pageSize    = 6;

    $scope.agreements = [ ];

    this.reload = function ()
    {
        Loader.load().then(function (data)
        {
            $scope.agreements = data.summaries;
            $log.debug("in examine: " + JSON.stringify($scope.agreements.toString()));
        });
    };

    this.reload();

    this.examine = function (agreement)
    {
        $log.debug("in examine");
        $state.go('agreement', agreement);
    };

    this.setCurrentPage = function (currentIndex)
    {
        $scope.currentPage = currentIndex;
    };

    this.decreaseCurrentPage = function()
    {
        $scope.currentPage--;
    };

    this.increaseCurrentPage = function()
    {
        $scope.currentPage--;
    };

    this.isCurrentPage = function (currentPage)
    {
        return $scope.currentPage == currentPage;
    };

    this.needsPagination = function ()
    {
        return $scope.agreements.length > $scope.pageSize;
    };

    this.havePreviousPage = function ()
    {
        return $scope.currentPage > 1;
    };

    this.haveNextPage = function ()
    {
        return $scope.currentPage < this.numberOfPages();
    };

    this.numberOfPages = function ()
    {
        return Math.ceil($scope.agreements.length / $scope.pageSize);
    };
}]);

angular.module('agreementsModule').filter('onpage', ['$scope', function ($scope)
{
    return function (input)
    {
        return input.slice($scope.currentPage * $scope.pageSize, ($scope.currentPage + 1) * $scope.pageSize);
    }
}]);

angular.module('agreementsModule').factory('Loader', ['$http', '$q', '$log', function ($http, $q, $log)
{
    return {
        load: function ()
        {
            var deferred = $q.defer();

            $http.get('/ws/agreements').
                success(function (data, status, headers, config)
                {
                    deferred.resolve(data);
                }).
                error(function (data, status, headers, config)
                {
                    deferred.resolve([ ]);
                });

            return deferred.promise;
        }
    };
}]);
<|endoftext|>


<commit_before>'use strict';

/* Directives */

var directiveModule = angular.module('BootstrapThemePreviewerApp.directives', []).
  directive('appVersion', ['version', function(version) {
    return function(scope, element, attrs) {
      elm.text(version);
    };
  }]);
  //scope contains the resolved variable
  //  element.attr('value') vs scope.color.hex
/*
directiveModule.directive('colorPicker',
     function() {
      return function(scope, element, attrs) {

          element.ColorPickerSliders({
            color: scope.color.hex,
            order: {
                preview:1,
                hsl: 2,
                opacity:3

            }
          });
  //console.log(attrs+" - "+ element.attr('value'));
      };
     }
  );  //*/

directiveModule.directive('colorPicker',
     function() {
       return {
          restrict: 'A',
          // This HTML will replace the directive.
          replace: true,
          transclude: true,
          // The linking function will add behavior to the template
          link: function postLink(scope, element, attrs) {

           element.click( function(){
              var slider = $(this).ColorPickerSliders({
                  color: scope.color.hex,
                  order: {
                      preview:1,
                      hsl: 2,
                      opacity:3
                  } ,
                  onchange: function(container, color) {
                    //update scope variables double bindings
                    //tinycolor object is in color.tiny
                     scope.color.hex = color.tiny.toHexString();
                     scope.color.rgb = color.tiny.toRgbString();
                     scope.color.name = color.tiny.toName();
                     scope.color.name = $.xcolor.nearestname(color.tiny.toHexString());
                     scope.color.hsl = color.tiny.toHslString();
                     //TODO dynamically update fontcolor
                     //fire DOM updates
                     scope.$digest();
                  }
                });
              //force display
              $(this).trigger("colorpickersliders.showPopup");
            });

            element.blur( function(){
              //hide colorpicker
               $(this).trigger("colorpickersliders.hidePopup");
               //destroy DOM to
               $(this).ColorPickerSliders().empty();
               console.log("blured - "+scope.color.hex);
            });
            //console.log(attrs+" - "+ element.attr('value')+" - "+scope.color.hex);
          }
      };
});  //*/
<commit_msg>added two ways binding for colorpicker<commit_after>'use strict';

/* Directives */

var directiveModule = angular.module('BootstrapThemePreviewerApp.directives', []).
  directive('appVersion', ['version', function(version) {
    return function(scope, element, attrs) {
      elm.text(version);
    };
  }]);
  //scope contains the resolved variable
  //  element.attr('value') vs scope.color.hex
/*
directiveModule.directive('colorPicker',
     function() {
      return function(scope, element, attrs) {

          element.ColorPickerSliders({
            color: scope.color.hex,
            order: {
                preview:1,
                hsl: 2,
                opacity:3

            }
          });
  //console.log(attrs+" - "+ element.attr('value'));
      };
     }
  );  //*/

directiveModule.directive('colorPicker',
     function() {
       return {
          restrict: 'A',
          // This HTML will replace the directive.
          replace: true,
          transclude: true,
          // The linking function will add behavior to the template
          link: function postLink(scope, element, attrs) {

           element.click( function(){
              var slider = $(this).ColorPickerSliders({
                  color: scope.color.hex,
                  order: {
                      preview:1,
                      hsl: 2,
                      opacity:3
                  } ,
                  onchange: function(container, color) {
                    //update scope variables double bindings
                    //tinycolor object is in color.tiny
                     scope.color.hex = color.tiny.toHexString();
                     scope.color.rgb = color.tiny.toRgbString();
                     //scope.color.name = color.tiny.toName();
                     scope.color.name = $.xcolor.nearestname(color.tiny.toHexString());
                     scope.color.hsl = color.tiny.toHslString();
                     //TODO dynamically update fontcolor
                     //fire DOM updates
                     scope.$digest();
                  }
                });
              //force display
              $(this).trigger("colorpickersliders.showPopup");
            });

            element.blur( function(){
              //hide colorpicker
               $(this).trigger("colorpickersliders.hidePopup");
               //destroy DOM to
               $(this).ColorPickerSliders().empty();
               console.log("blured - "+scope.color.hex);
            });
            //console.log(attrs+" - "+ element.attr('value')+" - "+scope.color.hex);
          }
      };
});  //*/
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = function configureServer(app, config) {
  // Add logging via Morgan middleware
  if (_.get(config, 'options.logs')) {
    app.use(require('morgan')());
  }

  // Add gzipping via compression middleware
  if (_.get(config, 'options.gzip')) {
    app.use(require('compression')());
  }
};
<commit_msg>Fix utilities middleware<commit_after>var _ = require('lodash');

module.exports = function configureServer(app, config) {
  // Add logging via Morgan middleware
  if (_.get(config, 'server.options.logs')) {
    app.use(require('morgan')());
  }

  // Add gzipping via compression middleware
  if (_.get(config, 'server.options.gzip')) {
    app.use(require('compression')());
  }
};
<|endoftext|>