<commit_before>const hideCommitFiles = function () {
    let $commitMenu = $('.diffbar-range-menu .select-menu-modal');
    let $commitLinks = $commitMenu.find('a[role=menuitem]');
    // disable this if only 1 commit link + all changes link
    if ($commitLinks.length <= 2) {
      console.log('Only 1 commit in PR. Nothing to hide.');
      return;
    }

    const toggleHoverStyle = {'text-decoration': 'underline'};
    const toggleResetStyle = {'text-decoration': 'inherit'};
    const toggleStyle = {'padding': '10px', 'margin-top': '-10px'};
    $commitMenu.css('width', '600px');
    $commitLinks.each(function (index) {
      if (index === 0) {
        return;
      }

      let isHidden = false;
      let $link = $(this);

      let $commitCode = $link.find('.select-menu-item-text code');
      let $fileToggle = $('Hide files');
      $fileToggle.css(toggleStyle);
      $fileToggle.insertBefore($commitCode);
      $fileToggle.hover(() => $fileToggle.css(toggleHoverStyle), () => $fileToggle.css(toggleResetStyle));

      const commitUrl = $link.attr('href');
      $.get(commitUrl).then(function (singleCommitBody) {
        let $singleCommitBody = $(singleCommitBody);

        let $commitAuthor = $singleCommitBody.find('.commit-author-section img');
        $commitAuthor.addClass('right');
        $commitAuthor.insertBefore($fileToggle);

        // display commit diff stats
        let diffStat = $singleCommitBody.find('.diffbar-item.diffstat');
        diffStat.addClass('right').removeClass('diff-item');
        diffStat.insertAfter($commitCode);

        // collect all files which are part of that commit
        let files = [];
        let $filesChanged = $singleCommitBody.find('#files .file-header');
        $filesChanged.each(function () {
          files.push($(this).attr('data-path'));
        });

        // Click on show/hide files toggle
        $fileToggle.click(function (e) {
          e.preventDefault();
          isHidden = !isHidden;
          $fileToggle.text(isHidden ? 'Show files' : 'Hide files');
          files.forEach(function (file) {
            if (isHidden) {
              $('[data-path="' + file + '"]').parent().hide();
            } else {
              $('[data-path="' + file + '"]').parent().show();
            }
          });

          return false;
        })
      });
    });
};
<commit_msg>All files toggle<commit_after>const hideCommitFiles = function () {
    let $commitMenu = $('.diffbar-range-menu .select-menu-modal');
    let $commitLinks = $commitMenu.find('a[role=menuitem]');
    // disable this if only 1 commit link + all changes link
    if ($commitLinks.length <= 2) {
      console.log('Only 1 commit in PR. Nothing to hide.');
      return;
    }

    const toggleHoverStyle = {'text-decoration': 'underline'};
    const toggleResetStyle = {'text-decoration': 'inherit'};
    const toggleStyle = {'padding': '10px', 'margin-top': '-10px'};
    $commitMenu.css('width', '600px');
    $commitLinks.each(function (index) {
      let isHidden = false;
      let $link = $(this);

      if (index === 0) {
        let $allCommitsToggle = $('Hide all files');
        $allCommitsToggle.css(toggleStyle);
        $link.find('.select-menu-item-text').prepend($allCommitsToggle);

        // On all commits click delegate to all commits
        $allCommitsToggle.click(function (e) {
          e.preventDefault();
          isHidden = !isHidden;
          $fileToggle.text(isHidden ? 'Show all files' : 'Hide all files');
          $commitLinks.find('[data-visibility-status="' + (isHidden ? 'show' : 'hide') + '"]').trigger('click');

          return false;
        });
      }

      let $commitCode = $link.find('.select-menu-item-text code');
      let $fileToggle = $('Hide files');
      $fileToggle.css(toggleStyle);
      $fileToggle.insertBefore($commitCode);
      $fileToggle.hover(() => $fileToggle.css(toggleHoverStyle), () => $fileToggle.css(toggleResetStyle));

      const commitUrl = $link.attr('href');
      $.get(commitUrl).then(function (singleCommitBody) {
        let $singleCommitBody = $(singleCommitBody);

        let $commitAuthor = $singleCommitBody.find('.commit-author-section img');
        $commitAuthor.addClass('right');
        $commitAuthor.insertBefore($fileToggle);

        // display commit diff stats
        let diffStat = $singleCommitBody.find('.diffbar-item.diffstat');
        diffStat.addClass('right').removeClass('diff-item');
        diffStat.insertAfter($commitCode);

        // collect all files which are part of that commit
        let files = [];
        let $filesChanged = $singleCommitBody.find('#files .file-header');
        $filesChanged.each(function () {
          files.push($(this).attr('data-path'));
        });

        // Click on show/hide files toggle
        $fileToggle.click(function (e) {
          e.preventDefault();
          isHidden = !isHidden;
          $fileToggle.text(isHidden ? 'Show files' : 'Hide files');
          $fileToggle.attr('data-visibility-status', isHidden ? 'hide' : 'show');
          files.forEach(function (file) {
            if (isHidden) {
              $('[data-path="' + file + '"]').parent().hide();
            } else {
              $('[data-path="' + file + '"]').parent().show();
            }
          });

          return false;
        })
      });
    });
};
<|endoftext|>


<commit_before>(function (angular) {
    "use strict";

    angular
        .module('folderPluginContent')
        .controller('folderPluginCtrl', ['$scope', 'Messaging', 'Utility',
            function ($scope, Messaging, Utility) {
                var tmpCarousalData = null;
                var tmpCarousalSettings=null;
                var editor = new buildfire.components.carousel.editor("#carousel",5,0);
                var _buildfire = {
                    plugins: {
                        dataType: "pluginInstance",
                        data: []
                    }
                };
                var _design = {
                    backgroundImage: null,
                    selectedLayout: 1,
                    backgroundblur: 0,
                    hideText: false
                };
                var navigationCallback = function (pluginData) {
                    Messaging.sendMessageToWidget({
                        name: 'OPEN_PLUGIN',
                        message: {
                            data: pluginData
                        }
                    });
                };
                var plugins = new buildfire.components.pluginInstance.sortableList("#plugins", [], { showIcon: true, confirmDeleteItem: false }, undefined, undefined, { itemEditable: true, navigationCallback: navigationCallback });
                var tmrDelay = null;
                var updateItem = null;
                $scope.editorOptions = Utility.getEditorOptions();
                $scope.masterData = Utility.getDefaultScopeData();
                $scope.datastoreInitialized = false;

                function isUnchanged(data) {
                    return angular.equals(data, $scope.masterData);
                }

                function updateMasterItem(data) {
                    $scope.masterData = angular.copy(data);
                }

                //Go pull any previously saved data
                buildfire.datastore.getWithDynamicData(function (err, result) {
                    if (!err) {
                        $scope.datastoreInitialized = true;
                    } else {
                        console.error("Error: ", err);
                        return;
                    }

                    var firstTimeVisit = false;
                    if (!result.id) {
                        result.data = Utility.getDefaultScopeData();
                        firstTimeVisit = true;
                    }

                    if (result && result.data && !angular.equals({}, result.data)) {
                        updateMasterItem(result.data);
                        $scope.data = result.data;
                        $scope.id = result.id;
                        if ($scope.data && $scope.data.content && $scope.data.content.carouselImages) {
                            editor.loadItems($scope.data.content.carouselImages);
                        }
                        if ($scope.data && $scope.data.content && $scope.data.content.speed) {
                            editor.setSpeed($scope.data.content.speed);
                        }
                        if ($scope.data && $scope.data.content && $scope.data.content.random) {
                            editor.setRandom($scope.data.content.random);
                        }
                        if ($scope.data && $scope.data._buildfire && $scope.data._buildfire.plugins && $scope.data._buildfire.plugins.result) {
                            var pluginsData = Utility.getPluginDetails($scope.data._buildfire.plugins.result, $scope.data._buildfire.plugins.data);
                            if ($scope.data.content && $scope.data.content.loadAllPlugins) {
                                if (pluginsData.length) {
                                    plugins.loadItems(pluginsData, "loadAll");
                                    $("#plugins").find(".carousel-items").hide();
                                } else {
                                    plugins.loadAllItems();
                                    $("#plugins").find(".carousel-items").hide();
                                }
                            } else {
                                plugins.loadItems(pluginsData, "selected");
                                $("#plugins").find(".carousel-items").show();
                            }
                        }

                        if ($scope.data && !$scope.data._buildfire) {
                            updateItem = angular.copy($scope.data);
                            updateItem._buildfire = _buildfire;
                            updateMasterItem(updateItem);
                            $scope.data = angular.copy(updateItem);
                        }

                        if ($scope.data && !$scope.data.design) {
                            updateItem = angular.copy($scope.data);
                            updateItem.design = _design;
                            updateMasterItem(updateItem);
                            $scope.data = angular.copy(updateItem);
                        }

                        if(firstTimeVisit){
                            setTimeout(function () {
                                saveData($scope.data);
                            }, 500);
                        }

                        if (tmrDelay) clearTimeout(tmrDelay);
                    }

                    /*
                     * watch for changes in data and trigger the saveDataWithDelay function on change
                     * */
                    $scope.$watch('data', saveDataWithDelay, true);
                    Utility.digest($scope);
                });

                /*
                 * Call the datastore to save the data object
                 */
                var saveData = function (newObj) {
                    if (!$scope.datastoreInitialized) {
                        console.error("Error with datastore didn't get called");
                        return;
                    }

                    if (newObj == undefined) return;
                    if ($scope.frmMain.$invalid) {
                        console.warn('invalid data, details will not be saved');
                        return;
                    }

                    if (newObj._buildfire && newObj._buildfire.plugins) {
                        newObj._buildfire.plugins.result = plugins.items;
                    }

                    updateMasterItem(newObj);

                    Utility.save(newObj);
                };

                /*
                 * create an artificial delay so api isnt called on every character entered
                 * */
                var saveDataWithDelay = function (newObj) {

                    if (tmrDelay) clearTimeout(tmrDelay);
                    if (isUnchanged(newObj)) {
                        return;
                    }
                    if (newObj.default) {
                        var instanceIds = newObj._buildfire.plugins.data;
                        var loadAllPlugins = newObj.content.loadAllPlugins;

                        newObj = Utility.getDefaultScopeBlankData();
                        newObj.content.loadAllPlugins = loadAllPlugins;

                        newObj._buildfire.plugins.data = instanceIds;
                        if (tmpCarousalData) {
                            editor.loadItems(tmpCarousalData);
                            newObj.content.carouselImages = tmpCarousalData;
                            tmpCarousalData = null;
                        } else {
                            editor.loadItems([]);
                        }

                        if(tmpCarousalSettings){
                            newObj.content.speed= tmpCarousalSettings.speed;
                            newObj.content.random= tmpCarousalSettings.random;
                        }

                        $scope.data = newObj;
                    }
                    tmrDelay = setTimeout(function () {
                        saveData(newObj);
                    }, 500);
                };

                var getPluginsIds = function (plugins) {
                    var pluginsIds = [];
                    for (var i = 0; i < plugins.length; i++) {
                        pluginsIds.push(plugins[i].instanceId);
                    }
                    return pluginsIds;
                };

                // this method will be called when a new item added to the list
                editor.onDeleteItem = editor.onItemChange = editor.onOrderChange = function () {

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

                editor.onAddItems = function (items) {
                    tmpCarousalData = items;
                    $scope.data.content.carouselImages = editor.items;
                    Utility.digest($scope);
                };

                editor.onSpeedChange = function (speed) {
                    tmpCarousalSettings = {speed:speed,random:0};
                    $scope.data.content.speed = speed;
                    Utility.digest($scope);
                };

                editor.onRandomChange = function (random) {
                    tmpCarousalSettings = {speed:5000,random:random};
                    $scope.data.content.random = random;
                    Utility.digest($scope);
                };

                plugins.onAddItems = function () {
                    var scopeItems = $scope.data._buildfire.plugins.data;
                    var itemIds = getPluginsIds(plugins.items);
                    for (var i = 0; i < itemIds.length; i++) {
                        if (scopeItems.indexOf(itemIds[i]) == -1) {
                            scopeItems.push(itemIds[i]);
                        }
                    }

                    Utility.digest($scope);
                };

                plugins.onDeleteItem = function (item, index) {
                    if (plugins.items.length == 0) {
                        $scope.data._buildfire.plugins.data = [];
                    } else {
                        $scope.data._buildfire.plugins.data.splice(index, 1);
                    }

                    Utility.digest($scope);
                };

                plugins.onOrderChange = function (item, oldIndex, newIndex) {
                    var items = $scope.data._buildfire.plugins.data;

                    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;

                    $scope.data._buildfire = {
                        "plugins": {
                            "dataType": "pluginInstance",
                            "data": items
                        }
                    };

                    Utility.digest($scope);
                };

                plugins.onLoadAll = function () {
                    $scope.data.content.loadAllPlugins = true;

                    $("#plugins").find(".carousel-items").hide();
                    Utility.digest($scope);
                };

                plugins.onUnloadAll = function (items) {
                    $scope.data.content.loadAllPlugins = false;
                    $("#plugins").find(".carousel-items").show();
                    Utility.digest($scope);
                };

                var digest = function () {
                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                };
            }

        ]);
})(window.angular);<commit_msg>changes in edit constructor<commit_after>(function (angular) {
    "use strict";

    angular
        .module('folderPluginContent')
        .controller('folderPluginCtrl', ['$scope', 'Messaging', 'Utility',
            function ($scope, Messaging, Utility) {
                var tmpCarousalData = null;
                var tmpCarousalSettings=null;
                var editor = new buildfire.components.carousel.editor("#carousel",{},5,0);
                var _buildfire = {
                    plugins: {
                        dataType: "pluginInstance",
                        data: []
                    }
                };
                var _design = {
                    backgroundImage: null,
                    selectedLayout: 1,
                    backgroundblur: 0,
                    hideText: false
                };
                var navigationCallback = function (pluginData) {
                    Messaging.sendMessageToWidget({
                        name: 'OPEN_PLUGIN',
                        message: {
                            data: pluginData
                        }
                    });
                };
                var plugins = new buildfire.components.pluginInstance.sortableList("#plugins", [], { showIcon: true, confirmDeleteItem: false }, undefined, undefined, { itemEditable: true, navigationCallback: navigationCallback });
                var tmrDelay = null;
                var updateItem = null;
                $scope.editorOptions = Utility.getEditorOptions();
                $scope.masterData = Utility.getDefaultScopeData();
                $scope.datastoreInitialized = false;

                function isUnchanged(data) {
                    return angular.equals(data, $scope.masterData);
                }

                function updateMasterItem(data) {
                    $scope.masterData = angular.copy(data);
                }

                //Go pull any previously saved data
                buildfire.datastore.getWithDynamicData(function (err, result) {
                    if (!err) {
                        $scope.datastoreInitialized = true;
                    } else {
                        console.error("Error: ", err);
                        return;
                    }

                    var firstTimeVisit = false;
                    if (!result.id) {
                        result.data = Utility.getDefaultScopeData();
                        firstTimeVisit = true;
                    }

                    if (result && result.data && !angular.equals({}, result.data)) {
                        updateMasterItem(result.data);
                        $scope.data = result.data;
                        $scope.id = result.id;
                        if ($scope.data && $scope.data.content && $scope.data.content.carouselImages) {
                            editor.loadItems($scope.data.content.carouselImages);
                        }
                        if ($scope.data && $scope.data.content && $scope.data.content.speed) {
                            editor.setSpeed($scope.data.content.speed);
                        }
                        if ($scope.data && $scope.data.content && $scope.data.content.random) {
                            editor.setRandom($scope.data.content.random);
                        }
                        if ($scope.data && $scope.data._buildfire && $scope.data._buildfire.plugins && $scope.data._buildfire.plugins.result) {
                            var pluginsData = Utility.getPluginDetails($scope.data._buildfire.plugins.result, $scope.data._buildfire.plugins.data);
                            if ($scope.data.content && $scope.data.content.loadAllPlugins) {
                                if (pluginsData.length) {
                                    plugins.loadItems(pluginsData, "loadAll");
                                    $("#plugins").find(".carousel-items").hide();
                                } else {
                                    plugins.loadAllItems();
                                    $("#plugins").find(".carousel-items").hide();
                                }
                            } else {
                                plugins.loadItems(pluginsData, "selected");
                                $("#plugins").find(".carousel-items").show();
                            }
                        }

                        if ($scope.data && !$scope.data._buildfire) {
                            updateItem = angular.copy($scope.data);
                            updateItem._buildfire = _buildfire;
                            updateMasterItem(updateItem);
                            $scope.data = angular.copy(updateItem);
                        }

                        if ($scope.data && !$scope.data.design) {
                            updateItem = angular.copy($scope.data);
                            updateItem.design = _design;
                            updateMasterItem(updateItem);
                            $scope.data = angular.copy(updateItem);
                        }

                        if(firstTimeVisit){
                            setTimeout(function () {
                                saveData($scope.data);
                            }, 500);
                        }

                        if (tmrDelay) clearTimeout(tmrDelay);
                    }

                    /*
                     * watch for changes in data and trigger the saveDataWithDelay function on change
                     * */
                    $scope.$watch('data', saveDataWithDelay, true);
                    Utility.digest($scope);
                });

                /*
                 * Call the datastore to save the data object
                 */
                var saveData = function (newObj) {
                    if (!$scope.datastoreInitialized) {
                        console.error("Error with datastore didn't get called");
                        return;
                    }

                    if (newObj == undefined) return;
                    if ($scope.frmMain.$invalid) {
                        console.warn('invalid data, details will not be saved');
                        return;
                    }

                    if (newObj._buildfire && newObj._buildfire.plugins) {
                        newObj._buildfire.plugins.result = plugins.items;
                    }

                    updateMasterItem(newObj);

                    Utility.save(newObj);
                };

                /*
                 * create an artificial delay so api isnt called on every character entered
                 * */
                var saveDataWithDelay = function (newObj) {

                    if (tmrDelay) clearTimeout(tmrDelay);
                    if (isUnchanged(newObj)) {
                        return;
                    }
                    if (newObj.default) {
                        var instanceIds = newObj._buildfire.plugins.data;
                        var loadAllPlugins = newObj.content.loadAllPlugins;

                        newObj = Utility.getDefaultScopeBlankData();
                        newObj.content.loadAllPlugins = loadAllPlugins;

                        newObj._buildfire.plugins.data = instanceIds;
                        if (tmpCarousalData) {
                            editor.loadItems(tmpCarousalData);
                            newObj.content.carouselImages = tmpCarousalData;
                            tmpCarousalData = null;
                        } else {
                            editor.loadItems([]);
                        }

                        if(tmpCarousalSettings){
                            newObj.content.speed= tmpCarousalSettings.speed;
                            newObj.content.random= tmpCarousalSettings.random;
                        }

                        $scope.data = newObj;
                    }
                    tmrDelay = setTimeout(function () {
                        saveData(newObj);
                    }, 500);
                };

                var getPluginsIds = function (plugins) {
                    var pluginsIds = [];
                    for (var i = 0; i < plugins.length; i++) {
                        pluginsIds.push(plugins[i].instanceId);
                    }
                    return pluginsIds;
                };

                // this method will be called when a new item added to the list
                editor.onDeleteItem = editor.onItemChange = editor.onOrderChange = function () {

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

                editor.onAddItems = function (items) {
                    tmpCarousalData = items;
                    $scope.data.content.carouselImages = editor.items;
                    Utility.digest($scope);
                };

                editor.onSpeedChange = function (speed) {
                    tmpCarousalSettings = {speed:speed,random:0};
                    $scope.data.content.speed = speed;
                    Utility.digest($scope);
                };

                editor.onRandomChange = function (random) {
                    tmpCarousalSettings = {speed:5000,random:random};
                    $scope.data.content.random = random;
                    Utility.digest($scope);
                };

                plugins.onAddItems = function () {
                    var scopeItems = $scope.data._buildfire.plugins.data;
                    var itemIds = getPluginsIds(plugins.items);
                    for (var i = 0; i < itemIds.length; i++) {
                        if (scopeItems.indexOf(itemIds[i]) == -1) {
                            scopeItems.push(itemIds[i]);
                        }
                    }

                    Utility.digest($scope);
                };

                plugins.onDeleteItem = function (item, index) {
                    if (plugins.items.length == 0) {
                        $scope.data._buildfire.plugins.data = [];
                    } else {
                        $scope.data._buildfire.plugins.data.splice(index, 1);
                    }

                    Utility.digest($scope);
                };

                plugins.onOrderChange = function (item, oldIndex, newIndex) {
                    var items = $scope.data._buildfire.plugins.data;

                    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;

                    $scope.data._buildfire = {
                        "plugins": {
                            "dataType": "pluginInstance",
                            "data": items
                        }
                    };

                    Utility.digest($scope);
                };

                plugins.onLoadAll = function () {
                    $scope.data.content.loadAllPlugins = true;

                    $("#plugins").find(".carousel-items").hide();
                    Utility.digest($scope);
                };

                plugins.onUnloadAll = function (items) {
                    $scope.data.content.loadAllPlugins = false;
                    $("#plugins").find(".carousel-items").show();
                    Utility.digest($scope);
                };

                var digest = function () {
                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                };
            }

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


<commit_before>var coffeeLocations = [];
var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm:', '4:00pm', '5:00pm', '6:00pm', '7:00pm', '8:00pm:'];
var totals = [0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0];
var total = 0;
var inputForm = document.getElementById('input-form');

function CampCoffee (locationName, minCustomersHour, maxCustomersHour, avgCupsPerCustomer, avgPoundsPerCustomer) {
  this.locationName = locationName;
  this.minCustomersHour = minCustomersHour;
  this.maxCustomersHour = maxCustomersHour;
  this.avgCupsPerCustomer = avgCupsPerCustomer;
  this.avgPoundsPerCustomer = avgPoundsPerCustomer;
  this.totalBeansPerHour = [];
  this.cupsPerHour = [];
  this.poundsPerHour = [];
  this.customersPerHour = [];
  this.barristaPerHour = [];
  this.totalCustomers = 0;
  this.totalCups = 0;
  this.totalPounds = 0;
  this.totalBeans = 0;
  this.totalBarristaHours = 0;
  coffeeLocations.push(this);
};

CampCoffee.prototype.calcCustomersPerHour = function(min,max) {
  if (this.totalCustomers === 0) {
    for (var i = 0; i < hours.length; i ++) {
      var customers = Math.floor(Math.random() * (max - min + 1)) + min;
      this.customersPerHour.push(customers);
      this.totalCustomers += customers;
    }
  }
};

CampCoffee.prototype.calcTotalCupsPerHour = function() {
  if (this.totalCups === 0) {
    for (var i = 0; i < hours.length; i++) {
      var cups = this.customersPerHour[i] * this.avgCupsPerCustomer;
      this.totalCups += cups;
      this.cupsPerHour.push(cups);
    }
  }
};

CampCoffee.prototype.calcTotalPoundsPerHour = function() {
  if (this.totalPounds === 0) {
    for (var i = 0; i < hours.length; i++) {
      var beans = this.customersPerHour[i] * this.avgPoundsPerCustomer;
      this.totalPounds += beans;
      this.poundsPerHour.push(beans);
    }
  }
};

CampCoffee.prototype.calcHourlyBeans = function() {
  if (this.totalBeans === 0) {
    for (var i = 0; i < hours.length; i++) {
      var beans = this.poundsPerHour[i] + (this.cupsPerHour[i] / 16);
      this.totalBeansPerHour[i] = beans;
      this.totalBeans += beans;
    }
  }
};

CampCoffee.prototype.calcBaristaHours = function() {
  if (this.totalBarristaHours === 0) {
    for (var i = 0; i < hours.length; i++) {
      var barHours = Math.ceil((this.cupsPerHour[i] + this.poundsPerHour[i]) / 30);
      this.barristaPerHour[i] = barHours;
      this.totalBarristaHours += barHours;
    }
  }
};

CampCoffee.prototype.renderBeanRow = function() {
  var table = document.getElementById('beans-table');
  var trElement = document.createElement('tr');
  var tdElement = document.createElement('td');
  tdElement.textContent = this.locationName;
  trElement.appendChild(tdElement);
  tdElement = document.createElement('td');
  tdElement.textContent = Math.ceil(this.totalBeans);
  trElement.appendChild(tdElement);
  total += Math.ceil(this.totalBeans);
  for (var i = 0; i < hours.length; i++) {
    tdElement = document.createElement('td');
    tdElement.textContent = Math.ceil(this.totalBeansPerHour[i]);
    totals[i] += Math.ceil(this.totalBeansPerHour[i]);
    trElement.appendChild(tdElement);
  }
  table.appendChild(trElement);
};

CampCoffee.prototype.renderBaristaRow = function() {
  var table = document.getElementById('baristas-table');
  var trElement = document.createElement('tr');
  var tdElement = document.createElement('td');
  tdElement.textContent = this.locationName;
  trElement.appendChild(tdElement);
  tdElement = document.createElement('td');
  tdElement.textContent = Math.ceil(this.totalBarristaHours);
  trElement.appendChild(tdElement);
  total += Math.ceil(this.totalBarristaHours);
  for (var i = 0; i < hours.length; i++) {
    tdElement = document.createElement('td');
    tdElement.textContent = Math.ceil(this.barristaPerHour[i]);
    totals[i] += Math.ceil(this.barristaPerHour[i]);
    trElement.appendChild(tdElement);
  }
  table.appendChild(trElement);
};

var pikePlace = new CampCoffee('Pike Place Market', 14, 34, 1.2, 0.34);
var capitolHill = new CampCoffee('Capitol Hill', 12, 28, 3.2, 0.03);
var seattlePublicLibrary = new CampCoffee('Seattle Public Library', 9, 45, 2.6, 0.02);
var southLakeUnion = new CampCoffee('South Lake Union', 5, 18, 1.3, 0.04);
var seaTacAirport = new CampCoffee('SeaTac Airport', 28, 44, 1.1, 0.41);

// Create Bean total table
function renderAllBeans() {
  tableHeadings('Daily Location ', 'beans-table');
  for (var i = 0; i < coffeeLocations.length; i++) {
    coffeeLocations[i].renderBeanRow();
  }
  totalRow('beans-table');
}

// Create barista total table
function renderAllBarista() {
  var table = document.getElementById('baristas-table');
  tableHeadings('', 'baristas-table');
  for (var i = 0; i < coffeeLocations.length; i++) {
    coffeeLocations[i].renderBaristaRow();
  }
  totalRow('baristas-table');
}

// Create and append table header row for table with argument id
function tableHeadings (title, id) {
  var table = document.getElementById(id);
  var trElement = document.createElement('tr');
  var thElement = document.createElement('th');
  thElement.textContent = '';
  trElement.appendChild(thElement);
  thElement = document.createElement('th');
  thElement.textContent = title + 'Total';
  trElement.appendChild(thElement);
  for (var i = 0; i < hours.length; i++) {
    thElement = document.createElement('th');
    thElement.textContent = hours[i];
    trElement.appendChild(thElement);
  }
  table.appendChild(trElement);
};

// Create and append total row for table with argument id
function totalRow (id){
  var table = document.getElementById(id);
  var trElement = document.createElement('tr');
  var tdElement = document.createElement('td');
  tdElement.textContent = 'Total';
  trElement.appendChild(tdElement);
  tdElement = document.createElement('td');
  tdElement.textContent = Math.ceil(total);
  trElement.appendChild(tdElement);
  for (var i = 0; i < totals.length; i++) {
    tdElement = document.createElement('td');
    tdElement.textContent = totals[i];
    trElement.appendChild(tdElement);
  }
  table.appendChild(trElement);
}

function clearTotals() {
  total = 0;
  totals = [0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0];
}

// Populate each instances' array and totals properties
function calculateData() {
  for (var i = 0; i < coffeeLocations.length; i++) {
    coffeeLocations[i].calcCustomersPerHour(coffeeLocations[i].minCustomersHour, coffeeLocations[i].maxCustomersHour);
    coffeeLocations[i].calcTotalCupsPerHour();
    coffeeLocations[i].calcTotalPoundsPerHour();
    coffeeLocations[i].calcHourlyBeans();
    coffeeLocations[i].calcBaristaHours();
    console.log(coffeeLocations[i]);
  }
}

function handleLocationSubmit(event) {
  event.preventDefault();
  if (!event.target.locationInput.value || !event.target.minCustomersHour.value || !event.target.maxCustomersHour.value || !event.target.cupsPerCustomer.value || !event.target.packagedLbsPerCustomer.value) {
    return alert('Fields can not be empty');
  }
<<<<<<< HEAD

  var locationName = event.target.locationInput.value;
  var minCustomersHour = parseInt(event.target.minCustomersHour.value);
  var maxCustomersHour = parseInt(event.target.maxCustomersHour.value);
  var cupsPerCustomer = parseFloat(event.target.cupsPerCustomer.value);
  var packagedLbsPerCustomer = parseFloat(event.target.packagedLbsPerCustomer.value);
  // Check for repeated entry
  var preExistingLocation = false;
  for (var i = 0; i < coffeeLocations.length; i++) {
    if (locationName === coffeeLocations[i].locationName) {
      preExistingLocation = true;
      newLocationData = new CampCoffee(locationName, minCustomersHour, maxCustomersHour, cupsPerCustomer, packagedLbsPerCustomer);
      coffeeLocations.splice(i, 1, newLocationData); // Replace repeat location with new instance for that location
      coffeeLocations = coffeeLocations.slice(0, -1); // Remove extra instance pushed to array from constructor
=======
  var preExistingLocation = false;
  for (var i = 0; i < coffeeLocations.length; i++) {
    if (event.target.locationInput.value === coffeeLocations[i].locationName) {
      preExistingLocation = true;
      newLocationData = new CampCoffee(event.target.locationInput.value, parseInt(event.target.minCustomersHour.value), parseInt(event.target.maxCustomersHour.value), parseFloat(event.target.cupsPerCustomer.value), parseFloat(event.target.packagedLbsPerCustomer.value));
      coffeeLocations.splice(i, 1, newLocationData);
      coffeeLocations = coffeeLocations.slice(0, -1);
>>>>>>> d9a1063be6468ce07f6f962b2f2b0b7ef0cde3ec
      break;
    }
  }
  // Create new location if repeated entry not found
  if (!preExistingLocation) {
    var newLocation = new CampCoffee(locationName, minCustomersHour, maxCustomersHour, cupsPerCustomer, packagedLbsPerCustomer);
  }

  // Clear input fields
  event.target.locationInput.value = null;
  event.target.minCustomersHour.value = null;
  event.target.maxCustomersHour.value = null;
  event.target.cupsPerCustomer.value = null;
  event.target.packagedLbsPerCustomer.value = null;

  // Clear tables
  var table = document.getElementById('beans-table');
  table.innerHTML = '';
  table = document.getElementById('baristas-table');
  table.innerHTML = '';
  // Render tables with new input
  renderAll();
}

function renderAll() {
  calculateData(); // Fill instance data for all locations
  renderAllBeans(); // Fill in all table rows
  clearTotals(); // Reset total counters for total row
  renderAllBarista();// Fill in table rows
  clearTotals(); // Reset total counters
}
inputForm.addEventListener('submit', handleLocationSubmit);

renderAll();
<commit_msg>pushing<commit_after>var coffeeLocations = [];
var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm:', '4:00pm', '5:00pm', '6:00pm', '7:00pm', '8:00pm:'];
var totals = [0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0];
var total = 0;
var inputForm = document.getElementById('input-form');

function CampCoffee (locationName, minCustomersHour, maxCustomersHour, avgCupsPerCustomer, avgPoundsPerCustomer) {
  this.locationName = locationName;
  this.minCustomersHour = minCustomersHour;
  this.maxCustomersHour = maxCustomersHour;
  this.avgCupsPerCustomer = avgCupsPerCustomer;
  this.avgPoundsPerCustomer = avgPoundsPerCustomer;
  this.totalBeansPerHour = [];
  this.cupsPerHour = [];
  this.poundsPerHour = [];
  this.customersPerHour = [];
  this.barristaPerHour = [];
  this.totalCustomers = 0;
  this.totalCups = 0;
  this.totalPounds = 0;
  this.totalBeans = 0;
  this.totalBarristaHours = 0;
  coffeeLocations.push(this);
};

CampCoffee.prototype.calcCustomersPerHour = function(min,max) {
  if (this.totalCustomers === 0) {
    for (var i = 0; i < hours.length; i ++) {
      var customers = Math.floor(Math.random() * (max - min + 1)) + min;
      this.customersPerHour.push(customers);
      this.totalCustomers += customers;
    }
  }
};

CampCoffee.prototype.calcTotalCupsPerHour = function() {
  if (this.totalCups === 0) {
    for (var i = 0; i < hours.length; i++) {
      var cups = this.customersPerHour[i] * this.avgCupsPerCustomer;
      this.totalCups += cups;
      this.cupsPerHour.push(cups);
    }
  }
};

CampCoffee.prototype.calcTotalPoundsPerHour = function() {
  if (this.totalPounds === 0) {
    for (var i = 0; i < hours.length; i++) {
      var beans = this.customersPerHour[i] * this.avgPoundsPerCustomer;
      this.totalPounds += beans;
      this.poundsPerHour.push(beans);
    }
  }
};

CampCoffee.prototype.calcHourlyBeans = function() {
  if (this.totalBeans === 0) {
    for (var i = 0; i < hours.length; i++) {
      var beans = this.poundsPerHour[i] + (this.cupsPerHour[i] / 16);
      this.totalBeansPerHour[i] = beans;
      this.totalBeans += beans;
    }
  }
};

CampCoffee.prototype.calcBaristaHours = function() {
  if (this.totalBarristaHours === 0) {
    for (var i = 0; i < hours.length; i++) {
      var barHours = Math.ceil((this.cupsPerHour[i] + this.poundsPerHour[i]) / 30);
      this.barristaPerHour[i] = barHours;
      this.totalBarristaHours += barHours;
    }
  }
};

CampCoffee.prototype.renderBeanRow = function() {
  var table = document.getElementById('beans-table');
  var trElement = document.createElement('tr');
  var tdElement = document.createElement('td');
  tdElement.textContent = this.locationName;
  trElement.appendChild(tdElement);
  tdElement = document.createElement('td');
  tdElement.textContent = Math.ceil(this.totalBeans);
  trElement.appendChild(tdElement);
  total += Math.ceil(this.totalBeans);
  for (var i = 0; i < hours.length; i++) {
    tdElement = document.createElement('td');
    tdElement.textContent = Math.ceil(this.totalBeansPerHour[i]);
    totals[i] += Math.ceil(this.totalBeansPerHour[i]);
    trElement.appendChild(tdElement);
  }
  table.appendChild(trElement);
};

CampCoffee.prototype.renderBaristaRow = function() {
  var table = document.getElementById('baristas-table');
  var trElement = document.createElement('tr');
  var tdElement = document.createElement('td');
  tdElement.textContent = this.locationName;
  trElement.appendChild(tdElement);
  tdElement = document.createElement('td');
  tdElement.textContent = Math.ceil(this.totalBarristaHours);
  trElement.appendChild(tdElement);
  total += Math.ceil(this.totalBarristaHours);
  for (var i = 0; i < hours.length; i++) {
    tdElement = document.createElement('td');
    tdElement.textContent = Math.ceil(this.barristaPerHour[i]);
    totals[i] += Math.ceil(this.barristaPerHour[i]);
    trElement.appendChild(tdElement);
  }
  table.appendChild(trElement);
};

var pikePlace = new CampCoffee('Pike Place Market', 14, 34, 1.2, 0.34);
var capitolHill = new CampCoffee('Capitol Hill', 12, 28, 3.2, 0.03);
var seattlePublicLibrary = new CampCoffee('Seattle Public Library', 9, 45, 2.6, 0.02);
var southLakeUnion = new CampCoffee('South Lake Union', 5, 18, 1.3, 0.04);
var seaTacAirport = new CampCoffee('SeaTac Airport', 28, 44, 1.1, 0.41);

// Create Bean total table
function renderAllBeans() {
  tableHeadings('Daily Location ', 'beans-table');
  for (var i = 0; i < coffeeLocations.length; i++) {
    coffeeLocations[i].renderBeanRow();
  }
  totalRow('beans-table');
}

// Create barista total table
function renderAllBarista() {
  var table = document.getElementById('baristas-table');
  tableHeadings('', 'baristas-table');
  for (var i = 0; i < coffeeLocations.length; i++) {
    coffeeLocations[i].renderBaristaRow();
  }
  totalRow('baristas-table');
}

// Create and append table header row for table with argument id
function tableHeadings (title, id) {
  var table = document.getElementById(id);
  var trElement = document.createElement('tr');
  var thElement = document.createElement('th');
  thElement.textContent = '';
  trElement.appendChild(thElement);
  thElement = document.createElement('th');
  thElement.textContent = title + 'Total';
  trElement.appendChild(thElement);
  for (var i = 0; i < hours.length; i++) {
    thElement = document.createElement('th');
    thElement.textContent = hours[i];
    trElement.appendChild(thElement);
  }
  table.appendChild(trElement);
};
// Create and append total row for table with argument id
function totalRow (id){
  var table = document.getElementById(id);
  var trElement = document.createElement('tr');
  var tdElement = document.createElement('td');
  tdElement.textContent = 'Total';
  trElement.appendChild(tdElement);
  tdElement = document.createElement('td');
  tdElement.textContent = Math.ceil(total);
  trElement.appendChild(tdElement);
  for (var i = 0; i < totals.length; i++) {
    tdElement = document.createElement('td');
    tdElement.textContent = totals[i];
    trElement.appendChild(tdElement);
  }
  table.appendChild(trElement);
}
function clearTotals() {
  total = 0;
  totals = [0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0];
}
// Populate each instances' array and totals properties
function calculateData() {
  for (var i = 0; i < coffeeLocations.length; i++) {
    coffeeLocations[i].calcCustomersPerHour(coffeeLocations[i].minCustomersHour, coffeeLocations[i].maxCustomersHour);
    coffeeLocations[i].calcTotalCupsPerHour();
    coffeeLocations[i].calcTotalPoundsPerHour();
    coffeeLocations[i].calcHourlyBeans();
    coffeeLocations[i].calcBaristaHours();
    console.log(coffeeLocations[i]);
  }
}

function handleLocationSubmit(event) {
  event.preventDefault();
  if (!event.target.locationInput.value || !event.target.minCustomersHour.value || !event.target.maxCustomersHour.value || !event.target.cupsPerCustomer.value || !event.target.packagedLbsPerCustomer.value) {
    return alert('Fields can not be empty');
  }
  var locationName = event.target.locationInput.value;
  var minCustomersHour = parseInt(event.target.minCustomersHour.value);
  var maxCustomersHour = parseInt(event.target.maxCustomersHour.value);
  var cupsPerCustomer = parseFloat(event.target.cupsPerCustomer.value);
  var packagedLbsPerCustomer = parseFloat(event.target.packagedLbsPerCustomer.value);
  // Check for repeated entry
  var preExistingLocation = false;
  for (var i = 0; i < coffeeLocations.length; i++) {
    if (locationName === coffeeLocations[i].locationName) {
      preExistingLocation = true;
      newLocationData = new CampCoffee(locationName, minCustomersHour, maxCustomersHour, cupsPerCustomer, packagedLbsPerCustomer);
      coffeeLocations.splice(i, 1, newLocationData); // Replace repeat location with new instance for that location
      coffeeLocations = coffeeLocations.slice(0, -1); // Remove extra instance pushed to array from constructor
      break;
    }
  }
  // Create new location if repeated entry not found
  if (!preExistingLocation) {
    var newLocation = new CampCoffee(locationName, minCustomersHour, maxCustomersHour, cupsPerCustomer, packagedLbsPerCustomer);
  }

  // Clear input fields
  event.target.locationInput.value = null;
  event.target.minCustomersHour.value = null;
  event.target.maxCustomersHour.value = null;
  event.target.cupsPerCustomer.value = null;
  event.target.packagedLbsPerCustomer.value = null;

  // Clear tables
  var table = document.getElementById('beans-table');
  table.innerHTML = '';
  table = document.getElementById('baristas-table');
  table.innerHTML = '';
  // Render tables with new input
  renderAll();
}

function renderAll() {
  calculateData(); // Fill instance data for all locations
  renderAllBeans(); // Fill in all table rows
  clearTotals(); // Reset total counters for total row
  renderAllBarista();// Fill in table rows
  clearTotals(); // Reset total counters
}
inputForm.addEventListener('submit', handleLocationSubmit);

renderAll();
<|endoftext|>


<commit_before>// Browser check variables
// If you support IE, our recommendation is that you sign-in using Redirect APIs
// If you as a developer are testing using Edge InPrivate mode, please add "isEdge" to the if check
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
const msie11 = ua.indexOf("Trident/");
const msedge = ua.indexOf("Edge/");
const isIE = msie > 0 || msie11 > 0;
const isEdge = msedge > 0;

let username = "";

// Create the main myMSALObj instance
// configuration parameters are located at authConfig.js
const myMSALObj = new msal.PublicClientApplication(msalConfig);

// Redirect: once login is successful and redirects with tokens, call Graph API
myMSALObj.handleRedirectPromise().then(handleResponse).catch(function (err) {
    console.error(err);
});

function handleResponse(resp) {
    if (resp !== null) {
        username = resp.account.username;
        showWelcomeMessage();
    } else {
        // need to call getAccount here?
        const currentAccounts = myMSALObj.getAllAccounts();
        if (currentAccounts === null) {
            return;
        } else if (currentAccounts.length > 1) {
            // Add choose account code here
        } else if (currentAccounts.length === 1) {
            username = currentAccounts[0].username;
            console.log(username)
            showWelcomeMessage();
        }
    }
}

function signIn() {
    myMSALObj.loginRedirect(request)
}

function signOut() {
    const logoutRequest = {
        account: myMSALObj.getAccountByUsername(username)
    };

    myMSALObj.logout(logoutRequest);
}

function getTokenRedirect(request, account) {
    request.account = account;
    return new Promise(function(resolve, reject) {
        myMSALObj.acquireTokenSilent(request).then(function (response) {
            resolve(response)
        }).catch(function (error) {
            console.log("silent token acquisition fails.");
            if (error instanceof msal.InteractionRequiredAuthError) {
                // fallback to interaction when silent call fails
                console.log("acquiring token using redirect");
                myMSALObj.acquireTokenRedirect(request);
            } else {
                console.error(error);
                reject(error);
            }
        });
    });
}
<commit_msg>Add response handling for acquireTokenRedirect<commit_after>// Browser check variables
// If you support IE, our recommendation is that you sign-in using Redirect APIs
// If you as a developer are testing using Edge InPrivate mode, please add "isEdge" to the if check
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
const msie11 = ua.indexOf("Trident/");
const msedge = ua.indexOf("Edge/");
const isIE = msie > 0 || msie11 > 0;
const isEdge = msedge > 0;

let username = "";

// Create the main myMSALObj instance
// configuration parameters are located at authConfig.js
const myMSALObj = new msal.PublicClientApplication(msalConfig);

// Redirect: once login is successful and redirects with tokens, call Graph API
myMSALObj.handleRedirectPromise().then(handleResponse).catch(function (err) {
    console.error(err);
});

function handleResponse(resp) {
    if (resp !== null) {
        username = resp.account.username;
        showWelcomeMessage();

        if (resp.accessToken) {
            callMSGraph(graphConfig.graphMeEndpoint, resp.accessToken, updateUI);
            profileButton.style.display = 'none';
        }
    } else {
        // need to call getAccount here?
        const currentAccounts = myMSALObj.getAllAccounts();
        if (currentAccounts === null) {
            return;
        } else if (currentAccounts.length > 1) {
            // Add choose account code here
        } else if (currentAccounts.length === 1) {
            username = currentAccounts[0].username;
            console.log(username)
            showWelcomeMessage();
        }
    }
}

function signIn() {
    myMSALObj.loginRedirect(request)
}

function signOut() {
    const logoutRequest = {
        account: myMSALObj.getAccountByUsername(username)
    };

    myMSALObj.logout(logoutRequest);
}

function getTokenRedirect(request, account) {
    request.account = account;
    return new Promise(function(resolve, reject) {
        myMSALObj.acquireTokenSilent(request).then(function (response) {
            resolve(response)
        }).catch(function (error) {
            console.log("silent token acquisition fails.");
            if (error instanceof msal.InteractionRequiredAuthError) {
                // fallback to interaction when silent call fails
                console.log("acquiring token using redirect");
                myMSALObj.acquireTokenRedirect(request);
            } else {
                console.error(error);
                reject(error);
            }
        });
    });
}
<|endoftext|>


<commit_before>'use strict';

formsAngular.controller('AnalysisCtrl', ['$rootScope', '$window', '$filter', '$scope', '$http', '$location', 'cssFrameworkService', 'routingService',
    function ($rootScope, $window, $filter, $scope, $http, $location, cssFrameworkService, routingService) {
        /*jshint newcap: false */
        var firstTime = true,
            pdfPlugIn = new ngGridPdfExportPlugin({inhibitButton: true}),
            csvPlugIn = new ngGridCsvExportPlugin({inhibitButton: true});
        /*jshint newcap: true */

        angular.extend($scope, routingService.parsePathFunc()($location.$$path));

        $scope.reportSchema = {
            columnDefs: []
        };
        $scope.gridOptions = {
            data: 'report',
            columnDefs: $scope.reportSchema.columnDefs,
            showColumnMenu: true,
            enableRowHeaderSelection: false,
            enableFiltering: false,
            showGridFooter: false,
            reallyShowFooter: false,   // this determines whether it is actually displayed or not
            showTotals: true,
            enableColumnResizing: true,
//        enableColumnReordering: true,
//        jqueryUIDraggable: true,
            footerRowHeight: 65,
            multiSelect: false,
            plugins: [pdfPlugIn, csvPlugIn],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridOptions.plugins.forEach(function (p) {
                    p.init($scope, gridApi.grid, null);
                });
                gridApi.selection.on.rowSelectionChanged($scope, function afterSelectionChange(rowItem) {
                    var url = $scope.reportSchema.drilldown;
                    if (url) {
                        if (typeof url === 'string') {
                            url = routingService.buildUrl(url.replace(/\|.+?\|/g, function (match) {
                                var param = match.slice(1, -1),
                                    isParamTest = /\((.+)\)/.exec(param);
                                if (isParamTest) {
                                    var instructions = $scope.reportSchema.params[isParamTest[1]];
                                    if (instructions) {
                                        $scope.param = $scope.record[isParamTest[1]];
                                        if (instructions.conversionExpression) {
                                            return $scope.$eval(instructions.conversionExpression);
                                        } else {
                                            return instructions.value;
                                        }
                                    } else {
                                        return $scope.reportSchema.params[isParamTest[1]].value;
                                    }
                                } else {
                                    return rowItem.entity[param];
                                }
                            }));
                            window.location = url;
                        } else {
                            console.error('Was expecting drilldown to be string but it was ' + typeof url + ' (' + url + ')'); // trying to track down Sentry 3037641567
                        }
                    }
                });
            },
        };
        $scope.report = [];

        function parseAndHandleError(str) {
            try {
                return JSON.parse(str);
            } catch (e) {
                throw new Error(`Invalid JSON ${str}
${e.message}`);
            }
        }

        if (!$scope.reportSchemaName && $location.$$search.r) {
            switch ($location.$$search.r.slice(0, 1)) {
                case '[' :
                    $scope.reportSchema.pipeline = parseAndHandleError($location.$$search.r);
                    break;
                case '{' :
                    angular.extend($scope.reportSchema, parseAndHandleError($location.$$search.r));
                    break;
                default :
                    throw new Error('No report instructions specified');
            }
        }

        $scope.getTotalVal = function (field, filter) {
            var result = '',
                instructions = _.find($scope.reportSchema.columnDefs, function (col) {
                    return col.field === field;
                });

            if (instructions) {
                switch (instructions.totalsRow) {
                    case undefined :
                        break;
                    case '$SUM' :
                        var sum = 0;
                        for (var j = 0; j < $scope.report.length; j++) {
                            sum += $scope.report[j][field];
                        }
                        result = sum;
                        if (filter) {
                            result = $filter(filter)(result);
                        }
                        break;
                    default :
                        result = instructions.totalsRow;
                        break;
                }
            }

            return result;
        };

        $scope.$on('exportToPDF', function () {
            pdfPlugIn.createPDF();
        });

        $scope.$on('exportToCSV', function () {
            csvPlugIn.createCSV();
        });

        $scope.extractFilter = function (col, filters) {
            if (col.cellFilter) {
                var filterName;
                var filterParam;
                var paramPos = col.cellFilter.indexOf(':');
                if (paramPos === -1) {
                    filterName = col.cellFilter;
                } else {
                    filterName = col.cellFilter.slice(0, paramPos).trim();
                    filterParam = col.cellFilter.slice(paramPos + 1, 999).trim();
                    if (filterParam[0] === '\'' || filterParam[0] === '"') {
                        filterParam = filterParam.slice(1, -1);
                    }
                }
                var filter = angular.element(document.body).injector().get('$filter')(filterName.trim());
                filters[col.field] = {filter: filter, filterParam: filterParam};
            }
        };

        function setupParamsForm(params) {
            $scope.paramSchema = [];
            // set up parameters
            $scope.record = {};
            for (var param in params) {
                if (params.hasOwnProperty(param)) {
                    var thisPart = params[param];
                    // if noInput then this value will be inferred from another parameter
                    if (!thisPart.noInput) {
                        var newLen = $scope.paramSchema.push({
                            name: param,
                            id: 'fp_' + param,
                            label: thisPart.label || $filter('titleCase')(param),
                            type: thisPart.type || 'text',
                            required: true,
                            add: thisPart.add || undefined,
                            size: thisPart.size || (cssFrameworkService.frameWork === 'bs3' ? 'large' : 'medium')
                        });
                        if (thisPart.type === 'select') {
                            // TODO: Remove when select and select2 is modified during the restructure
                            $scope[param + '_Opts'] = thisPart.enum;
                            $scope.paramSchema[newLen - 1].options = param + '_Opts';
                        }
                    }
                    var dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(thisPart.value);
                    if (dateTest) {
                        thisPart.value = new Date(dateTest[1]);
                    }
                    $scope.record[param] = thisPart.value;
                }
            }
            $scope.$watch('record', function (newValue, oldValue) {
                if (oldValue !== newValue) {
                    $scope.refreshQuery();
                }
            }, true);
        }

        var container = document.querySelector('div.report-grow');
        if (container) {
            var margin = container.offsetLeft;  // let's have the same top and bottom margins as we have side margin
            var topOffset = container.offsetTop + margin;
            var header = document.querySelector('div.ui-grid-header');
            var headerHeight = header ? header.clientHeight : 31;
            var availRows = Math.floor(($window.innerHeight - topOffset - headerHeight - margin) / 30);
            angular.element(container).css('height', '' + availRows * 30 + 'px');
        }

        var navScope = $rootScope.navScope;
        navScope.items = [
            {
                fn: pdfPlugIn.createPDF,
                text: 'Save as PDF'
            },
            {
                fn: csvPlugIn.createCSV,
                text: 'Export as CSV'
            }
        ];
        navScope.contextMenu = 'Report';
        $scope.titleWithSubstitutions = $scope.reportSchema.title;

//  inhibitRefresh can be set by a controller, for example if report data is being provided as part of the URL
        if (!$scope.inhibitRefresh) {

            $scope.refreshQuery = function () {

                function substituteParams(str) {
                    return str.replace(/\|.+?\|/g, function (match) {
                        var param = match.slice(1, -1);
                        var isParamTest = /\((.+)\)/.exec(param);
                        return isParamTest ? $scope.reportSchema.params[isParamTest[1]].value : '';
                    });
                }

                var apiCall = '/api/report/' + $scope.modelName;
                var connector = '?';
                var haveUrlParams = false;
                var query = $location.$$url.match(/\?.*/);

                if ($scope.reportSchemaName) {
                    apiCall += '/' + $scope.reportSchemaName;
                } else if (query) {
                    if (firstTime) {
                        // See if we have params in the URL (rather than going through schemaName)
                        $scope.paramSchema = JSON.parse($location.search().r).params;
                        setupParamsForm($scope.paramSchema);
                    }
                    apiCall += connector + query[0].slice(1);
                    connector = '&';
                    haveUrlParams = true;
                }

                if ($scope.paramSchema) {
                    // we are using the params form
                    for (var paramVal in $scope.record) {
                        if ($scope.record.hasOwnProperty(paramVal)) {
                            var instructions = $scope.reportSchema.params[paramVal];
                            if ($scope.record[paramVal] && $scope.record[paramVal] !== '') {
                                $scope.param = $scope.record[paramVal];
                                if (instructions.conversionExpression) {
                                    $scope.param = $scope.$eval(instructions.conversionExpression);
                                }
                                apiCall += connector + paramVal + '=' + $scope.param;
                                connector = '&';
                            } else if (instructions.required) {
                                // Don't do a round trip if a required field is empty - it will show up red
                                return;
                            }
                        }
                    }
                } else {
                    if (!haveUrlParams && query) {
                        apiCall += connector + query[0].slice(1);
                        connector = '&';
                    }
                }
                return $http.get(apiCall).then(function (response) {
                    if (response && response.data && response.data.success) {
                        var data = response.data;
                        $scope.report = data.report;
                        $scope.reportSchema = data.schema;
                        $scope.reportSchema.title = $scope.reportSchema.title || $scope.modelName;
                        $scope.titleWithSubstitutions = substituteParams($scope.reportSchema.title);
                        $scope.gridOptions.enableFiltering = !!$scope.reportSchema.filter;
                        if (navScope && navScope.items) {
                            navScope.items.length = 2;
                            if ($scope.reportSchema.menu) {
                                $scope.reportSchema.menu.forEach(function (m) {
                                    navScope.items.push(JSON.parse(substituteParams(JSON.stringify(m))));
                                });
                            }
                        }

                        /*
                        Generate link data
                         */

                        if (firstTime) {
                            firstTime = false;

                            $scope.$watch('reportSchema.columnDefs', function (newValue) {
                                var columnTotals = false;
                                if (newValue) {
                                    for (var i = 0; i < newValue.length; i++) {
                                        if (newValue[i].totalsRow) {
                                            columnTotals = true;
                                        }
                                        if (newValue[i].align) {
                                            var alignClass = 'fng-' + newValue[i].align;
                                            newValue[i].cellClass = newValue[i].cellClass || '';
                                            if (newValue[i].cellClass.indexOf(alignClass) === -1) {
                                                newValue[i].cellClass = newValue[i].cellClass + ' ' + alignClass;
                                            }
                                        }
                                    }
                                    // Auto-upgrade from ng-grid to ui-grid
                                    newValue.forEach(function (def) {
                                        // Remove px from column widths
                                        if (def.width && typeof def.width === 'string' && def.width.indexOf('px') !== -1) {
                                            def.width = parseInt(def.width.slice(0, -2));
                                        }
                                    });
                                    $scope.gridOptions.columnDefs = newValue;
                                }
                                $scope.gridOptions.showTotals = columnTotals;
                                $scope.gridOptions.reallyShowFooter = columnTotals;
                                $scope.gridOptions.footerRowHeight = 55 + (columnTotals ? 10 : 0);
                            }, true);

                            if (!$scope.paramSchema && data.schema.params) {
                                setupParamsForm(data.schema.params);
                            }
                        }
                    } else {
                        $scope.showError(JSON.stringify(response.data.error), 'Invalid Response Error');
                        $scope.reportSchema.title = 'Error - see console log';
                    }
                }, function () {
                    $scope.showError('The server could not process the request', 'Error');
                });
            };

            $scope.refreshQuery();
        }

        // Check whether a cell template shows the content (in which case we want to output it) or does something funky
        // (for example displays an image)
        $scope.showsContent = function (template, col) {
            if (/{{[\s]*COL_FIELD[\s]*}}/.test(template.replace(/(<([^>]+)>)/gi, ''))) {
                return true;
            } else if (template.indexOf('ng-bind-html="row.entity.' + col) !== -1) {
                return 'HTML';
            }
        };

        $scope.$on('$locationChangeStart', function () {
            delete navScope.contextMenu;
            delete navScope.items;
        });

        // Error handling, stolen quickly from forms-angulat record-handler
        $scope.showError = function(error, alertTitle) {
            $scope.alertTitle = alertTitle ? alertTitle : 'Error!';
            if (typeof error === 'string') {
                $scope.errorMessage = error;
            } else if (!error) {
                $scope.errorMessage = `An error occurred - that's all we got.  Sorry.`;
            } else if (error.message && typeof error.message === 'string') {
                $scope.errorMessage = error.message;
            } else if (error.data && error.data.message) {
                $scope.errorMessage = error.data.message;
            } else {
                try {
                    $scope.errorMessage = JSON.stringify(error);
                } catch (e) {
                    $scope.errorMessage = error;
                }
            }
            $scope.errorHideTimer = window.setTimeout(function() {
                $scope.dismissError();
                $scope.$digest();
            }, 3500 + (1000 * ($scope.alertTitle + $scope.errorMessage).length / 50));
            $scope.errorVisible = true;
            window.setTimeout(() => {
                $scope.$digest();
            });
        };

        $scope.clearTimeout = function() {
            if ($scope.errorHideTimer) {
                clearTimeout($scope.errorHideTimer);
                delete $scope.errorHideTimer;
            }
        };

        $scope.dismissError = function() {
            $scope.clearTimeout;
            $scope.errorVisible = false;
            delete $scope.errorMessage;
            delete $scope.alertTitle;
        };

        $scope.stickError = function() {
            clearTimeout($scope.errorHideTimer);
        };

    }]);
<commit_msg>Don't lose the timezone when creating date<commit_after>'use strict';

formsAngular.controller('AnalysisCtrl', ['$rootScope', '$window', '$filter', '$scope', '$http', '$location', 'cssFrameworkService', 'routingService',
    function ($rootScope, $window, $filter, $scope, $http, $location, cssFrameworkService, routingService) {
        /*jshint newcap: false */
        var firstTime = true,
            pdfPlugIn = new ngGridPdfExportPlugin({inhibitButton: true}),
            csvPlugIn = new ngGridCsvExportPlugin({inhibitButton: true});
        /*jshint newcap: true */

        angular.extend($scope, routingService.parsePathFunc()($location.$$path));

        $scope.reportSchema = {
            columnDefs: []
        };
        $scope.gridOptions = {
            data: 'report',
            columnDefs: $scope.reportSchema.columnDefs,
            showColumnMenu: true,
            enableRowHeaderSelection: false,
            enableFiltering: false,
            showGridFooter: false,
            reallyShowFooter: false,   // this determines whether it is actually displayed or not
            showTotals: true,
            enableColumnResizing: true,
//        enableColumnReordering: true,
//        jqueryUIDraggable: true,
            footerRowHeight: 65,
            multiSelect: false,
            plugins: [pdfPlugIn, csvPlugIn],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridOptions.plugins.forEach(function (p) {
                    p.init($scope, gridApi.grid, null);
                });
                gridApi.selection.on.rowSelectionChanged($scope, function afterSelectionChange(rowItem) {
                    var url = $scope.reportSchema.drilldown;
                    if (url) {
                        if (typeof url === 'string') {
                            url = routingService.buildUrl(url.replace(/\|.+?\|/g, function (match) {
                                var param = match.slice(1, -1),
                                    isParamTest = /\((.+)\)/.exec(param);
                                if (isParamTest) {
                                    var instructions = $scope.reportSchema.params[isParamTest[1]];
                                    if (instructions) {
                                        $scope.param = $scope.record[isParamTest[1]];
                                        if (instructions.conversionExpression) {
                                            return $scope.$eval(instructions.conversionExpression);
                                        } else {
                                            return instructions.value;
                                        }
                                    } else {
                                        return $scope.reportSchema.params[isParamTest[1]].value;
                                    }
                                } else {
                                    return rowItem.entity[param];
                                }
                            }));
                            window.location = url;
                        } else {
                            console.error('Was expecting drilldown to be string but it was ' + typeof url + ' (' + url + ')'); // trying to track down Sentry 3037641567
                        }
                    }
                });
            },
        };
        $scope.report = [];

        function parseAndHandleError(str) {
            try {
                return JSON.parse(str);
            } catch (e) {
                throw new Error(`Invalid JSON ${str}
${e.message}`);
            }
        }

        if (!$scope.reportSchemaName && $location.$$search.r) {
            switch ($location.$$search.r.slice(0, 1)) {
                case '[' :
                    $scope.reportSchema.pipeline = parseAndHandleError($location.$$search.r);
                    break;
                case '{' :
                    angular.extend($scope.reportSchema, parseAndHandleError($location.$$search.r));
                    break;
                default :
                    throw new Error('No report instructions specified');
            }
        }

        $scope.getTotalVal = function (field, filter) {
            var result = '',
                instructions = _.find($scope.reportSchema.columnDefs, function (col) {
                    return col.field === field;
                });

            if (instructions) {
                switch (instructions.totalsRow) {
                    case undefined :
                        break;
                    case '$SUM' :
                        var sum = 0;
                        for (var j = 0; j < $scope.report.length; j++) {
                            sum += $scope.report[j][field];
                        }
                        result = sum;
                        if (filter) {
                            result = $filter(filter)(result);
                        }
                        break;
                    default :
                        result = instructions.totalsRow;
                        break;
                }
            }

            return result;
        };

        $scope.$on('exportToPDF', function () {
            pdfPlugIn.createPDF();
        });

        $scope.$on('exportToCSV', function () {
            csvPlugIn.createCSV();
        });

        $scope.extractFilter = function (col, filters) {
            if (col.cellFilter) {
                var filterName;
                var filterParam;
                var paramPos = col.cellFilter.indexOf(':');
                if (paramPos === -1) {
                    filterName = col.cellFilter;
                } else {
                    filterName = col.cellFilter.slice(0, paramPos).trim();
                    filterParam = col.cellFilter.slice(paramPos + 1, 999).trim();
                    if (filterParam[0] === '\'' || filterParam[0] === '"') {
                        filterParam = filterParam.slice(1, -1);
                    }
                }
                var filter = angular.element(document.body).injector().get('$filter')(filterName.trim());
                filters[col.field] = {filter: filter, filterParam: filterParam};
            }
        };

        function setupParamsForm(params) {
            $scope.paramSchema = [];
            // set up parameters
            $scope.record = {};
            for (var param in params) {
                if (params.hasOwnProperty(param)) {
                    var thisPart = params[param];
                    // if noInput then this value will be inferred from another parameter
                    if (!thisPart.noInput) {
                        var newLen = $scope.paramSchema.push({
                            name: param,
                            id: 'fp_' + param,
                            label: thisPart.label || $filter('titleCase')(param),
                            type: thisPart.type || 'text',
                            required: true,
                            add: thisPart.add || undefined,
                            size: thisPart.size || (cssFrameworkService.frameWork === 'bs3' ? 'large' : 'medium')
                        });
                        if (thisPart.type === 'select') {
                            // TODO: Remove when select and select2 is modified during the restructure
                            $scope[param + '_Opts'] = thisPart.enum;
                            $scope.paramSchema[newLen - 1].options = param + '_Opts';
                        }
                    }
                    var dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(thisPart.value);
                    if (dateTest) {
                        thisPart.value = new Date(thisPart.value);
                    }
                    $scope.record[param] = thisPart.value;
                }
            }
            $scope.$watch('record', function (newValue, oldValue) {
                if (oldValue !== newValue) {
                    $scope.refreshQuery();
                }
            }, true);
        }

        var container = document.querySelector('div.report-grow');
        if (container) {
            var margin = container.offsetLeft;  // let's have the same top and bottom margins as we have side margin
            var topOffset = container.offsetTop + margin;
            var header = document.querySelector('div.ui-grid-header');
            var headerHeight = header ? header.clientHeight : 31;
            var availRows = Math.floor(($window.innerHeight - topOffset - headerHeight - margin) / 30);
            angular.element(container).css('height', '' + availRows * 30 + 'px');
        }

        var navScope = $rootScope.navScope;
        navScope.items = [
            {
                fn: pdfPlugIn.createPDF,
                text: 'Save as PDF'
            },
            {
                fn: csvPlugIn.createCSV,
                text: 'Export as CSV'
            }
        ];
        navScope.contextMenu = 'Report';
        $scope.titleWithSubstitutions = $scope.reportSchema.title;

//  inhibitRefresh can be set by a controller, for example if report data is being provided as part of the URL
        if (!$scope.inhibitRefresh) {

            $scope.refreshQuery = function () {

                function substituteParams(str) {
                    return str.replace(/\|.+?\|/g, function (match) {
                        var param = match.slice(1, -1);
                        var isParamTest = /\((.+)\)/.exec(param);
                        return isParamTest ? $scope.reportSchema.params[isParamTest[1]].value : '';
                    });
                }

                var apiCall = '/api/report/' + $scope.modelName;
                var connector = '?';
                var haveUrlParams = false;
                var query = $location.$$url.match(/\?.*/);

                if ($scope.reportSchemaName) {
                    apiCall += '/' + $scope.reportSchemaName;
                } else if (query) {
                    if (firstTime) {
                        // See if we have params in the URL (rather than going through schemaName)
                        $scope.paramSchema = JSON.parse($location.search().r).params;
                        setupParamsForm($scope.paramSchema);
                    }
                    apiCall += connector + query[0].slice(1);
                    connector = '&';
                    haveUrlParams = true;
                }

                if ($scope.paramSchema) {
                    // we are using the params form
                    for (var paramVal in $scope.record) {
                        if ($scope.record.hasOwnProperty(paramVal)) {
                            var instructions = $scope.reportSchema.params[paramVal];
                            if ($scope.record[paramVal] && $scope.record[paramVal] !== '') {
                                $scope.param = $scope.record[paramVal];
                                if (instructions.conversionExpression) {
                                    $scope.param = $scope.$eval(instructions.conversionExpression);
                                }
                                apiCall += connector + paramVal + '=' + $scope.param;
                                connector = '&';
                            } else if (instructions.required) {
                                // Don't do a round trip if a required field is empty - it will show up red
                                return;
                            }
                        }
                    }
                } else {
                    if (!haveUrlParams && query) {
                        apiCall += connector + query[0].slice(1);
                        connector = '&';
                    }
                }
                return $http.get(apiCall).then(function (response) {
                    if (response && response.data && response.data.success) {
                        var data = response.data;
                        $scope.report = data.report;
                        $scope.reportSchema = data.schema;
                        $scope.reportSchema.title = $scope.reportSchema.title || $scope.modelName;
                        $scope.titleWithSubstitutions = substituteParams($scope.reportSchema.title);
                        $scope.gridOptions.enableFiltering = !!$scope.reportSchema.filter;
                        if (navScope && navScope.items) {
                            navScope.items.length = 2;
                            if ($scope.reportSchema.menu) {
                                $scope.reportSchema.menu.forEach(function (m) {
                                    navScope.items.push(JSON.parse(substituteParams(JSON.stringify(m))));
                                });
                            }
                        }

                        /*
                        Generate link data
                         */

                        if (firstTime) {
                            firstTime = false;

                            $scope.$watch('reportSchema.columnDefs', function (newValue) {
                                var columnTotals = false;
                                if (newValue) {
                                    for (var i = 0; i < newValue.length; i++) {
                                        if (newValue[i].totalsRow) {
                                            columnTotals = true;
                                        }
                                        if (newValue[i].align) {
                                            var alignClass = 'fng-' + newValue[i].align;
                                            newValue[i].cellClass = newValue[i].cellClass || '';
                                            if (newValue[i].cellClass.indexOf(alignClass) === -1) {
                                                newValue[i].cellClass = newValue[i].cellClass + ' ' + alignClass;
                                            }
                                        }
                                    }
                                    // Auto-upgrade from ng-grid to ui-grid
                                    newValue.forEach(function (def) {
                                        // Remove px from column widths
                                        if (def.width && typeof def.width === 'string' && def.width.indexOf('px') !== -1) {
                                            def.width = parseInt(def.width.slice(0, -2));
                                        }
                                    });
                                    $scope.gridOptions.columnDefs = newValue;
                                }
                                $scope.gridOptions.showTotals = columnTotals;
                                $scope.gridOptions.reallyShowFooter = columnTotals;
                                $scope.gridOptions.footerRowHeight = 55 + (columnTotals ? 10 : 0);
                            }, true);

                            if (!$scope.paramSchema && data.schema.params) {
                                setupParamsForm(data.schema.params);
                            }
                        }
                    } else {
                        $scope.showError(JSON.stringify(response.data.error), 'Invalid Response Error');
                        $scope.reportSchema.title = 'Error - see console log';
                    }
                }, function () {
                    $scope.showError('The server could not process the request', 'Error');
                });
            };

            $scope.refreshQuery();
        }

        // Check whether a cell template shows the content (in which case we want to output it) or does something funky
        // (for example displays an image)
        $scope.showsContent = function (template, col) {
            if (/{{[\s]*COL_FIELD[\s]*}}/.test(template.replace(/(<([^>]+)>)/gi, ''))) {
                return true;
            } else if (template.indexOf('ng-bind-html="row.entity.' + col) !== -1) {
                return 'HTML';
            }
        };

        $scope.$on('$locationChangeStart', function () {
            delete navScope.contextMenu;
            delete navScope.items;
        });

        // Error handling, stolen quickly from forms-angulat record-handler
        $scope.showError = function(error, alertTitle) {
            $scope.alertTitle = alertTitle ? alertTitle : 'Error!';
            if (typeof error === 'string') {
                $scope.errorMessage = error;
            } else if (!error) {
                $scope.errorMessage = `An error occurred - that's all we got.  Sorry.`;
            } else if (error.message && typeof error.message === 'string') {
                $scope.errorMessage = error.message;
            } else if (error.data && error.data.message) {
                $scope.errorMessage = error.data.message;
            } else {
                try {
                    $scope.errorMessage = JSON.stringify(error);
                } catch (e) {
                    $scope.errorMessage = error;
                }
            }
            $scope.errorHideTimer = window.setTimeout(function() {
                $scope.dismissError();
                $scope.$digest();
            }, 3500 + (1000 * ($scope.alertTitle + $scope.errorMessage).length / 50));
            $scope.errorVisible = true;
            window.setTimeout(() => {
                $scope.$digest();
            });
        };

        $scope.clearTimeout = function() {
            if ($scope.errorHideTimer) {
                clearTimeout($scope.errorHideTimer);
                delete $scope.errorHideTimer;
            }
        };

        $scope.dismissError = function() {
            $scope.clearTimeout;
            $scope.errorVisible = false;
            delete $scope.errorMessage;
            delete $scope.alertTitle;
        };

        $scope.stickError = function() {
            clearTimeout($scope.errorHideTimer);
        };

    }]);
<|endoftext|>