<commit_before>'use strict';

(function (angular) {
    angular
        .module('geoFencePluginContent')
        .controller('ContentHomeCtrl', ['$scope', '$timeout', 'Utils', 'COLLECTIONS', 'DB', 'Modals', 'DEFAULT_DATA',
            function ($scope, $timeout, Utils, COLLECTIONS, DB, Modals, DEFAULT_DATA) {
                console.log('--------ContentHomeCtrl Controller Loaded-----');
                var ContentHome = this;
                var _skip = 0,
                    _limit = 10;
                var searchOptions = {
                    filter: {"$json.title": {"$regex": '/*'}},
                    skip: _skip,
                    limit: _limit + 1 // the plus one is to check if there are any more
                };
                ContentHome.radiusMiles=10;
                ContentHome.radiusFeet=0;
                ContentHome.geoAction = {
                    data: {
                        title: '',
                        actionToPerform: {},
                        epicenter: {address: '', coordinates: {lat: '', long: ''}},
                        radius: 10 //in miles
                    }
                };
                ContentHome.masterGeoAction = {
                    data: {
                        title: '',
                        actionToPerform: {},
                        epicente: {address: '', coordinates: {lat: '', long: ''}},
                        radius: 10 //in miles
                    }
                };

                ContentHome.selectItem = function (item) {
                    console.log('selectItem method called-------------------', item);
                    if (item && item.data) {
                        ContentHome.geoAction = item;
                        updateMasterItem(item);
                        if (item.data.epicenter && item.data.epicenter.coordinates) {
                            ContentHome.center = item.data.epicenter.coordinates;
                            ContentHome.selectedLocation = item.data.epicenter.address;
                        }
                    }

                };

                var tmrDelayForItem = null
                    , GeoActions = new DB(COLLECTIONS.GeoActions)
                    , updating = false
                    , isNewItemInserted = false;
                ContentHome.center = {};

                ContentHome.setLocation = function (data) {
                    console.log('SetLoaction caleed-------------------', data);
                    ContentHome.selectedLocation = data.location;
                    ContentHome.currentCoordinates = data.coordinates;

                    ContentHome.geoAction.data.epicenter.address = data.location;
                    ContentHome.geoAction.data.epicenter.coordinates = ContentHome.center;

                    ContentHome.center.lat = data.coordinates[1];
                    ContentHome.center.lng = data.coordinates[0];
                    $scope.$digest();
                };

                ContentHome.setCoordinates = function () {
                    var latlng = '';
                    console.log('ng-enter---------------------called-----ContentHome.selectedLocation-------------', ContentHome.selectedLocation);
                    function successCallback(resp) {
                        console.error('Successfully validated coordinates-----------', resp);
                        if (resp) {
                            ContentHome.center = {
                                lng: parseInt(ContentHome.selectedLocation.split(",")[1].trim()),
                                lat: parseInt(ContentHome.selectedLocation.split(",")[0].trim())
                            };
                        } else {
                            //errorCallback();
                        }
                    }

                    function errorCallback(err) {
                        console.error('Error while validating coordinates------------', err);
                        ContentHome.validCoordinatesFailure = true;
                        $timeout(function () {
                            ContentHome.validCoordinatesFailure = false;
                        }, 5000);
                    }

                    if (ContentHome.selectedLocation) {
                        latlng = ContentHome.selectedLocation.split(',')[1] + "," + ContentHome.selectedLocation.split(',')[0]
                    }

                    Utils.validLongLats(latlng).then(successCallback, errorCallback);
                };
                ContentHome.clearData = function () {
                    if (!ContentHome.selectedLocation) {
                        ContentHome.center = {
                            lng: '',
                            lat: ''
                        };
                    }
                };

                ContentHome.validCopyAddressFailure = false;
                ContentHome.locationAutocompletePaste = function () {
                    function error() {
                        console.error('ERROOR emethpdd called');
                        ContentHome.validCopyAddressFailure = true;
                        $timeout(function () {
                            ContentHome.validCopyAddressFailure = false;
                        }, 5000);

                    }

                    $timeout(function () {
                        console.log('val>>>', $("#googleMapAutocomplete").val());
                        console.log('.pac-container .pac-item', $(".pac-container .pac-item").length);
                        if ($(".pac-container .pac-item").length) {
                            var firstResult = $(".pac-container .pac-item:first").find('.pac-matched').map(function () {
                                return $(this).text();
                            }).get().join(); // + ', ' + $(".pac-container .pac-item:first").find('span:last').text();
                            console.log('firstResult', firstResult);
                            var geocoder = new google.maps.Geocoder();
                            geocoder.geocode({"address": firstResult}, function (results, status) {
                                if (status == google.maps.GeocoderStatus.OK) {
                                    var lat = results[0].geometry.location.lat(),
                                        lng = results[0].geometry.location.lng();
                                    ContentHome.geoAction.data.epicenter.address = firstResult;
                                    ContentHome.geoAction.data.epicenter.lat = lat;
                                    ContentHome.geoAction.data.epicenter.lng = lng;
                                    ContentHome.center = {lat: lat, lng: lng};
                                    $("#googleMapAutocomplete").blur();
                                }
                                else {
                                    console.error('' +
                                        'Error else parts of google');
                                    error();
                                }
                            });
                        }
                        else if (ContentHome.selectedLocation && ContentHome.selectedLocation.split(',').length) {
                            console.log('Location found---------selectedLocation------------', ContentHome.selectedLocation.split(',').length, ContentHome.selectedLocation.split(','));
                            ContentHome.setCoordinates();
                        }
                        else {
                            error();
                        }
                    }, 1000);

                };

                ContentHome.addNewItem = function () {
                    ContentHome.geoAction = angular.copy(DEFAULT_DATA.GEO_ACTION);
                    ContentHome.selectedLocation = '';
                    ContentHome.center = {
                        lat: '',
                        lng: ''
                    };
                    ContentHome.radiusMiles=10;
                    ContentHome.radiusFeet=0;
                };

                /**
                 * ContentHome.noMore tells if all data has been loaded
                 */
                ContentHome.noMore = false;

                ContentHome.isBusy = false;
                /**
                 * ContentHome.getMore is used to load the items
                 */
                ContentHome.getMore = function () {
                    if (ContentHome.isBusy && !ContentHome.noMore) {
                        return;
                    }
                    ContentHome.isBusy = true;
                    GeoActions.find(searchOptions).then(function success(result) {
                        if (result.length <= _limit) {// to indicate there are more
                            ContentHome.noMore = true;
                        }
                        else {
                            result.pop();
                            searchOptions.skip = searchOptions.skip + _limit;
                            ContentHome.noMore = false;
                        }
                        ContentHome.items = ContentHome.items ? ContentHome.items.concat(result) : result;
                        console.log('items>>>', angular.copy(ContentHome.items));
                        ContentHome.isBusy = false;
                    }, function fail() {
                        ContentHome.isBusy = false;
                    });
                };

                ContentHome.updateRadius=function(){
                    console.log('updateRadius=============method called---------',ContentHome.radiusMiles,ContentHome.radiusFeet);
                    ContentHome.geoAction.data.radius= parseInt(ContentHome.radiusMiles)+parseFloat(ContentHome.radiusFeet/5280);
                    console.log('ContentHome.geoAction.data.radius------------in updateRadius method------',ContentHome.geoAction.data.radius);
                };

                /**
                 * ContentHome.removeListItem() used to delete an item from section list
                 * @param index tells the index of item to be deleted.
                 */
                ContentHome.removeListItem = function (index, $event) {

                    if ("undefined" == typeof index) {
                        return;
                    }
                    var item = ContentHome.items[index];
                    if ("undefined" !== typeof item) {
                        //buildfire.navigation.scrollTop();

                        Modals.removePopupModal({title: '', event: $event}).then(function (result) {
                            if (result) {
                                if(item.id==ContentHome.geoAction.id){
                                    ContentHome.geoAction=angular.copy(DEFAULT_DATA.GEO_ACTION);
                                    ContentHome.selectedLocation = '';
                                    ContentHome.center = {
                                        lat: '',
                                        lng: ''
                                    };
                                    ContentHome.radiusMiles=10;
                                    ContentHome.radiusFeet=0;
                                }
                                GeoActions.delete(item.id).then(function (data) {
                                    ContentHome.items.splice(index, 1);
                                }, function (err) {
                                    console.error('Error while deleting an item-----', err);
                                });
                            }
                            else {
                                console.info('Unable to load data.');
                            }
                        }, function (cancelData) {
                            //do something on cancel
                        });
                    }
                };

                /**
                 * This updateMasterItem will update the ContentMedia.masterItem with passed item
                 * @param item
                 */
                function updateMasterItem(item) {
                    ContentHome.masterGeoAction = angular.copy(item);
                }

                /**
                 * This resetItem will reset the ContentMedia.item with ContentMedia.masterItem
                 */
                function resetItem() {
                    ContentHome.geoAction.data = angular.copy(ContentHome.masterGeoAction);
                }

                /**
                 * isUnChanged to check whether there is change in controller media item or not
                 * @param item
                 * @returns {*|boolean}
                 */
                function isUnChanged(item) {
                    return angular.equals(item, ContentHome.masterGeoAction);
                }

                function insertAndUpdate(_item) {
                    console.log('insertAndUpdate-----------------method called-----', _item);
                    updating = true;
                    if (_item.id) {
                        GeoActions.update(_item.id, _item.data).then(function (data) {
                            console.log('Item updated successfully----------------', data);
                            updateMasterItem(data);
                            updating = false;
                        }, function (err) {
                            updating = false;
                            //console.log('Error while updating data---', err);
                        });
                    }
                   // else if (!isNewItemInserted) {
                    else{
                        isNewItemInserted = true;
                        GeoActions.insert(_item.data).then(function (data) {
                            ContentHome.geoAction = data;
                            ContentHome.items.push(data);
                            updateMasterItem(data);
                            updating = false;
                            console.log('new ---------------- Item inserted-------------------------------', data);
                            //updateMasterItem(ContentItem.item);

                        }, function (err) {
                            //resetItem();
                            updating = false;
                            //isNewItemInserted = false;
                        });
                    }
                }

                //to validate the action with title
                function isValidItem(action) {
                    return action.data && action.data.title;
                }

                /**
                 * updateItemWithDelay called when ever there is some change in current geo action
                 * @param _item
                 */
                function updateItemsWithDelay(_item) {
                    if (updating)
                        return;
                    if (tmrDelayForItem) {
                        $timeout.cancel(tmrDelayForItem);
                    }
                    ContentHome.isItemValid = isValidItem(_item);
                    if (_item && !isUnChanged(_item) && ContentHome.isItemValid) {
                        tmrDelayForItem = $timeout(function () {
                            insertAndUpdate(_item);
                        }, 300);
                    }
                }

                $scope.$watch(function () {
                    return ContentHome.geoAction;
                }, updateItemsWithDelay, true);

            }]);
})(window.angular);<commit_msg>COde Refactored of content.home.controller<commit_after>'use strict';

(function (angular) {
    angular
        .module('geoFencePluginContent')
        .controller('ContentHomeCtrl', ['$scope', '$timeout', 'Utils', 'COLLECTIONS', 'DB', 'Modals', 'DEFAULT_DATA',
            function ($scope, $timeout, Utils, COLLECTIONS, DB, Modals, DEFAULT_DATA) {
                console.log('--------ContentHomeCtrl Controller Loaded-----');
                var ContentHome = this;
                var _skip, _limit, searchOptions, tmrDelayForItem, GeoActions, updating;

                ContentHome.selectItem = function (item) {
                    console.log('selectItem method called-------------------', item);
                    if (item && item.data) {
                        ContentHome.geoAction = item;
                        updateMasterItem(item);
                        if (item.data.epicenter && item.data.epicenter.coordinates) {
                            ContentHome.center = item.data.epicenter.coordinates;
                            ContentHome.selectedLocation = item.data.epicenter.address;
                        }
                    }

                };

                ContentHome.setLocation = function (data) {
                    console.log('SetLoaction caleed-------------------', data);
                    ContentHome.selectedLocation = data.location;
                    ContentHome.currentCoordinates = data.coordinates;

                    ContentHome.geoAction.data.epicenter.address = data.location;
                    ContentHome.geoAction.data.epicenter.coordinates = ContentHome.center;

                    ContentHome.center.lat = data.coordinates[1];
                    ContentHome.center.lng = data.coordinates[0];
                    $scope.$digest();
                };

                ContentHome.setCoordinates = function () {
                    var latlng = '';
                    function successCallback(resp) {
                        if (resp) {
                            ContentHome.center = {
                                lng: parseInt(ContentHome.selectedLocation.split(",")[1].trim()),
                                lat: parseInt(ContentHome.selectedLocation.split(",")[0].trim())
                            };
                        } else {
                            console.log('coordinates validated successfully but no data recieved');
                        }
                    }

                    function errorCallback(err) {
                        console.error('Error while validating coordinates------------', err);
                        ContentHome.validCoordinatesFailure = true;
                        $timeout(function () {
                            ContentHome.validCoordinatesFailure = false;
                        }, 5000);
                    }

                    if (ContentHome.selectedLocation) {
                        latlng = ContentHome.selectedLocation.split(',')[1] + "," + ContentHome.selectedLocation.split(',')[0]
                    }

                    Utils.validLongLats(latlng).then(successCallback, errorCallback);
                };
                ContentHome.clearData = function () {
                    if (!ContentHome.selectedLocation) {
                        ContentHome.center = {
                            lng: '',
                            lat: ''
                        };
                    }
                };

                ContentHome.locationAutocompletePaste = function () {
                    $timeout(function () {
                        if ($(".pac-container .pac-item").length) {
                            var firstResult = $(".pac-container .pac-item:first").find('.pac-matched').map(function () {
                                return $(this).text();
                            }).get().join(); // + ', ' + $(".pac-container .pac-item:first").find('span:last').text();
                            console.log('firstResult', firstResult);
                            var geocoder = new google.maps.Geocoder();
                            geocoder.geocode({"address": firstResult}, function (results, status) {
                                if (status == google.maps.GeocoderStatus.OK) {
                                    var lat = results[0].geometry.location.lat(),
                                        lng = results[0].geometry.location.lng();
                                    ContentHome.geoAction.data.epicenter.address = firstResult;
                                    ContentHome.geoAction.data.epicenter.lat = lat;
                                    ContentHome.geoAction.data.epicenter.lng = lng;
                                    ContentHome.center = {lat: lat, lng: lng};
                                    $("#googleMapAutocomplete").blur();
                                }
                                else {
                                    console.error('--lat long does not find-- corresponding to input');
                                }
                            });
                        }
                        else if (ContentHome.selectedLocation && (ContentHome.selectedLocation.split(',').length==2)) {
                            ContentHome.setCoordinates();
                        }
                        else {
                            console.error('InValid Input');
                        }
                    }, 1000);

                };

                ContentHome.addNewItem = function () {
                    ContentHome.geoAction = angular.copy(DEFAULT_DATA.GEO_ACTION);
                    ContentHome.selectedLocation = '';
                    ContentHome.center = {
                        lat: '',
                        lng: ''
                    };
                    ContentHome.radiusMiles = 10;
                    ContentHome.radiusFeet = 0;
                };

                /**
                 * ContentHome.noMore tells if all data has been loaded
                 */
                ContentHome.noMore = false;

                ContentHome.isBusy = false;
                /**
                 * ContentHome.getMore is used to load the items
                 */
                ContentHome.getMore = function () {
                    if (ContentHome.isBusy && !ContentHome.noMore) {
                        return;
                    }
                    ContentHome.isBusy = true;
                    GeoActions.find(searchOptions).then(function success(result) {
                        if (result.length <= _limit) {// to indicate there are more
                            ContentHome.noMore = true;
                        }
                        else {
                            result.pop();
                            searchOptions.skip = searchOptions.skip + _limit;
                            ContentHome.noMore = false;
                        }
                        ContentHome.items = ContentHome.items ? ContentHome.items.concat(result) : result;
                        console.log('items----------------->>>', angular.copy(ContentHome.items));
                        ContentHome.isBusy = false;
                    }, function fail() {
                        ContentHome.isBusy = false;
                    });
                };

                ContentHome.updateRadius = function () {
                    ContentHome.geoAction.data.radius = parseInt(ContentHome.radiusMiles) + parseFloat(ContentHome.radiusFeet / 5280);
                };

                /**
                 * ContentHome.removeListItem() used to delete an item from section list
                 * @param index
                 * @param event
                 */
                ContentHome.removeListItem = function (index, event) {

                    if ("undefined" == typeof index) {
                        return;
                    }
                    var item = ContentHome.items[index];
                    if ("undefined" !== typeof item) {

                        Modals.removePopupModal({event: event1}).then(function (result) {
                            if (result) {
                                if (item.id == ContentHome.geoAction.id) {
                                    ContentHome.geoAction = angular.copy(DEFAULT_DATA.GEO_ACTION);
                                    ContentHome.selectedLocation = '';
                                    ContentHome.center = {
                                        lat: '',
                                        lng: ''
                                    };
                                    ContentHome.radiusMiles = 10;
                                    ContentHome.radiusFeet = 0;
                                }
                                GeoActions.delete(item.id).then(function (data) {
                                    ContentHome.items.splice(index, 1);
                                }, function (err) {
                                    console.error('Error while deleting an item-----', err);
                                });
                            }
                            else {
                                console.info('Unable to load data.');
                            }
                        }, function (cancelData) {
                            //do something on cancel
                        });
                    }
                };

                /**
                 * This updateMasterItem will update the ContentMedia.masterItem with passed item
                 * @param item
                 */
                function updateMasterItem(item) {
                    ContentHome.masterGeoAction = angular.copy(item);
                }

                /**
                 * This resetItem will reset the ContentMedia.item with ContentMedia.masterItem
                 */
                function resetItem() {
                    ContentHome.geoAction.data = angular.copy(ContentHome.masterGeoAction);
                }

                /**
                 * isUnChanged to check whether there is change in controller media item or not
                 * @param item
                 * @returns {*|boolean}
                 */
                function isUnChanged(item) {
                    return angular.equals(item, ContentHome.masterGeoAction);
                }

                function insertAndUpdate(_item) {
                    console.log('insertAndUpdate-----------------method called-----', _item);
                    updating = true;
                    if (_item.id) {
                        GeoActions.update(_item.id, _item.data).then(function (data) {
                            console.log('Item updated successfully----------------', data);
                            updateMasterItem(data);
                            updating = false;
                        }, function (err) {
                            updating = false;
                            resetItem();
                            console.error('Error while inserting an item data---', err);
                        });
                    }
                    else {
                        GeoActions.insert(_item.data).then(function (data) {
                            ContentHome.geoAction = data;
                            ContentHome.items.push(data);
                            updateMasterItem(data);
                            updating = false;
                            console.log('new ---------------- Item inserted-------------------------------', data);
                        }, function (err) {
                            console.error('Error while updating an item data---', err);
                            resetItem();
                            updating = false;
                        });
                    }
                }

                //to validate the action with title
                function isValidItem(action) {
                    return action.data && action.data.title;
                }

                /**
                 * updateItemWithDelay called when ever there is some change in current geo action
                 * @param _item
                 */
                function updateItemsWithDelay(_item) {
                    if (updating)
                        return;
                    if (tmrDelayForItem) {
                        $timeout.cancel(tmrDelayForItem);
                    }
                    ContentHome.isItemValid = isValidItem(_item);
                    if (_item && !isUnChanged(_item) && ContentHome.isItemValid) {
                        tmrDelayForItem = $timeout(function () {
                            insertAndUpdate(_item);
                        }, 300);
                    }
                }

                $scope.$watch(function () {
                    return ContentHome.geoAction;
                }, updateItemsWithDelay, true);

                /**
                 * initialization of variables
                 */
                function init() {

                    _skip = 0;
                    _limit = 10;
                    searchOptions = {
                        filter: {"$json.title": {"$regex": '/*'}},
                        skip: _skip,
                        limit: _limit + 1 // the plus one is to check if there are any more
                    };
                    tmrDelayForItem = null;
                    GeoActions = new DB(COLLECTIONS.GeoActions);
                    updating = false;
                    ContentHome.radiusMiles = 10;
                    ContentHome.radiusFeet = 0;
                    ContentHome.center = {};
                    ContentHome.geoAction = angular.copy(DEFAULT_DATA.GEO_ACTION);
                    ContentHome.masterGeoAction = angular.copy(DEFAULT_DATA.GEO_ACTION);
                }

                init();

            }]);
})(window.angular);<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
  angular
    .module('couponPluginContent')
    .controller('ContentHomeCtrl', ['$scope', 'TAG_NAMES','SORT_FILTER', 'STATUS_CODE', 'DataStore', 'LAYOUTS','Buildfire','Modals','RankOfLastFilter',
      function ($scope, TAG_NAMES, SORT_FILTER, STATUS_CODE, DataStore, LAYOUTS,Buildfire,Modals,RankOfLastFilter) {

        var ContentHome = this;
        ContentHome.filter=null;
        var _data = {
          "content": {
            "carouselImages": [],
            "description":'',
            "rankOfLastFilter" :''
          },
          "design": {
            "itemListLayout": LAYOUTS.itemListLayout[0].name
          },
          "settings": {
            "defaultView": "list",
            "distanceIn": "mi",
            mapView: "show",
            filterPage: "show"
          }
        };

        ContentHome.filters=[];

        ContentHome.sortFilterOptions=[
          SORT_FILTER.MANUALLY,
          SORT_FILTER.CATEGORY_NAME_A_Z,
          SORT_FILTER.CATEGORY_NAME_Z_A
        ]

        ContentHome.searchOptions = {
          filter: {"$json.title": {"$regex": '/*'}},
          skip: SORT_FILTER._skip,
          limit: SORT_FILTER._limit + 1 // the plus one is to check if there are any more
        };
        /*
         * create an artificial delay so api isnt called on every character entered
         * */
        var tmrDelay = null;

        ContentHome.busy=false;
        RankOfLastFilter.setRank(0);

        var updateMasterItem = function (data) {
          ContentHome.masterData = angular.copy(data);
        };

        var isUnchanged = function (data) {
          return angular.equals(data, ContentHome.masterData);
        };

        ContentHome.descriptionWYSIWYGOptions = {
          plugins: 'advlist autolink link image lists charmap print preview',
          skin: 'lightgray',
          trusted: true,
          theme: 'modern'
        };

        // create a new instance of the buildfire carousel editor
        var editor = new Buildfire.components.carousel.editor("#carousel");

        // this method will be called when a new item added to the list
        editor.onAddItems = function (items) {
          if (!ContentHome.data.content.carouselImages)
            ContentHome.data.content.carouselImages = [];
          ContentHome.data.content.carouselImages.push.apply(ContentHome.data.content.carouselImages, items);
          $scope.$digest();
        };
        // this method will be called when an item deleted from the list
        editor.onDeleteItem = function (item, index) {
          ContentHome.data.content.carouselImages.splice(index, 1);
          $scope.$digest();
        };
        // this method will be called when you edit item details
        editor.onItemChange = function (item, index) {
          ContentHome.data.content.carouselImages.splice(index, 1, item);
          $scope.$digest();
        };
        // this method will be called when you change the order of items
        editor.onOrderChange = function (item, oldIndex, newIndex) {
          var items = ContentHome.data.content.carouselImages;

          var tmp = items[oldIndex];

          if (oldIndex < newIndex) {
            for (var i = oldIndex + 1; i <= newIndex; i++) {
              items[i - 1] = items[i];
            }
          } else {
            for (var i = oldIndex - 1; i >= newIndex; i--) {
              items[i + 1] = items[i];
            }
          }
          items[newIndex] = tmp;

          ContentHome.data.content.carouselImages = items;
          $scope.$digest();
        };

        /**
         * ContentHome.itemSortableOptions used for ui-sortable directory to sort filter listing Manually.
         * @type object
         */
        ContentHome.itemSortableOptions = {
          handle: '> .cursor-grab',
          disabled: true,
          stop: function (e, ui) {
            var endIndex = ui.item.sortable.dropindex,
                maxRank = 0,
                draggedItem = ContentHome.filters[endIndex];

            if (draggedItem) {
              var prev = ContentHome.filters[endIndex - 1],
                  next = ContentHome.filters[endIndex + 1];
              var isRankChanged = false;
              if (next) {
                if (prev) {
                  draggedItem.rank = ((prev.rank || 0) + (next.rank || 0)) / 2;
                  isRankChanged = true;
                } else {
                  draggedItem.rank = (next.rank || 0) / 2;
                  isRankChanged = true;
                }
              } else {
                if (prev) {
                  draggedItem.rank = (((prev.rank || 0) * 2) + 10) / 2;
                  maxRank = draggedItem.rank;
                  isRankChanged = true;
                }
              }
              if (isRankChanged) {
                Buildfire.datastore.update(draggedItem.id, draggedItem, TAG_NAMES.COUPON_CATEGORIES, function (err) {
                  if (err) {
                    console.error('Error during updating rank');
                  } else {
                    if (ContentHome.data.content.rankOfLastFilter < maxRank) {
                      ContentHome.data.content.rankOfLastFilter = maxRank;
                      RankOfLastFilter.setRank(maxRank);
                    }
                  }
                })
              }
            }
          }
        };
        //ContentHome.itemSortableOptions.disabled = !(ContentHome.data.content.sortFilterBy === SORT_FILTER.MANUALLY);

        ContentHome.addEditFilter=function(filter, editFlag , index){
          var tempTitle='';
          if(filter)
            tempTitle=filter.title;
          Modals.addFilterModal({
            title: tempTitle,
            isEdit:editFlag
          }).then(function (response) {
            if (!(response.title === null || response.title.match(/^ *$/) !== null)) {

              //if index is there it means filter update operation is performed
              if(Number.isInteger(index)){
                ContentHome.filters[index].title= response.title;
              }else{
                ContentHome.filter={
                  title: response.title,
                  rank: RankOfLastFilter.getRank()+10
                }
                ContentHome.data.content.rankOfLastFilter=RankOfLastFilter.getRank()+10;
                RankOfLastFilter.setRank(ContentHome.data.content.rankOfLastFilter);
                ContentHome.filters.unshift(ContentHome.filter);
                Buildfire.datastore.insert(ContentHome.filter, TAG_NAMES.COUPON_CATEGORIES, false, function (err, data) {
                  console.log("Saved", data.id);
                  ContentHome.isUpdating = false;
                  ContentHome.filter.id=data.id;
                  if (err) {
                    ContentHome.isNewItemInserted = false;
                    return console.error('There was a problem saving your data');
                  }
                  $scope.$digest();
                });
              }
            }
            if(!$scope.$apply)
                $scope.$digest();
          }, function (err) {

          });
        }

        ContentHome.deleteFilter=function(index){
          Modals.removePopupModal().then(function (result) {
            if (result) {

              Buildfire.datastore.delete(ContentHome.filters[index].id, TAG_NAMES.COUPON_CATEGORIES, function (err, result) {
                if (err)
                  return;
                //ContentHome.items.splice(_index, 1);
                ContentHome.filters.splice(index, 1);
                $scope.$digest();
              });
            }
          });
        }

        ContentHome.sortFilterBy = function (value) {
          if (!value) {
            console.info('There was a problem sorting your data');
          } else {
           // ContentHome.data.content.filters=null;
            ContentHome.filters = [];
            ContentHome.searchOptions.skip = 0;
            ContentHome.busy = false;
            ContentHome.data.content.sortFilterBy = value;
            ContentHome.loadMore('js');
          }
        };

        ContentHome.chooseFilter=function (value) {
          if (!value) {
            console.info('There was a problem sorting your data');
          } else {
            ContentHome.data.content.selectedFilter = value;
            //ContentHome.loadMore('js');
          }
        };

        /**
         * getSearchOptions(value) is used to get searchOptions with one more key sort which decide the order of sorting.
         * @param value is used to filter sort option.
         * @returns object
         * SORT_FILTER.CATEGORY_NAME_A_Z,
         * SORT_FILTER.CATEGORY_NAME_Z_A
         */
        var getSearchOptions = function (value) {
          //ContentHome.itemSortableOptions.disabled = true;
          switch (value) {
            case SORT_FILTER.CATEGORY_NAME_A_Z:
              ContentHome.searchOptions.sort = {"title": 1};
              break;
            case SORT_FILTER.CATEGORY_NAME_Z_A:
              ContentHome.searchOptions.sort = {"title": -1};
              break;
            default :
              ContentHome.itemSortableOptions.disabled = false;
              ContentHome.searchOptions.sort = {"rank": 1};
              break;
          }
          return ContentHome.searchOptions;
        };

        ContentHome.loadMore = function (str) {
          Buildfire.spinner.show();
          if (ContentHome.busy) {
            return;
          }

          ContentHome.busy = true;
          if (ContentHome.data && ContentHome.data.content.sortFilterBy) {
            ContentHome.searchOptions = getSearchOptions(ContentHome.data.content.sortFilterBy);
          }else{
            return;
          }
          Buildfire.datastore.search(ContentHome.searchOptions, TAG_NAMES.COUPON_CATEGORIES, function (err, result) {
            if (err) {
              Buildfire.spinner.hide();
              return console.error('-----------err in getting list-------------', err);
            }
            if (result.length <= SORT_FILTER._limit) {// to indicate there are more
              ContentHome.noMore = true;
              Buildfire.spinner.hide();
            } else {
              result.pop();
              ContentHome.searchOptions.skip = ContentHome.searchOptions.skip + SORT_FILTER._limit;
              ContentHome.noMore = false;
            }
            var tmpArray=[];
            var lastIndex=result.length;
            result.forEach(function(res,index){
              tmpArray.push({'title' : res.data.title,
              rank:index +1,
                id:res.data.id});
            });

            ContentHome.filters = ContentHome.filters ? ContentHome.filters.concat(tmpArray) : tmpArray;
            ContentHome.busy = false;
            Buildfire.spinner.hide();
            $scope.$digest();
          });
        };

        /*
         * Call the datastore to save the data object
         */
        var saveData = function (newObj, tag) {
          if (typeof newObj === 'undefined') {
            return;
          }
          var success = function (result) {
              console.info('Saved data result: ', result);
              RankOfLastFilter.setRank(result.data.content.rankOfLastFilter);
              updateMasterItem(newObj);
            }
            , error = function (err) {
              console.error('Error while saving data : ', err);
            };
          newObj.content.rankOfLastFilter = newObj.content.rankOfLastFilter || 0;
          DataStore.save(newObj, tag).then(success, error);
        };

        function isValidItem(item) {
          if(item){
            return item.title;
          }
          else{
            return false;
          }

        }

        var updateItemsWithDelay = function (item) {
          ContentHome.isUpdating = false;
          ContentHome.isItemValid = isValidItem(ContentHome.filter);
          if (!ContentHome.isUpdating && !isUnchanged(ContentHome.filter) && ContentHome.isItemValid) {
           setTimeout(function () {
              if (item.id) {
                ContentHome.updateItemData();
                $scope.$digest();
              } /*else if (!ContentHome.isNewItemInserted) {
                ContentHome.addNewItem();
              }*/
            }, 300);
          }
        };

        ContentHome.updateItemData = function () {
          Buildfire.datastore.update(ContentHome.filter.id, ContentHome.filter, TAG_NAMES.COUPON_CATEGORIES, function (err) {
            ContentHome.isUpdating = false;
            if (err)
              return console.error('There was a problem saving your data');
          })
        };

        var saveDataWithDelay = function (newObj) {
          if (newObj) {
            if (isUnchanged(newObj)) {
              return;
            }
            if (tmrDelay) {
              clearTimeout(tmrDelay);
            }
            tmrDelay = setTimeout(function () {
              saveData(JSON.parse(angular.toJson(newObj)), TAG_NAMES.COUPON_INFO);
            }, 500);
          }
        };

        /*
         * Go pull any previously saved data
         * */
        var init = function () {
          var success = function (result) {
              console.info('Init success result:', result);
              ContentHome.data = result.data;
              if (!ContentHome.data) {
                ContentHome.data = angular.copy(_data);
              } else {
                if (!ContentHome.data.content)
                  ContentHome.data.content = {};
                if (!ContentHome.data.settings)
                  ContentHome.data.settings = {};
                if (!ContentHome.data.content.carouselImages)
                  editor.loadItems([]);
                else
                  editor.loadItems(ContentHome.data.content.carouselImages);
                ContentHome.filters = [];
                ContentHome.searchOptions.skip = 0;
                ContentHome.busy = false;
                RankOfLastFilter.setRank(ContentHome.data.content.rankOfLastFilter || 0);
              }
              updateMasterItem(ContentHome.data);
              if (tmrDelay)clearTimeout(tmrDelay);
                ContentHome.loadMore('js');
            }
            , error = function (err) {
              if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting data', err);
                if (tmrDelay)clearTimeout(tmrDelay);
              }
              else if (err && err.code === STATUS_CODE.NOT_FOUND) {
                saveData(JSON.parse(angular.toJson(ContentHome.data)), TAG_NAMES.COUPON_INFO);
              }
            };
          DataStore.get(TAG_NAMES.COUPON_INFO).then(success, error);

        };

        init();

        updateMasterItem(_data);

        /*
         * watch for changes in data and trigger the saveDataWithDelay function on change
         * */
        $scope.$watch(function () {
          return ContentHome.data;
        }, saveDataWithDelay, true);

        /*
         * watch for changes in filters and trigger the saveDataWithDelay function on change
         * */
        $scope.$watch(function () {
          return ContentHome.filter;
        }, updateItemsWithDelay, true);

      }]);
})(window.angular, window.buildfire);
<commit_msg>minor issue related to filter list resolved<commit_after>'use strict';

(function (angular, buildfire) {
  angular
    .module('couponPluginContent')
    .controller('ContentHomeCtrl', ['$scope', 'TAG_NAMES','SORT_FILTER', 'STATUS_CODE', 'DataStore', 'LAYOUTS','Buildfire','Modals','RankOfLastFilter',
      function ($scope, TAG_NAMES, SORT_FILTER, STATUS_CODE, DataStore, LAYOUTS,Buildfire,Modals,RankOfLastFilter) {

        var ContentHome = this;
        ContentHome.filter=null;
        var _data = {
          "content": {
            "carouselImages": [],
            "description":'',
            "rankOfLastFilter" :''
          },
          "design": {
            "itemListLayout": LAYOUTS.itemListLayout[0].name
          },
          "settings": {
            "defaultView": "list",
            "distanceIn": "mi",
            mapView: "show",
            filterPage: "show"
          }
        };

        ContentHome.filters=[];

        ContentHome.sortFilterOptions=[
          SORT_FILTER.MANUALLY,
          SORT_FILTER.CATEGORY_NAME_A_Z,
          SORT_FILTER.CATEGORY_NAME_Z_A
        ]

        ContentHome.searchOptions = {
          filter: {"$json.title": {"$regex": '/*'}},
          skip: SORT_FILTER._skip,
          limit: SORT_FILTER._limit + 1 // the plus one is to check if there are any more
        };
        /*
         * create an artificial delay so api isnt called on every character entered
         * */
        var tmrDelay = null;

        ContentHome.busy=false;
        RankOfLastFilter.setRank(0);

        var updateMasterItem = function (data) {
          ContentHome.masterData = angular.copy(data);
        };

        var isUnchanged = function (data) {
          return angular.equals(data, ContentHome.masterData);
        };

        ContentHome.descriptionWYSIWYGOptions = {
          plugins: 'advlist autolink link image lists charmap print preview',
          skin: 'lightgray',
          trusted: true,
          theme: 'modern'
        };

        // create a new instance of the buildfire carousel editor
        var editor = new Buildfire.components.carousel.editor("#carousel");

        // this method will be called when a new item added to the list
        editor.onAddItems = function (items) {
          if (!ContentHome.data.content.carouselImages)
            ContentHome.data.content.carouselImages = [];
          ContentHome.data.content.carouselImages.push.apply(ContentHome.data.content.carouselImages, items);
          $scope.$digest();
        };
        // this method will be called when an item deleted from the list
        editor.onDeleteItem = function (item, index) {
          ContentHome.data.content.carouselImages.splice(index, 1);
          $scope.$digest();
        };
        // this method will be called when you edit item details
        editor.onItemChange = function (item, index) {
          ContentHome.data.content.carouselImages.splice(index, 1, item);
          $scope.$digest();
        };
        // this method will be called when you change the order of items
        editor.onOrderChange = function (item, oldIndex, newIndex) {
          var items = ContentHome.data.content.carouselImages;

          var tmp = items[oldIndex];

          if (oldIndex < newIndex) {
            for (var i = oldIndex + 1; i <= newIndex; i++) {
              items[i - 1] = items[i];
            }
          } else {
            for (var i = oldIndex - 1; i >= newIndex; i--) {
              items[i + 1] = items[i];
            }
          }
          items[newIndex] = tmp;

          ContentHome.data.content.carouselImages = items;
          $scope.$digest();
        };

        /**
         * ContentHome.itemSortableOptions used for ui-sortable directory to sort filter listing Manually.
         * @type object
         */
        ContentHome.itemSortableOptions = {
          handle: '> .cursor-grab',
          disabled: true,
          stop: function (e, ui) {
            var endIndex = ui.item.sortable.dropindex,
                maxRank = 0,
                draggedItem = ContentHome.filters[endIndex];

            if (draggedItem) {
              var prev = ContentHome.filters[endIndex - 1],
                  next = ContentHome.filters[endIndex + 1];
              var isRankChanged = false;
              if (next) {
                if (prev) {
                  draggedItem.rank = ((prev.rank || 0) + (next.rank || 0)) / 2;
                  isRankChanged = true;
                } else {
                  draggedItem.rank = (next.rank || 0) / 2;
                  isRankChanged = true;
                }
              } else {
                if (prev) {
                  draggedItem.rank = (((prev.rank || 0) * 2) + 10) / 2;
                  maxRank = draggedItem.rank;
                  isRankChanged = true;
                }
              }
              if (isRankChanged) {
                Buildfire.datastore.update(draggedItem.id, draggedItem, TAG_NAMES.COUPON_CATEGORIES, function (err) {
                  if (err) {
                    console.error('Error during updating rank');
                  } else {
                    if (ContentHome.data.content.rankOfLastFilter < maxRank) {
                      ContentHome.data.content.rankOfLastFilter = maxRank;
                      RankOfLastFilter.setRank(maxRank);
                    }
                  }
                })
              }
            }
          }
        };
        //ContentHome.itemSortableOptions.disabled = !(ContentHome.data.content.sortFilterBy === SORT_FILTER.MANUALLY);

        ContentHome.addEditFilter=function(filter, editFlag , index){
          var tempTitle='';
          if(filter)
            tempTitle=filter.title;
          Modals.addFilterModal({
            title: tempTitle,
            isEdit:editFlag
          }).then(function (response) {
            if (!(response.title === null || response.title.match(/^ *$/) !== null)) {

              //if index is there it means filter update operation is performed
              if(Number.isInteger(index)){
                ContentHome.filters[index].title= response.title;
              }else{
                ContentHome.filter={
                  title: response.title,
                  rank: RankOfLastFilter.getRank()+10
                }
                ContentHome.data.content.rankOfLastFilter=RankOfLastFilter.getRank()+10;
                RankOfLastFilter.setRank(ContentHome.data.content.rankOfLastFilter);
                ContentHome.filters.unshift(ContentHome.filter);
                Buildfire.datastore.insert(ContentHome.filter, TAG_NAMES.COUPON_CATEGORIES, false, function (err, data) {
                  console.log("Saved", data.id);
                  ContentHome.isUpdating = false;
                  ContentHome.filter.id=data.id;
                  if (err) {
                    ContentHome.isNewItemInserted = false;
                    return console.error('There was a problem saving your data');
                  }
                  $scope.$digest();
                });
              }
            }
            if(!$scope.$apply)
                $scope.$digest();
          }, function (err) {

          });
        }

        ContentHome.deleteFilter=function(index){
          Modals.removePopupModal().then(function (result) {
            if (result) {

              Buildfire.datastore.delete(ContentHome.filters[index].id, TAG_NAMES.COUPON_CATEGORIES, function (err, result) {
                if (err)
                  return;
                //ContentHome.items.splice(_index, 1);
                ContentHome.filters.splice(index, 1);
                $scope.$digest();
              });
            }
          });
        }

        ContentHome.sortFilterBy = function (value) {
          if (!value) {
            console.info('There was a problem sorting your data');
          } else {
           // ContentHome.data.content.filters=null;
            ContentHome.filters = [];
            ContentHome.searchOptions.skip = 0;
            ContentHome.busy = false;
            ContentHome.data.content.sortFilterBy = value;
            ContentHome.loadMore('js');
          }
        };

        ContentHome.chooseFilter=function (value) {
          if (!value) {
            console.info('There was a problem sorting your data');
          } else {
            ContentHome.data.content.selectedFilter = value;
            //ContentHome.loadMore('js');
          }
        };

        /**
         * getSearchOptions(value) is used to get searchOptions with one more key sort which decide the order of sorting.
         * @param value is used to filter sort option.
         * @returns object
         * SORT_FILTER.CATEGORY_NAME_A_Z,
         * SORT_FILTER.CATEGORY_NAME_Z_A
         */
        var getSearchOptions = function (value) {
          //ContentHome.itemSortableOptions.disabled = true;
          switch (value) {
            case SORT_FILTER.CATEGORY_NAME_A_Z:
              ContentHome.searchOptions.sort = {"title": 1};
              break;
            case SORT_FILTER.CATEGORY_NAME_Z_A:
              ContentHome.searchOptions.sort = {"title": -1};
              break;
            default :
              ContentHome.itemSortableOptions.disabled = false;
              ContentHome.searchOptions.sort = {"rank": 1};
              break;
          }
          return ContentHome.searchOptions;
        };

        ContentHome.loadMore = function (str) {
          Buildfire.spinner.show();
          if (ContentHome.busy) {
            return;
          }

          ContentHome.busy = true;
          if (ContentHome.data && ContentHome.data.content.sortFilterBy) {
            ContentHome.searchOptions = getSearchOptions(ContentHome.data.content.sortFilterBy);
          }else{
            return;
          }
          Buildfire.datastore.search(ContentHome.searchOptions, TAG_NAMES.COUPON_CATEGORIES, function (err, result) {
            if (err) {
              Buildfire.spinner.hide();
              return console.error('-----------err in getting list-------------', err);
            }
            if (result.length <= SORT_FILTER._limit) {// to indicate there are more
              ContentHome.noMore = true;
              Buildfire.spinner.hide();
            } else {
              result.pop();
              ContentHome.searchOptions.skip = ContentHome.searchOptions.skip + SORT_FILTER._limit;
              ContentHome.noMore = false;
            }
            var tmpArray=[];
            var lastIndex=result.length;
            result.forEach(function(res,index){
              tmpArray.push({'title' : res.data.title,
              rank:index +1,
                id:res.data.id});
            });

            ContentHome.filters = ContentHome.filters ? ContentHome.filters.concat(tmpArray) : tmpArray;
            ContentHome.busy = false;
            Buildfire.spinner.hide();
            $scope.$digest();
          });
        };

        /*
         * Call the datastore to save the data object
         */
        var saveData = function (newObj, tag) {
          if (typeof newObj === 'undefined') {
            return;
          }
          var success = function (result) {
              console.info('Saved data result: ', result);
              RankOfLastFilter.setRank(result.data.content.rankOfLastFilter);
              updateMasterItem(newObj);
            }
            , error = function (err) {
              console.error('Error while saving data : ', err);
            };
          newObj.content.rankOfLastFilter = newObj.content.rankOfLastFilter || 0;
          DataStore.save(newObj, tag).then(success, error);
        };

        function isValidItem(item) {
          if(item){
            return item.title;
          }
          else{
            return false;
          }

        }

        var updateItemsWithDelay = function (item) {
          ContentHome.isUpdating = false;
          ContentHome.isItemValid = isValidItem(ContentHome.filter);
          if (!ContentHome.isUpdating && !isUnchanged(ContentHome.filter) && ContentHome.isItemValid) {
           setTimeout(function () {
              if (item.id) {
                ContentHome.updateItemData();
                $scope.$digest();
              } /*else if (!ContentHome.isNewItemInserted) {
                ContentHome.addNewItem();
              }*/
            }, 300);
          }
        };

        ContentHome.updateItemData = function () {
          Buildfire.datastore.update(ContentHome.filter.id, ContentHome.filter, TAG_NAMES.COUPON_CATEGORIES, function (err) {
            ContentHome.isUpdating = false;
            if (err)
              return console.error('There was a problem saving your data');
          })
        };

        var saveDataWithDelay = function (newObj) {
          if (newObj) {
            if (isUnchanged(newObj)) {
              return;
            }
            if (tmrDelay) {
              clearTimeout(tmrDelay);
            }
            tmrDelay = setTimeout(function () {
              saveData(JSON.parse(angular.toJson(newObj)), TAG_NAMES.COUPON_INFO);
            }, 500);
          }
        };

        /*
         * Go pull any previously saved data
         * */
        var init = function () {
          var success = function (result) {
              console.info('Init success result:', result);
              ContentHome.data = result.data;
              if (!ContentHome.data) {
                ContentHome.data = angular.copy(_data);
              } else {
                if (!ContentHome.data.content)
                  ContentHome.data.content = {};
                if (!ContentHome.data.settings)
                  ContentHome.data.settings = {};
                if (!ContentHome.data.content.carouselImages)
                  editor.loadItems([]);
                else
                  editor.loadItems(ContentHome.data.content.carouselImages);
                if(!ContentHome.data.content.sortFilterBy)
                  ContentHome.data.content.sortFilterBy=ContentHome.sortFilterOptions[0];
                ContentHome.filters = [];
                ContentHome.searchOptions.skip = 0;
                ContentHome.busy = false;
                RankOfLastFilter.setRank(ContentHome.data.content.rankOfLastFilter || 0);
              }
              updateMasterItem(ContentHome.data);
              if (tmrDelay)clearTimeout(tmrDelay);
                ContentHome.loadMore('js');
            }
            , error = function (err) {
              if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting data', err);
                if (tmrDelay)clearTimeout(tmrDelay);
              }
              else if (err && err.code === STATUS_CODE.NOT_FOUND) {
                saveData(JSON.parse(angular.toJson(ContentHome.data)), TAG_NAMES.COUPON_INFO);
              }
            };
          DataStore.get(TAG_NAMES.COUPON_INFO).then(success, error);

        };

        init();

        updateMasterItem(_data);

        /*
         * watch for changes in data and trigger the saveDataWithDelay function on change
         * */
        $scope.$watch(function () {
          return ContentHome.data;
        }, saveDataWithDelay, true);

        /*
         * watch for changes in filters and trigger the saveDataWithDelay function on change
         * */
        $scope.$watch(function () {
          return ContentHome.filter;
        }, updateItemsWithDelay, true);

      }]);
})(window.angular, window.buildfire);
<|endoftext|>


<commit_before>/*!
 * rating-utils
 * Copyright(c) 2016 Wes Grimes
 * MIT Licensed
 */

'use strict';

/**
 * Module dependencies.
 * @private
 */
var config = require("config");
var moment = require("moment");
require("twix");

var rounding = config.get("prorata.rounding");

/**
 * Determine proratafactor given original eff date and revision eff date
 * @param {String} policyEffectiveDate
 * @param {String} revisionEffectiveDate
 * @return {Number}
 */

function getProrateFactor(policyEffectiveDate, revisionEffectiveDate) {
    var actualDays = moment(policyEffectiveDate).twix(revisionEffectiveDate).length("days");
    var effPlusYear = moment(policyEffectiveDate).add(1, "years").subtract(1, "days");
    var daysIfFullYear = moment(policyEffectiveDate).twix(effPlusYear).length("days");

    if (rounding.enabled) {
        return (actualDays / daysIfFullYear).toPrecision(rounding.precision);
    }
    else {
        return (actualDays / daysIfFullYear);
    }

}

function getNetChangeAmount(newFullTermAmount, prevFullTermAmount, policyEffectiveDate, revisionEffectiveDate) {
    var netChangeUnadjusted = newFullTermAmount - prevFullTermAmount;
    var netChangeAdjusted = netChangeUnadjusted * getProrateFactor(policyEffectiveDate, revisionEffectiveDate);
    return Math.round(netChangeAdjusted, 0);
}

 module.exports = {
     getProrateFactor: getProrateFactor,
     getNetChangeAmount: getNetChangeAmount
 };<commit_msg>code comments<commit_after>/*!
 * rating-utils
 * Copyright(c) 2016 Wes Grimes
 * MIT Licensed
 */

'use strict';

/**
 * Module dependencies.
 * @private
 */
var config = require("config");
var moment = require("moment");
require("twix");

var rounding = config.get("prorata.rounding");

/**
 * Determine proratafactor given original eff date and revision eff date
 * @param {String} policyEffectiveDate
 * @param {String} revisionEffectiveDate
 * @return {Number}
 */

function getProrateFactor(policyEffectiveDate, revisionEffectiveDate) {
    var actualDays = moment(policyEffectiveDate).twix(revisionEffectiveDate).length("days");
    var effPlusYear = moment(policyEffectiveDate).add(1, "years").subtract(1, "days");
    var daysIfFullYear = moment(policyEffectiveDate).twix(effPlusYear).length("days");

    if (rounding.enabled) {
        return (actualDays / daysIfFullYear).toPrecision(rounding.precision);
    }
    else {
        return (actualDays / daysIfFullYear);
    }
}

/**
 * Calculate net change amount new full term, previous full term, original eff date and revision eff date
 * @param {Number} newFullTermAmount
 * @param {Number} prevFullTermAmount
 * @param {String} policyEffectiveDate
 * @param {String} revisionEffectiveDate
 * @return {Number}
 */
function getNetChangeAmount(newFullTermAmount, prevFullTermAmount, policyEffectiveDate, revisionEffectiveDate) {
    var netChangeUnadjusted = newFullTermAmount - prevFullTermAmount;
    var netChangeAdjusted = netChangeUnadjusted * getProrateFactor(policyEffectiveDate, revisionEffectiveDate);
    return Math.round(netChangeAdjusted, 0);
}

 module.exports = {
     getProrateFactor: getProrateFactor,
     getNetChangeAmount: getNetChangeAmount
 };<|endoftext|>


<commit_before>'use strict';

var EventEmitter    = require('events').EventEmitter;
var VError          = require('VError');
var stringify       = require('json-stringify-safe');
var Joi             = require('joi');
var extend          = require('xtend');
var validateAdapter = require('./validate_adapter');
var through         = require('through');
var JSONStream      = require('JSONStream');
var es              = require('event-stream');
var async           = require('async');
var ut              = require('./util');

module.exports = function(adp) {
  function Publish(opts) {
    opts = opts || {};

    var emitter = new EventEmitter();

    emitter.ready = false;
    emitter.port = +(opts.port || Publish.defaults.port);
    emitter.host = opts.host || Publish.defaults.host;
    emitter.publishQueue = [];

    emitter.meta = extend({}, Publish.defaults, opts);

    function onError(err) {
      process.nextTick(function() { emitter.emit('error', err); });
    }

    var cli = emitter.cli = adp.createClient({
      port: emitter.port,
      host: emitter.host,
      meta: emitter.meta,
      onError: onError
    });

    cli.validate = function(data, schema, next) {
      if (schema) {
        if (ut.types.isObject(data)) {
          Joi.validate(data, schema, {
            stripUnknown: true,
            abortEarly: true,
            convert: true
          }, function(err, info) {
            if (err) {
              next(err);
            } else {
              next(undefined, stringify(info));
            }
          });
        } else {
          var t = ut.getType(data);
          next(new VError('Expecting object not %s', t));
        }
      } else {
        next(undefined, ut.types.isObject(data) ? stringify(data) : data);
      }
    };

    emitter.publish = adp.publish(cli);

    adp.onReady(cli)(function(err) {
      //
      // event emitter handlers might
      // not be registered yet, we
      // need to give them a change to register
      // their handlers
      //
      process.nextTick(function() {
        if (err) {
          onError(err);
          emitter.emit('end');
        } else {
          adp.prepareChannels(cli)(function(err) {
            if (err) {
              onError(err);
              emitter.emit('end');
            } else {
              emitter.ready = true;
              emitter.emit('ready');
              //
              // send any buffered messages
              //
              async.eachLimit(emitter.publishQueue, 5, function(pub, cb) {
                emitter.publish(pub.name, pub.buff, function() {
                  pub.next(undefined, pub.resp);
                  cb();
                });
              }, function() {
                //
                // reset so users know
                // its been sent
                //
                emitter.publishQueue = [];
              });
            }
          });
        }
      });
    });

    emitter.channel = function createWriteStream(name, opts) {
      opts = opts || {};

      var ws = through();
      var schema = opts.schema;

      ws.json = ut.types.isBoolean(opts.json) ? opts.json :
        ut.types.isObject(schema);

      ws.on('pipe', function(src) {
        var dest = ws.json ? JSONStream.parse() : es.split();
        dest.on('error', function(err) { ws.emit('error', err); });
        src
        .pipe(dest)
        .on('data', function(obj) {
          ws.publish(obj, function(err, res) {
            if (err) {
              return ws.emit('error', err);
            }
            return res;
          });
        });
      });

      ws.publish = function(data, next) {
        if (emitter.closed) {
          return next(new Error('Connection closed'));
        }

        cli.validate(data, schema, function(err, serializedData) {
          if (err) {
            return next(err);
          }

          var buff = new Buffer(serializedData);
          var resp = {
            ack: true,
            ts: new Date(),
            written: serializedData
          };

          if (!emitter.ready) {
            emitter.publishQueue.push({
              resp: resp,
              name: name,
              buff: buff,
              next: next
            });
          } else {
            emitter.publish(name, buff, function() {
              next(undefined, resp);
            });
          }

        });
      };

      return ws;
    };

    emitter.onError = onError;

    emitter.closed = false;
    emitter._close = adp.destroyClient(cli);

    emitter.close = function(onEnd) {
      onEnd = onEnd || ut.noop;
      emitter.closed = true;
      emitter.ready = false;
      emitter.emit('close');
      emitter._close(onEnd);
    };

    return emitter;
  }

  adp = adp || {};

  validateAdapter(adp);

  Publish.defaults = adp.defaults;
  Publish.name = adp.name;

  adp = adp.publish;

  return Publish;
};
<commit_msg>verror<commit_after>'use strict';

var EventEmitter    = require('events').EventEmitter;
var VError          = require('verror');
var stringify       = require('json-stringify-safe');
var Joi             = require('joi');
var extend          = require('xtend');
var validateAdapter = require('./validate_adapter');
var through         = require('through');
var JSONStream      = require('JSONStream');
var es              = require('event-stream');
var async           = require('async');
var ut              = require('./util');

module.exports = function(adp) {
  function Publish(opts) {
    opts = opts || {};

    var emitter = new EventEmitter();

    emitter.ready = false;
    emitter.port = +(opts.port || Publish.defaults.port);
    emitter.host = opts.host || Publish.defaults.host;
    emitter.publishQueue = [];

    emitter.meta = extend({}, Publish.defaults, opts);

    function onError(err) {
      process.nextTick(function() { emitter.emit('error', err); });
    }

    var cli = emitter.cli = adp.createClient({
      port: emitter.port,
      host: emitter.host,
      meta: emitter.meta,
      onError: onError
    });

    cli.validate = function(data, schema, next) {
      if (schema) {
        if (ut.types.isObject(data)) {
          Joi.validate(data, schema, {
            stripUnknown: true,
            abortEarly: true,
            convert: true
          }, function(err, info) {
            if (err) {
              next(err);
            } else {
              next(undefined, stringify(info));
            }
          });
        } else {
          var t = ut.getType(data);
          next(new VError('Expecting object not %s', t));
        }
      } else {
        next(undefined, ut.types.isObject(data) ? stringify(data) : data);
      }
    };

    emitter.publish = adp.publish(cli);

    adp.onReady(cli)(function(err) {
      //
      // event emitter handlers might
      // not be registered yet, we
      // need to give them a change to register
      // their handlers
      //
      process.nextTick(function() {
        if (err) {
          onError(err);
          emitter.emit('end');
        } else {
          adp.prepareChannels(cli)(function(err) {
            if (err) {
              onError(err);
              emitter.emit('end');
            } else {
              emitter.ready = true;
              emitter.emit('ready');
              //
              // send any buffered messages
              //
              async.eachLimit(emitter.publishQueue, 5, function(pub, cb) {
                emitter.publish(pub.name, pub.buff, function() {
                  pub.next(undefined, pub.resp);
                  cb();
                });
              }, function() {
                //
                // reset so users know
                // its been sent
                //
                emitter.publishQueue = [];
              });
            }
          });
        }
      });
    });

    emitter.channel = function createWriteStream(name, opts) {
      opts = opts || {};

      var ws = through();
      var schema = opts.schema;

      ws.json = ut.types.isBoolean(opts.json) ? opts.json :
        ut.types.isObject(schema);

      ws.on('pipe', function(src) {
        var dest = ws.json ? JSONStream.parse() : es.split();
        dest.on('error', function(err) { ws.emit('error', err); });
        src
        .pipe(dest)
        .on('data', function(obj) {
          ws.publish(obj, function(err, res) {
            if (err) {
              return ws.emit('error', err);
            }
            return res;
          });
        });
      });

      ws.publish = function(data, next) {
        if (emitter.closed) {
          return next(new Error('Connection closed'));
        }

        cli.validate(data, schema, function(err, serializedData) {
          if (err) {
            return next(err);
          }

          var buff = new Buffer(serializedData);
          var resp = {
            ack: true,
            ts: new Date(),
            written: serializedData
          };

          if (!emitter.ready) {
            emitter.publishQueue.push({
              resp: resp,
              name: name,
              buff: buff,
              next: next
            });
          } else {
            emitter.publish(name, buff, function() {
              next(undefined, resp);
            });
          }

        });
      };

      return ws;
    };

    emitter.onError = onError;

    emitter.closed = false;
    emitter._close = adp.destroyClient(cli);

    emitter.close = function(onEnd) {
      onEnd = onEnd || ut.noop;
      emitter.closed = true;
      emitter.ready = false;
      emitter.emit('close');
      emitter._close(onEnd);
    };

    return emitter;
  }

  adp = adp || {};

  validateAdapter(adp);

  Publish.defaults = adp.defaults;
  Publish.name = adp.name;

  adp = adp.publish;

  return Publish;
};
<|endoftext|>