<commit_before>'use strict';

// This module is used by user, business-process-submitted and inspector routes.
module.exports = function (uniqueKey/*, collection*/) {
	var collection = arguments[1] || 'userApplicable';

	if (this.businessProcess.isClosed) {
		if (!this.businessProcess.isApproved) return false;

		this.businessProcess.certificates.dataSnapshot.resolved.some(function (data) {
			if (data.uniqueKey === uniqueKey) {
				this.dataSnapshot = data;
				return true;
			}
		}, this);
		if (!this.dataSnapshot) return false;
	}

	this.businessProcess.certificates[collection].some(function (certificate) {
		if (certificate.key === uniqueKey) {
			this.document = certificate;
			return true;
		}
	}, this);

	if (!this.businessProcess.isClosed && !this.document) return false;

	this.documentKind = 'certificate';
	this.documentUniqueKey = uniqueKey;
	this.documentUniqueId = this.businessProcess.__id__ + '/' + this.documentKind + '/' + uniqueKey;
	return true;
};
<commit_msg>Issue #1704. Pass collection as options<commit_after>'use strict';

var normalizeOptions = require('es5-ext/object/normalize-options');

// This module is used by user, business-process-submitted and inspector routes.
module.exports = function (uniqueKey/*, options*/) {
	var options    = normalizeOptions(arguments[1])
	  , collection = options.collection || 'userApplicable';

	if (this.businessProcess.isClosed) {
		if (!this.businessProcess.isApproved) return false;

		this.businessProcess.certificates.dataSnapshot.resolved.some(function (data) {
			if (data.uniqueKey === uniqueKey) {
				this.dataSnapshot = data;
				return true;
			}
		}, this);
		if (!this.dataSnapshot) return false;
	}

	this.businessProcess.certificates[collection].some(function (certificate) {
		if (certificate.key === uniqueKey) {
			this.document = certificate;
			return true;
		}
	}, this);

	if (!this.businessProcess.isClosed && !this.document) return false;

	this.documentKind = 'certificate';
	this.documentUniqueKey = uniqueKey;
	this.documentUniqueId = this.businessProcess.__id__ + '/' + this.documentKind + '/' + uniqueKey;
	return true;
};
<|endoftext|>


<commit_before>cbecc.controller('ConstructionsCtrl', [
  '$scope', '$location', '$modal', 'uiGridConstants', 'toaster', 'ConstructionDefaults', 'Shared', 'constData', 'fenData', 'defaults', function ($scope, $location, $modal, uiGridConstants, toaster, ConstructionDefaults, Shared, constData, fenData, defaults) {
    Shared.stopSpinner();

    // construction data
    $scope.constData = constData;
    $scope.fenData = fenData;

    // retrieve saved defaults (if any)
    $scope.defaults = defaults[0] || {};

    // retrieve each saved default record from ids
    function getSelected(the_data, the_id) {
      return _.find(the_data, {
        id: the_id
      });
    }

    //collapsible panels
    $scope.panels = [{
      title: 'Exterior Wall Construction',
      name: 'exterior_wall'
    }, {
      title: 'Interior Wall Construction',
      name: 'interior_wall'
    }, {
      title: 'Underground Wall Construction',
      name: 'underground_wall'
    }, {
      title: 'Roof Construction',
      name: 'roof'
    }, {
      title: 'Door Construction',
      name: 'door'
    }, {
      title: 'Interior Floor Construction',
      name: 'interior_floor'
    }, {
      title: 'Exterior Floor Construction',
      name: 'exterior_floor'
    }, {
      title: 'Underground Floor Construction',
      name: 'underground_floor'
    }];

    $scope.panels.forEach(function (panel) {
      panel.gridOptions = {
        columnDefs: [{
          name: 'name',
          displayName: 'Layer'
        }, {
          name: 'code_category'
        }],
        enableColumnMenus: false,
        enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
        enableSorting: false,
        enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER
      };

      // retrieve selected and layers
      var sel = getSelected($scope.constData, $scope.defaults[panel.name]);
      if (sel) {
        panel.selected = sel;
        panel.gridOptions.data = sel.layers;
        panel.open = true;
      } else {
        panel.open = false;
      }
    });

    $scope.fenPanels = [{
      title: 'Window Construction',
      name: 'window'
    }, {
      title: 'Skylight Construction',
      name: 'skylight'
    }];

    $scope.fenPanels.forEach(function (panel) {
      panel.fenGridOptions = {
        columnDefs: [{
          name: 'name'
        }, {
          name: 'fenestration_framing',
          displayName: 'Frame Type'
        }, {
          name: 'fenestration_panes',
          displayName: 'Panes'
        }, {
          name: 'fenestration_product_type',
          displayName: 'Product Type',
          visible: panel.name == 'window'
        }, {
          name: 'glazing_tint',
          visible: panel.name == 'window'
        }, {
          name: 'u_factor'
        }, {
          name: 'shgc',
          displayName: 'Solar Heat Gain Coefficient',
          visible: panel.name == 'window'
        }, {
          name: 'skylight_curb',
          visible: panel.name == 'skylight'
        }],
        enableColumnMenus: false,
        enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
        enableSorting: false,
        enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER
      };

      // retrieve selected
      var sel = getSelected($scope.fenData, $scope.defaults[panel.name]);
      if (sel) {
        panel.selected = sel;
        panel.fenGridOptions.data = [sel];
        panel.open = true;
      } else {
        panel.open = false;
      }
    });

    // Modal Settings
    $scope.openLibraryModal = function (index, rowEntity) {
      var modalInstance = $modal.open({
        backdrop: 'static',
        controller: 'ModalConstructionsLibraryCtrl',
        templateUrl: 'constructions/library.html',
        windowClass: 'wide-modal',
        resolve: {
          params: function () {
            return {
              data: $scope.constData,
              rowEntity: rowEntity,
              title: $scope.panels[index].title
            };
          }
        }
      });

      modalInstance.result.then(function (selectedConstruction) {
        $scope.panels[index].selected = selectedConstruction;
        $scope.panels[index].gridOptions.data = selectedConstruction.layers;
      }, function () {
        // Modal canceled
      });
    };

    // Modal Settings
    $scope.openFenLibraryModal = function (index, rowEntity) {
      var modalInstance = $modal.open({
        backdrop: 'static',
        controller: 'ModalFenestrationLibraryCtrl',
        templateUrl: 'constructions/fen_library.html',
        windowClass: 'wide-modal',
        resolve: {
          params: function () {
            return {
              data: $scope.fenData,
              rowEntity: rowEntity,
              panel: $scope.fenPanels[index]
            };
          }
        }
      });

      modalInstance.result.then(function (selectedFen) {
        $scope.fenPanels[index].selected = selectedFen;
        $scope.fenPanels[index].fenGridOptions.data = [selectedFen];
      }, function () {
        // Modal canceled
      });
    };

    // save (constructions and fenestrations saved in same record
    $scope.submit = function () {
      console.log("submit");

      function success(response) {
        toaster.pop('success', 'Construction defaults successfully saved');
      }

      function failure(response) {
        console.log("failure", response);
        toaster.pop('error', 'An error occurred while saving', response.statusText);
      }

      var construction_defaults = {};
      $scope.panels.forEach(function (panel) {
        construction_defaults[panel.name] = panel.selected ? panel.selected.id : null;
      });
      $scope.fenPanels.forEach(function (panel) {
        construction_defaults[panel.name] = panel.selected ? panel.selected.id : null;
      });

      ConstructionDefaults.createUpdate({
        project_id: Shared.getProjectId()
      }, construction_defaults, success, failure);

    };

    // Remove Buttons
    $scope.removeConstruction = function (index) {
      $scope.panels[index].selected = null;
      $scope.panels[index].gridOptions.data = [];
    };

    $scope.removeFenestration = function (index) {
      $scope.fenPanels[index].selected = null;
      $scope.fenPanels[index].fenGridOptions.data = [];
    };
  }]);

cbecc.controller('ModalConstructionsLibraryCtrl', [
  '$scope', '$modalInstance', '$interval', 'uiGridConstants', 'Shared', 'params', function ($scope, $modalInstance, $interval, uiGridConstants, Shared, params) {
    $scope.data = params.data;
    $scope.title = params.title;
    $scope.layerData = [];
    $scope.selected = null;

    $scope.constructionsGridOptions = {
      columnDefs: [{
        name: 'name',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        minWidth: 400
      }, {
        name: 'type',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'framing_configuration',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        maxWidth: 218
      }, {
        name: 'framing_size',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        maxWidth: 159
      }, {
        name: 'cavity_insulation_r_value',
        secondLine: Shared.html('ft2 °F hr / Btu'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'continuous_insulation_r_value',
        secondLine: Shared.html('ft2 °F hr / Btu'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'continuous_insulation_material_name',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        minWidth: 300
      }],
      data: 'data',
      enableFiltering: true,
      enableRowHeaderSelection: false,
      enableRowSelection: true,
      multiSelect: false,
      onRegisterApi: function (gridApi) {
        $scope.gridApi = gridApi;
        gridApi.selection.on.rowSelectionChanged($scope, function (row) {
          if (row.isSelected) {
            $scope.selected = row.entity;
            $scope.layerData = row.entity.layers;
          } else {
            // No rows selected
            $scope.selected = null;
            $scope.layerData = [];
          }
        });
        if (typeof (params.rowEntity) !== 'undefined' && params.rowEntity) {
          $interval(function () {
            $scope.gridApi.selection.selectRow(params.rowEntity);
          }, 0, 1);
        }
      }
    };

    $scope.layersGridOptions = {
      columnDefs: [{
        name: 'name',
        displayName: 'Layer'
      }, {
        name: 'code_category'
      }],
      data: 'layerData',
      enableColumnMenus: false,
      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableSorting: false,
      enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER
    };

    $scope.ok = function () {
      $modalInstance.close($scope.selected);
    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }]);

cbecc.controller('ModalFenestrationLibraryCtrl', [
  '$scope', '$modalInstance', '$interval', 'uiGridConstants', 'Shared', 'params', function ($scope, $modalInstance, $interval, uiGridConstants, Shared, params) {
    $scope.data = params.data;
    $scope.title = params.panel.title;
    $scope.selected = null;

    if (params.panel.name == 'window') {
      $scope.type = 'VerticalFenestration';
    } else if (params.panel.name == 'skylight') {
      $scope.type = 'Skylight';
    }

    $scope.fenestrationGridOptions = {
      columnDefs: [{
        name: 'name',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        minWidth: 400
      }, {
        name: 'fenestration_type',
        enableFiltering: false,
        filter: {
          noTerm: true,
          term: $scope.type
        },
        visible: false
      }, {
        name: 'fenestration_framing',
        displayName: 'Frame Type',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'fenestration_panes',
        displayName: 'Panes',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'fenestration_product_type',
        displayName: 'Product Type',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'VerticalFenestration'
      }, {
        name: 'glazing_tint',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'VerticalFenestration'
      }, {
        name: 'u_factor',
        secondLine: Shared.html('Btu / (ft2 °F hr)'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'shgc',
        displayName: 'Solar Heat Gain Coefficient',
        secondLine: Shared.html('frac.'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'VerticalFenestration'
      }, {
        name: 'skylight_curb',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'Skylight'
      }],
      data: 'data',
      enableFiltering: true,
      enableRowHeaderSelection: false,
      enableRowSelection: true,
      multiSelect: false,
      onRegisterApi: function (gridApi) {
        $scope.gridApi = gridApi;
        gridApi.selection.on.rowSelectionChanged($scope, function (row) {
          if (row.isSelected) {
            $scope.selected = row.entity;
          } else {
            // No rows selected
            $scope.selected = null;
          }
        });
        if (typeof (params.rowEntity) !== 'undefined' && params.rowEntity) {
          $interval(function () {
            $scope.gridApi.selection.selectRow(params.rowEntity);
          }, 0, 1);
        }
      }
    };

    $scope.ok = function () {
      $modalInstance.close($scope.selected);
    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }]);<commit_msg>Updating constructions modals to match surface types to panels<commit_after>cbecc.controller('ConstructionsCtrl', [
  '$scope', '$location', '$modal', 'uiGridConstants', 'toaster', 'ConstructionDefaults', 'Shared', 'constData', 'fenData', 'defaults', function ($scope, $location, $modal, uiGridConstants, toaster, ConstructionDefaults, Shared, constData, fenData, defaults) {
    Shared.stopSpinner();

    // construction data
    $scope.constData = constData;
    $scope.fenData = fenData;

    // retrieve saved defaults (if any)
    $scope.defaults = defaults[0] || {};

    // retrieve each saved default record from ids
    function getSelected(the_data, the_id) {
      return _.find(the_data, {
        id: the_id
      });
    }

    //collapsible panels
    $scope.panels = [{
      title: 'Exterior Wall Construction',
      name: 'exterior_wall'
    }, {
      title: 'Interior Wall Construction',
      name: 'interior_wall'
    }, {
      title: 'Underground Wall Construction',
      name: 'underground_wall'
    }, {
      title: 'Roof Construction',
      name: 'roof'
    }, {
      title: 'Door Construction',
      name: 'door'
    }, {
      title: 'Interior Floor Construction',
      name: 'interior_floor'
    }, {
      title: 'Exterior Floor Construction',
      name: 'exterior_floor'
    }, {
      title: 'Underground Floor Construction',
      name: 'underground_floor'
    }];

    $scope.panels.forEach(function (panel) {
      panel.gridOptions = {
        columnDefs: [{
          name: 'name',
          displayName: 'Layer'
        }, {
          name: 'code_category'
        }],
        enableColumnMenus: false,
        enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
        enableSorting: false,
        enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER
      };

      // retrieve selected and layers
      var sel = getSelected($scope.constData, $scope.defaults[panel.name]);
      if (sel) {
        panel.selected = sel;
        panel.gridOptions.data = sel.layers;
        panel.open = true;
      } else {
        panel.open = false;
      }
    });

    $scope.fenPanels = [{
      title: 'Window Construction',
      name: 'window'
    }, {
      title: 'Skylight Construction',
      name: 'skylight'
    }];

    $scope.fenPanels.forEach(function (panel) {
      panel.fenGridOptions = {
        columnDefs: [{
          name: 'name'
        }, {
          name: 'fenestration_framing',
          displayName: 'Frame Type'
        }, {
          name: 'fenestration_panes',
          displayName: 'Panes'
        }, {
          name: 'fenestration_product_type',
          displayName: 'Product Type',
          visible: panel.name == 'window'
        }, {
          name: 'glazing_tint',
          visible: panel.name == 'window'
        }, {
          name: 'u_factor'
        }, {
          name: 'shgc',
          displayName: 'Solar Heat Gain Coefficient',
          visible: panel.name == 'window'
        }, {
          name: 'skylight_curb',
          visible: panel.name == 'skylight'
        }],
        enableColumnMenus: false,
        enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
        enableSorting: false,
        enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER
      };

      // retrieve selected
      var sel = getSelected($scope.fenData, $scope.defaults[panel.name]);
      if (sel) {
        panel.selected = sel;
        panel.fenGridOptions.data = [sel];
        panel.open = true;
      } else {
        panel.open = false;
      }
    });

    // Modal Settings
    $scope.openLibraryModal = function (index, rowEntity) {
      var modalInstance = $modal.open({
        backdrop: 'static',
        controller: 'ModalConstructionsLibraryCtrl',
        templateUrl: 'constructions/library.html',
        windowClass: 'wide-modal',
        resolve: {
          params: function () {
            return {
              data: $scope.constData,
              rowEntity: rowEntity,
              panel: $scope.panels[index]
            };
          }
        }
      });

      modalInstance.result.then(function (selectedConstruction) {
        $scope.panels[index].selected = selectedConstruction;
        $scope.panels[index].gridOptions.data = selectedConstruction.layers;
      }, function () {
        // Modal canceled
      });
    };

    // Modal Settings
    $scope.openFenLibraryModal = function (index, rowEntity) {
      var modalInstance = $modal.open({
        backdrop: 'static',
        controller: 'ModalFenestrationLibraryCtrl',
        templateUrl: 'constructions/fen_library.html',
        windowClass: 'wide-modal',
        resolve: {
          params: function () {
            return {
              data: $scope.fenData,
              rowEntity: rowEntity,
              panel: $scope.fenPanels[index]
            };
          }
        }
      });

      modalInstance.result.then(function (selectedFen) {
        $scope.fenPanels[index].selected = selectedFen;
        $scope.fenPanels[index].fenGridOptions.data = [selectedFen];
      }, function () {
        // Modal canceled
      });
    };

    // save (constructions and fenestrations saved in same record
    $scope.submit = function () {
      console.log("submit");

      function success(response) {
        toaster.pop('success', 'Construction defaults successfully saved');
      }

      function failure(response) {
        console.log("failure", response);
        toaster.pop('error', 'An error occurred while saving', response.statusText);
      }

      var construction_defaults = {};
      $scope.panels.forEach(function (panel) {
        construction_defaults[panel.name] = panel.selected ? panel.selected.id : null;
      });
      $scope.fenPanels.forEach(function (panel) {
        construction_defaults[panel.name] = panel.selected ? panel.selected.id : null;
      });

      ConstructionDefaults.createUpdate({
        project_id: Shared.getProjectId()
      }, construction_defaults, success, failure);

    };

    // Remove Buttons
    $scope.removeConstruction = function (index) {
      $scope.panels[index].selected = null;
      $scope.panels[index].gridOptions.data = [];
    };

    $scope.removeFenestration = function (index) {
      $scope.fenPanels[index].selected = null;
      $scope.fenPanels[index].fenGridOptions.data = [];
    };
  }]);

cbecc.controller('ModalConstructionsLibraryCtrl', [
  '$scope', '$modalInstance', '$interval', 'uiGridConstants', 'Shared', 'params', function ($scope, $modalInstance, $interval, uiGridConstants, Shared, params) {
    $scope.data = params.data;
    $scope.title = params.panel.title;
    $scope.layerData = [];
    $scope.selected = null;

    if (params.panel.name == 'exterior_wall') {
      $scope.type = 'ExteriorWall';
    } else if (params.panel.name == 'interior_wall') {
      $scope.type = 'InteriorWall';
    } else if (params.panel.name == 'underground_wall') {
      $scope.type = 'UndergroundWall';
    } else if (params.panel.name == 'roof') {
      $scope.type = 'ExteriorRoof';
    } else if (params.panel.name == 'door') {
      $scope.type = 'Door';
    } else if (params.panel.name == 'interior_floor') {
      $scope.type = 'InteriorFloor';
    } else if (params.panel.name == 'exterior_floor') {
      $scope.type = 'ExteriorFloor';
    } else if (params.panel.name == 'underground_floor') {
      $scope.type = 'UndergroundFloor';
    }

    $scope.constructionsGridOptions = {
      columnDefs: [{
        name: 'name',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        minWidth: 400
      }, {
        name: 'compatible_surface_type',
        enableFiltering: false,
        filter: {
          condition: uiGridConstants.filter.EXACT,
          noTerm: true,
          term: $scope.type
        },
        visible: false
      }, {
        name: 'type',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'framing_configuration',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        maxWidth: 218
      }, {
        name: 'framing_size',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        maxWidth: 159
      }, {
        name: 'cavity_insulation_r_value',
        secondLine: Shared.html('ft2 °F hr / Btu'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'continuous_insulation_r_value',
        secondLine: Shared.html('ft2 °F hr / Btu'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'continuous_insulation_material_name',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        minWidth: 300
      }],
      data: 'data',
      enableFiltering: true,
      enableRowHeaderSelection: false,
      enableRowSelection: true,
      multiSelect: false,
      onRegisterApi: function (gridApi) {
        $scope.gridApi = gridApi;
        gridApi.selection.on.rowSelectionChanged($scope, function (row) {
          if (row.isSelected) {
            $scope.selected = row.entity;
            $scope.layerData = row.entity.layers;
          } else {
            // No rows selected
            $scope.selected = null;
            $scope.layerData = [];
          }
        });
        if (typeof (params.rowEntity) !== 'undefined' && params.rowEntity) {
          $interval(function () {
            $scope.gridApi.selection.selectRow(params.rowEntity);
          }, 0, 1);
        }
      }
    };

    $scope.layersGridOptions = {
      columnDefs: [{
        name: 'name',
        displayName: 'Layer'
      }, {
        name: 'code_category'
      }],
      data: 'layerData',
      enableColumnMenus: false,
      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableSorting: false,
      enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER
    };

    $scope.ok = function () {
      $modalInstance.close($scope.selected);
    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }]);

cbecc.controller('ModalFenestrationLibraryCtrl', [
  '$scope', '$modalInstance', '$interval', 'uiGridConstants', 'Shared', 'params', function ($scope, $modalInstance, $interval, uiGridConstants, Shared, params) {
    $scope.data = params.data;
    $scope.title = params.panel.title;
    $scope.selected = null;

    if (params.panel.name == 'window') {
      $scope.type = 'VerticalFenestration';
    } else if (params.panel.name == 'skylight') {
      $scope.type = 'Skylight';
    }

    $scope.fenestrationGridOptions = {
      columnDefs: [{
        name: 'name',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        minWidth: 400
      }, {
        name: 'fenestration_type',
        enableFiltering: false,
        filter: {
          condition: uiGridConstants.filter.EXACT,
          noTerm: true,
          term: $scope.type
        },
        visible: false
      }, {
        name: 'fenestration_framing',
        displayName: 'Frame Type',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'fenestration_panes',
        displayName: 'Panes',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'fenestration_product_type',
        displayName: 'Product Type',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'VerticalFenestration'
      }, {
        name: 'glazing_tint',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'VerticalFenestration'
      }, {
        name: 'u_factor',
        secondLine: Shared.html('Btu / (ft2 °F hr)'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell'
      }, {
        name: 'shgc',
        displayName: 'Solar Heat Gain Coefficient',
        secondLine: Shared.html('frac.'),
        enableHiding: false,
        filters: Shared.numberFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'VerticalFenestration'
      }, {
        name: 'skylight_curb',
        enableHiding: false,
        filter: Shared.textFilter(),
        headerCellTemplate: 'ui-grid/customHeaderCell',
        visible: $scope.type == 'Skylight'
      }],
      data: 'data',
      enableFiltering: true,
      enableRowHeaderSelection: false,
      enableRowSelection: true,
      multiSelect: false,
      onRegisterApi: function (gridApi) {
        $scope.gridApi = gridApi;
        gridApi.selection.on.rowSelectionChanged($scope, function (row) {
          if (row.isSelected) {
            $scope.selected = row.entity;
          } else {
            // No rows selected
            $scope.selected = null;
          }
        });
        if (typeof (params.rowEntity) !== 'undefined' && params.rowEntity) {
          $interval(function () {
            $scope.gridApi.selection.selectRow(params.rowEntity);
          }, 0, 1);
        }
      }
    };

    $scope.ok = function () {
      $modalInstance.close($scope.selected);
    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }]);<|endoftext|>


<commit_before>const cheerio = require("cheerio");
const fetch = require("node-fetch");
//import http and https, needed for setting the agents for node-fetch
const http = require('http');
const https = require('https');

function extractHostname(url) {
  var hostname;
  //find & remove protocol (http, ftp, etc.) and get hostname

  if (url.indexOf("//") > -1) {
    hostname = url.split("/")[2];
  } else {
    hostname = url.split("/")[0];
  }

  //find & remove port number
  hostname = hostname.split(":")[0];
  //find & remove "?"
  hostname = hostname.split("?")[0];

  return hostname;
}

// To address those who want the "root domain," use this function:
function extractRootDomain(url) {
  var domain = extractHostname(url),
    splitArr = domain.split("."),
    arrLen = splitArr.length;

  //extracting the root domain here
  //if there is a subdomain
  if (arrLen > 2) {
    domain = splitArr[arrLen - 2] + "." + splitArr[arrLen - 1];
    //check to see if it's using a Country Code Top Level Domain (ccTLD) (i.e. ".me.uk")
    if (splitArr[arrLen - 2].length == 2 && splitArr[arrLen - 1].length == 2) {
      //this is using a ccTLD
      domain = splitArr[arrLen - 3] + "." + domain;
    }
  }
  return domain;
}

//function to return overlap
function findOverlap(a, b) {
  if (b.length === 0) {
    return "";
  }
  if (a.endsWith(b)) {
    return b;
  }
  if (a.indexOf(b) >= 0) {
    return b;
  }
  return findOverlap(a, b.substring(0, b.length - 1));
}

//function to validate if url is valid
function isURL(str) {
  var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
  if (!regex.test(str)) {
    return false;
  } else {
    return true;
  }
}

async function getUrl(url) {
  try {

    //set httpAgents
    const httpAgent = new http.Agent({
      keepAlive: true
    });
    const httpsAgent = new https.Agent({
      keepAlive: true
    });

    const options = {
      agent: function(_parsedURL) {
        if (_parsedURL.protocol == 'http:') {
          return httpAgent;
        } else {
          return httpsAgent;
        }
      },
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36",
        Accept: "text/html,application/xhtml+xml"
      }
    };

    //fetch url by using proper user agent
    const response = await fetch(url, options);

    if (response.ok) {

      //set body text, needed for cheerio for trying to retrieve rss link
      const body = await response.text();
      //return response url, in case the url has been changed
      const responseUrl = response.url;

      //validate body
      if (body) {
        //load body into cheerio
        //dismiss "cheerio.load() expects a string" by converting to string
        const $ = cheerio.load(String(body));

        //validate if application/rss+xml attribute is present in header
        if ($("head").find('link[type="application/rss+xml"]').length > 0) {
          autoDiscoverUrl = $('head link[type="application/rss+xml"]').attr(
            "href"
          );

          //validate if the url is valid
          if (isURL(autoDiscoverUrl)) {
            url = autoDiscoverUrl;
          } else {
            //find overlap and create new url
            var overlap = findOverlap(responseUrl, autoDiscoverUrl);
            url = responseUrl.replace(overlap, "") + autoDiscoverUrl;
          }
        }

        //validate if application/atom+xml attribute is present in header
        if ($("head").find('link[type="application/atom+xml"]').length > 0) {
          autoDiscoverUrl = $('head link[type="application/atom+xml"]').attr(
            "href"
          );

          //validate if the url is valid
          if (isURL(autoDiscoverUrl)) {
            url = autoDiscoverUrl;
          } else {
            //find overlap and create new url
            var overlap = findOverlap(responseUrl, autoDiscoverUrl);
            url = responseUrl.replace(overlap, "") + autoDiscoverUrl;
          }
        }
      }
      //return final result set
      return url;
    } else {
      console.log("HTTP Error Response: " + response.status + " (" + response.statusText + ") - " + url);
    }
  } catch (err) {
    console.log("getUrl Error: " + err + " - " + url);
  }
}

exports.discover = async function(url) {
  try {
    const autodiscover = await getUrl(url);
    return autodiscover;
  } catch (err) {
    console.log(err);
  }
};
<commit_msg>add globalAgent.maxSockets to avoid socket errors<commit_after>const cheerio = require("cheerio");
const fetch = require("node-fetch");
//import http and https, needed for setting the agents for node-fetch
const http = require('http');
const https = require('https');
http.globalAgent.maxSockets = 1000000;
https.globalAgent.maxSockets = 1000000;

function extractHostname(url) {
  var hostname;
  //find & remove protocol (http, ftp, etc.) and get hostname

  if (url.indexOf("//") > -1) {
    hostname = url.split("/")[2];
  } else {
    hostname = url.split("/")[0];
  }

  //find & remove port number
  hostname = hostname.split(":")[0];
  //find & remove "?"
  hostname = hostname.split("?")[0];

  return hostname;
}

// To address those who want the "root domain," use this function:
function extractRootDomain(url) {
  var domain = extractHostname(url),
    splitArr = domain.split("."),
    arrLen = splitArr.length;

  //extracting the root domain here
  //if there is a subdomain
  if (arrLen > 2) {
    domain = splitArr[arrLen - 2] + "." + splitArr[arrLen - 1];
    //check to see if it's using a Country Code Top Level Domain (ccTLD) (i.e. ".me.uk")
    if (splitArr[arrLen - 2].length == 2 && splitArr[arrLen - 1].length == 2) {
      //this is using a ccTLD
      domain = splitArr[arrLen - 3] + "." + domain;
    }
  }
  return domain;
}

//function to return overlap
function findOverlap(a, b) {
  if (b.length === 0) {
    return "";
  }
  if (a.endsWith(b)) {
    return b;
  }
  if (a.indexOf(b) >= 0) {
    return b;
  }
  return findOverlap(a, b.substring(0, b.length - 1));
}

//function to validate if url is valid
function isURL(str) {
  var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
  if (!regex.test(str)) {
    return false;
  } else {
    return true;
  }
}

async function getUrl(url) {
  try {

    //set httpAgents
    const httpAgent = new http.Agent({
      keepAlive: true
    });
    const httpsAgent = new https.Agent({
      keepAlive: true
    });

    const options = {
      agent: function(_parsedURL) {
        if (_parsedURL.protocol == 'http:') {
          return httpAgent;
        } else {
          return httpsAgent;
        }
      },
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36",
        Accept: "text/html,application/xhtml+xml"
      }
    };

    //fetch url by using proper user agent
    const response = await fetch(url, options);

    if (response.ok) {

      //set body text, needed for cheerio for trying to retrieve rss link
      const body = await response.text();
      //return response url, in case the url has been changed
      const responseUrl = response.url;

      //validate body
      if (body) {
        //load body into cheerio
        //dismiss "cheerio.load() expects a string" by converting to string
        const $ = cheerio.load(String(body));

        //validate if application/rss+xml attribute is present in header
        if ($("head").find('link[type="application/rss+xml"]').length > 0) {
          autoDiscoverUrl = $('head link[type="application/rss+xml"]').attr(
            "href"
          );

          //validate if the url is valid
          if (isURL(autoDiscoverUrl)) {
            url = autoDiscoverUrl;
          } else {
            //find overlap and create new url
            var overlap = findOverlap(responseUrl, autoDiscoverUrl);
            url = responseUrl.replace(overlap, "") + autoDiscoverUrl;
          }
        }

        //validate if application/atom+xml attribute is present in header
        if ($("head").find('link[type="application/atom+xml"]').length > 0) {
          autoDiscoverUrl = $('head link[type="application/atom+xml"]').attr(
            "href"
          );

          //validate if the url is valid
          //sometimes the RSS url in the header points to a new or different URL than the processed URL itself
          if (isURL(autoDiscoverUrl)) {
            url = autoDiscoverUrl;
          } else {
            //find overlap and create new url
            var overlap = findOverlap(responseUrl, autoDiscoverUrl);
            url = responseUrl.replace(overlap, "") + autoDiscoverUrl;
          }
        }
      }
      //return final result set
      return url;
    } else {
      console.log("HTTP Error Response: " + response.status + " (" + response.statusText + ") - " + url);
    }
  } catch (err) {
    console.log("getUrl Error: " + err + " - " + url);
  }
}

exports.discover = async function(url) {
  try {
    const autodiscover = await getUrl(url);
    return autodiscover;
  } catch (err) {
    console.log(err);
  }
};
<|endoftext|>


<commit_before>const sass = require('node-sass');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const chokidar = require('chokidar');
const scaffold = require('./scaffold');
const { promisify } = require('util');
const log = require('debug')('flint:scss');
const mongoose = require('mongoose');

const writeFileAsync = promisify(fs.writeFile);

function sassAsync(opt) {
  return new Promise((resolve, reject) => {
    sass.render(opt, (err, res) => {
      /* istanbul ignore if */
      if (err) reject(err);
      resolve(res);
    });
  });
}

function generateHash(length = 16) {
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let retVal = '';

  for (let i = 0, n = charset.length; i < length; ++i) {
    retVal += charset.charAt(Math.floor(Math.random() * n));
  }
  return retVal;
}

async function handleCacheBusting() {
  const filename = global.FLINT.scssEntryPoint.replace('.scss', '.css');
  if (!global.FLINT.enableCacheBusting) return filename;

  const Site = mongoose.model('Site');

  const cssHash = generateHash();
  global.FLINT.cssHash = cssHash;
  const site = await Site.findOne().exec();
  const updatedSite = await Site.findByIdAndUpdate(site._id, { cssHash }, { new: true }).exec();

  /* istanbul ignore if */
  if (!updatedSite) throw new Error('Could not save the site config to the database.');

  return filename.replace('.css', `-${cssHash}.css`);
}

/**
 * Actually compiles the SCSS
 * @param {object} opts - Compile options
 */
async function compile() {
  /* istanbul ignore next */
  const outputStyle = process.env.NODE_ENV === 'production' ? 'compressed' : 'nested';

  const opts = {
    file: path.join(global.FLINT.scssPath, global.FLINT.scssEntryPoint),
    includePaths: global.FLINT.scssIncludePaths,
    outputStyle,
  };

  try {
    const scss = await sassAsync(opts);
    const filename = await handleCacheBusting();
    const pathToFile = path.join(await scaffold(global.FLINT.publicPath), filename);

    await writeFileAsync(pathToFile, scss.css);
    return `${chalk.grey('[SCSS]')} Your SCSS has been compiled to ${pathToFile}`;
  } catch (e) /* istanbul ignore next */ {
    log(`  ${chalk.grey('Message:')} ${chalk.red(e.message)}`);
    log(`  ${chalk.grey('Line:')} ${chalk.red(e.line)}`);
    log(`  ${chalk.grey('File:')} ${chalk.red(e.file)}`);

    return `${chalk.red('[SCSS]')} There was an error compiling your SCSS.`;
  }
}

/* istanbul ignore next */
function recompile() {
  // eslint-disable-next-line no-console
  log(chalk.cyan('Recompiling SASS...'));
  return compile();
}

/* istanbul ignore next */
function watch(watcher) {
  watcher.on('add', async () => {
    const compiled = await recompile();
    log(compiled); // eslint-disable-line no-console
  });
  watcher.on('change', async () => {
    const compiled = await recompile();
    log(compiled); // eslint-disable-line no-console
  });
}

/**
 * Compiles SASS using the scssEntryPoint config
 */
async function compileSass() {
  if (global.FLINT.scssEntryPoint) {
    /* istanbul ignore if */
    if (global.FLINT.debugMode) {
      const watcher = chokidar.watch(global.FLINT.scssPath, {
        persistent: true,
        ignoreInitial: true,
      });

      watch(watcher);
    }

    return compile();
  }

  return chalk.grey('SCSS compiling has been disabled in the site configuration.');
}

module.exports = compileSass;
<commit_msg>Delete old file if it exists<commit_after>const sass = require('node-sass');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const chokidar = require('chokidar');
const scaffold = require('./scaffold');
const { promisify } = require('util');
const log = require('debug')('flint:scss');
const mongoose = require('mongoose');

const writeFileAsync = promisify(fs.writeFile);
const unlink = promisify(fs.unlink);

function sassAsync(opt) {
  return new Promise((resolve, reject) => {
    sass.render(opt, (err, res) => {
      /* istanbul ignore if */
      if (err) reject(err);
      resolve(res);
    });
  });
}

function generateHash(length = 16) {
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let retVal = '';

  for (let i = 0, n = charset.length; i < length; ++i) {
    retVal += charset.charAt(Math.floor(Math.random() * n));
  }
  return retVal;
}

const appendHash = (str, hash) => str.replace('.css', `-${hash}.css`);

/**
 * @typedef {Object} CacheBusted
 * @property {string} file - File name ending in .css
 * @property {string} [oldFile] - The old file, if cache busting is enabled.
 * @property {string} [newHash] - The new hash, if one was generated.
 *
 * Generates a hash and adds the hash to the db's site document.
 * @param {string} filename - File name, sans extension.
 * @returns {CacheBusted}
 */
async function handleCacheBusting(filename) {
  const file = `${filename}.css`;
  if (!global.FLINT.enableCacheBusting) return { file };

  const Site = mongoose.model('Site');
  const site = await Site.findOne().exec();
  const cssHash = generateHash();
  global.FLINT.cssHash = cssHash;
  const updatedSite = await Site.findByIdAndUpdate(site._id, { cssHash }, { new: true }).exec();

  /* istanbul ignore if */
  if (!updatedSite) throw new Error('Could not save the site config to the database.');
  return {
    file: appendHash(file, cssHash),
    oldFile: appendHash(file, site.cssHash),
    newHash: cssHash,
  };
}

/**
 * Actually compiles the SCSS
 * @returns {string}
 */
async function compile() {
  /* istanbul ignore next */
  const outputStyle = process.env.NODE_ENV === 'production' ? 'compressed' : 'nested';

  const opts = {
    file: path.join(global.FLINT.scssPath, global.FLINT.scssEntryPoint),
    includePaths: global.FLINT.scssIncludePaths,
    outputStyle,
  };

  const fileSplit = global.FLINT.scssEntryPoint.split('.');
  const filename = fileSplit.slice(0, fileSplit.length - 1).join('.');

  try {
    const scss = await sassAsync(opts);
    const { file, oldFile } = await handleCacheBusting(filename);
    const pathToFile = path.join(await scaffold(global.FLINT.publicPath), file);

    await writeFileAsync(pathToFile, scss.css);

    // Delete the old file
    if (global.FLINT.enableCacheBusting && oldFile) {
      const pathToOldFile = path.join(global.FLINT.publicPath, oldFile);
      const exists = fs.existsSync(pathToOldFile);
      if (exists) {
        log('Deleting old bundle.');
        await unlink(pathToOldFile);
      }
    }

    return `${chalk.grey('[SCSS]')} Your SCSS has been compiled to ${pathToFile}`;
  } catch (e) /* istanbul ignore next */ {
    log(`  ${chalk.grey('Message:')} ${chalk.red(e.message)}`);
    log(`  ${chalk.grey('Line:')} ${chalk.red(e.line)}`);
    log(`  ${chalk.grey('File:')} ${chalk.red(e.file)}`);

    return `${chalk.red('[SCSS]')} There was an error compiling your SCSS.`;
  }
}

/* istanbul ignore next */
function recompile() {
  // eslint-disable-next-line no-console
  log(chalk.cyan('Recompiling SASS...'));
  return compile();
}

/* istanbul ignore next */
function watch(watcher) {
  watcher.on('add', async () => {
    const compiled = await recompile();
    log(compiled); // eslint-disable-line no-console
  });
  watcher.on('change', async () => {
    const compiled = await recompile();
    log(compiled); // eslint-disable-line no-console
  });
}

/**
 * Compiles SASS using the scssEntryPoint config
 */
async function compileSass() {
  if (global.FLINT.scssEntryPoint) {
    /* istanbul ignore if */
    if (global.FLINT.debugMode) {
      const watcher = chokidar.watch(global.FLINT.scssPath, {
        persistent: true,
        ignoreInitial: true,
      });

      watch(watcher);
    }

    return compile();
  }

  return chalk.grey('SCSS compiling has been disabled in the site configuration.');
}

module.exports = compileSass;
<|endoftext|>


<commit_before>const BankAccountDetails = require('../../../../services/domain/bank-account-details')
const insertBankAccountDetailsForClaim = require('../../../../services/data/insert-bank-account-details-for-claim')
const submitFirstTimeClaim = require('../../../../services/data/submit-first-time-claim')
const ValidationError = require('../../../../services/errors/validation-error')
const UrlPathValidator = require('../../../../services/validators/url-path-validator')

module.exports = function (router) {
  router.get('/first-time-claim/eligibility/:reference/claim/:claimId/bank-account-details', function (req, res) {
    UrlPathValidator(req.params)
    return res.render('first-time/eligibility/claim/bank-account-details', {
      reference: req.params.reference,
      claimId: req.params.claimId
    })
  })

  router.post('/first-time-claim/eligibility/:reference/claim/:claimId/bank-account-details', function (req, res) {
    UrlPathValidator(req.params)
    try {
      var bankAccountDetails = new BankAccountDetails(req.body.AccountNumber, req.body.SortCode)
      insertBankAccountDetailsForClaim(req.params.claimId, bankAccountDetails)
        .then(function () {
          return submitFirstTimeClaim(req.params.reference, req.params.claimId)
            .then(function () {
              return res.redirect(`/application-submitted/${req.params.reference}`)
            })
        })
    } catch (error) {
      if (error instanceof ValidationError) {
        return res.status(400).render('first-time/eligibility/claim/bank-account-details', {
          bankDetails: req.body,
          errors: error.validationErrors
        })
      } else {
        throw error
      }
    }
  })
}
<commit_msg>chore - fix bank account details render (#84)<commit_after>const BankAccountDetails = require('../../../../services/domain/bank-account-details')
const insertBankAccountDetailsForClaim = require('../../../../services/data/insert-bank-account-details-for-claim')
const submitFirstTimeClaim = require('../../../../services/data/submit-first-time-claim')
const ValidationError = require('../../../../services/errors/validation-error')
const UrlPathValidator = require('../../../../services/validators/url-path-validator')

module.exports = function (router) {
  router.get('/first-time-claim/eligibility/:reference/claim/:claimId/bank-account-details', function (req, res) {
    UrlPathValidator(req.params)
    return res.render('first-time/eligibility/claim/bank-account-details', {
      reference: req.params.reference,
      claimId: req.params.claimId
    })
  })

  router.post('/first-time-claim/eligibility/:reference/claim/:claimId/bank-account-details', function (req, res) {
    UrlPathValidator(req.params)
    try {
      var bankAccountDetails = new BankAccountDetails(req.body.AccountNumber, req.body.SortCode)
      insertBankAccountDetailsForClaim(req.params.claimId, bankAccountDetails)
        .then(function () {
          return submitFirstTimeClaim(req.params.reference, req.params.claimId)
            .then(function () {
              return res.redirect(`/application-submitted/${req.params.reference}`)
            })
        })
    } catch (error) {
      if (error instanceof ValidationError) {
        return res.status(400).render('first-time/eligibility/claim/bank-account-details', {
          bankDetails: req.body,
          errors: error.validationErrors,
          reference: req.params.reference,
          claimId: req.params.claimId
        })
      } else {
        throw error
      }
    }
  })
}
<|endoftext|>


<commit_before>'use strict';
const moment = require('moment');
const url = require('url');
const Case = require('case');
const resultsPerPage = require('../server/config').searchResultsPerPage;

const acronyms = [
'ARD',
'CJA',
'DTO',
'EPP',
'GOAD',
'HDC',
'IPP',
'YO',
'YP'
];

module.exports = {

    pad: function(n) {
        return (n < 10) ? ('0' + parseInt(n)) : n;
    },

    padPrisonNumber: function(v) {
        let spaces = '';
        const lenPrisonNumber = 8;

        for(let i=0; i < lenPrisonNumber-v.length; i++) {
            spaces += ' ';
        }

        return (v.length < lenPrisonNumber) ? (spaces + v) : v;
    },

    getAgeFromDOB: function(dateInGDSFormat) {
        let dob = moment(dateInGDSFormat, 'DD/MM/YYYY');
        return moment().diff(dob, 'years', false);
    },

    getDateRange: function(age) {
        if (age.indexOf('-') === -1) {
            let startDate = this.getCurrentTime()
                            .subtract(age, 'years')
                            .subtract(1, 'years')
                            .add(1, 'days')
                            .format('YYYYMMDD');

            let endDate = this.getCurrentTime().subtract(age, 'years').format('YYYYMMDD');
            return [startDate, endDate];
        }

        let ages = age.split('-');
        let startDate = this.getCurrentTime()
                        .subtract(ages[1], 'years')
                        .subtract(1, 'years')
                        .add(1, 'days')
                        .format('YYYYMMDD');

        let endDate = this.getCurrentTime().subtract(ages[0], 'years').format('YYYYMMDD');
        return [startDate, endDate];
    },

    pagination: function(rowCount, currPage) {
        currPage = (currPage) ? currPage : 1;

        let totalPages = Math.ceil(rowCount / resultsPerPage);
        let showPrev = (currPage - 1) == 0 ? false : true;
        let showNext = currPage == totalPages ? false : true;

        return {totalPages: totalPages,
                currPage: currPage,
                showPrev: showPrev,
                showNext: showNext};
    },

    getCurrentTime: function() {
        return moment();
    },

    getFormattedDateFromString: function(dateAsIISDateFormat) {
        return dateAsIISDateFormat == '18991231' ? null : moment(dateAsIISDateFormat, 'YYYYMMDD').format('DD/MM/YYYY');
    },

    getPathFromURL: function(v) {
        return url.parse(v).path;
    },

    acronymsToUpperCase: function(text) {
        return acronyms.map(function(acronym) {
            let pattern = '\\b('+acronym+')\\b';
            let regex = new RegExp(pattern, 'gi');
            text = text.replace(regex, Case.upper(acronym));
            return text;
        }).pop();
    }
};
<commit_msg>Add alias ARP<commit_after>'use strict';
const moment = require('moment');
const url = require('url');
const Case = require('case');
const resultsPerPage = require('../server/config').searchResultsPerPage;

const acronyms = [
'ARD',
'ARP',
'CJA',
'DTO',
'EPP',
'GOAD',
'HDC',
'IPP',
'YO',
'YP'
];

module.exports = {

    pad: function(n) {
        return (n < 10) ? ('0' + parseInt(n)) : n;
    },

    padPrisonNumber: function(v) {
        let spaces = '';
        const lenPrisonNumber = 8;

        for(let i=0; i < lenPrisonNumber-v.length; i++) {
            spaces += ' ';
        }

        return (v.length < lenPrisonNumber) ? (spaces + v) : v;
    },

    getAgeFromDOB: function(dateInGDSFormat) {
        let dob = moment(dateInGDSFormat, 'DD/MM/YYYY');
        return moment().diff(dob, 'years', false);
    },

    getDateRange: function(age) {
        if (age.indexOf('-') === -1) {
            let startDate = this.getCurrentTime()
                            .subtract(age, 'years')
                            .subtract(1, 'years')
                            .add(1, 'days')
                            .format('YYYYMMDD');

            let endDate = this.getCurrentTime().subtract(age, 'years').format('YYYYMMDD');
            return [startDate, endDate];
        }

        let ages = age.split('-');
        let startDate = this.getCurrentTime()
                        .subtract(ages[1], 'years')
                        .subtract(1, 'years')
                        .add(1, 'days')
                        .format('YYYYMMDD');

        let endDate = this.getCurrentTime().subtract(ages[0], 'years').format('YYYYMMDD');
        return [startDate, endDate];
    },

    pagination: function(rowCount, currPage) {
        currPage = (currPage) ? currPage : 1;

        let totalPages = Math.ceil(rowCount / resultsPerPage);
        let showPrev = (currPage - 1) == 0 ? false : true;
        let showNext = currPage == totalPages ? false : true;

        return {totalPages: totalPages,
                currPage: currPage,
                showPrev: showPrev,
                showNext: showNext};
    },

    getCurrentTime: function() {
        return moment();
    },

    getFormattedDateFromString: function(dateAsIISDateFormat) {
        return dateAsIISDateFormat == '18991231' ? null : moment(dateAsIISDateFormat, 'YYYYMMDD').format('DD/MM/YYYY');
    },

    getPathFromURL: function(v) {
        return url.parse(v).path;
    },

    acronymsToUpperCase: function(text) {
        return acronyms.map(function(acronym) {
            let pattern = '\\b('+acronym+')\\b';
            let regex = new RegExp(pattern, 'gi');
            text = text.replace(regex, Case.upper(acronym));
            return text;
        }).pop();
    }
};
<|endoftext|>


<commit_before>define([
  'angular',
  'lodash',
  'jquery',
],
function (angular, _, $) {
  'use strict';

  angular
    .module('grafana.directives')
    .directive('influxdbFuncEditor', function($compile) {

      var funcSpanTemplate = '{{field.func}}(';

      var paramTemplate = '<input type="text" style="display:none"' +
                          ' class="input-mini tight-form-func-param"></input>';

      var functionList = [
        'count', 'mean', 'sum', 'min', 'max', 'mode', 'distinct', 'median',
        'derivative', 'non_negative_derivative', 'stddev', 'first', 'last', 'difference'
      ];

      var functionMenu = _.map(functionList, function(func) {
        return { text: func, click: "changeFunction('" + func + "');" };
      });

      return {
        restrict: 'A',
        scope: {
          field: "=",
          getFields: "&",
          onChange: "&",
        },
        link: function postLink($scope, elem) {
          var $funcLink = $(funcSpanTemplate);

          $scope.functionMenu = functionMenu;

          $scope.changeFunction = function(func) {
            $scope.field.func = func;
            $scope.onChange();
          };

          function clickFuncParam() {
            /*jshint validthis:true */

            var $link = $(this);
            var $input = $link.next();

            $input.val($scope.field.name);
            $input.css('width', ($link.width() + 16) + 'px');

            $link.hide();
            $input.show();
            $input.focus();
            $input.select();

            var typeahead = $input.data('typeahead');
            if (typeahead) {
              $input.val('');
              typeahead.lookup();
            }
          }

          function inputBlur() {
            /*jshint validthis:true */

            var $input = $(this);
            var $link = $input.prev();

            if ($input.val() !== '') {
              $link.text($input.val());

              $scope.field.name = $input.val();
              $scope.$apply($scope.onChange());
            }

            $input.hide();
            $link.show();
          }

          function inputKeyPress(e) {
            /*jshint validthis:true */

            if(e.which === 13) {
              inputBlur.call(this);
            }
          }

          function inputKeyDown() {
            /*jshint validthis:true */
            this.style.width = (3 + this.value.length) * 8 + 'px';
          }

          function addTypeahead($input) {
            $input.attr('data-provide', 'typeahead');

            $input.typeahead({
              source: function (query, callback) {
                return $scope.getFields().then(function(results) {
                  callback(results);
                });
              },
              minLength: 0,
              items: 20,
              updater: function (value) {
                setTimeout(function() {
                  inputBlur.call($input[0]);
                }, 0);
                return value;
              }
            });

            var typeahead = $input.data('typeahead');
            typeahead.lookup = function () {
              var items;
              this.query = this.$element.val() || '';
              items = this.source(this.query, $.proxy(this.process, this));
              return items ? this.process(items) : items;
            };
          }

          function addElementsAndCompile() {
            $funcLink.appendTo(elem);

            var $paramLink = $('' + $scope.field.name + '');
            var $input = $(paramTemplate);

            $paramLink.appendTo(elem);
            $input.appendTo(elem);

            $input.blur(inputBlur);
            $input.keyup(inputKeyDown);
            $input.keypress(inputKeyPress);
            $paramLink.click(clickFuncParam);

            addTypeahead($input);

            $(')').appendTo(elem);

            $compile(elem.contents())($scope);
          }

          addElementsAndCompile();

        }
      };

    });

});
<commit_msg>fix(influxdb 0.9): removed  function from function dropdown as this function does not exist in InfluxDB 0.9<commit_after>define([
  'angular',
  'lodash',
  'jquery',
],
function (angular, _, $) {
  'use strict';

  angular
    .module('grafana.directives')
    .directive('influxdbFuncEditor', function($compile) {

      var funcSpanTemplate = '{{field.func}}(';

      var paramTemplate = '<input type="text" style="display:none"' +
                          ' class="input-mini tight-form-func-param"></input>';

      var functionList = [
        'count', 'mean', 'sum', 'min', 'max', 'mode', 'distinct', 'median',
        'derivative', 'non_negative_derivative', 'stddev', 'first', 'last'
      ];

      var functionMenu = _.map(functionList, function(func) {
        return { text: func, click: "changeFunction('" + func + "');" };
      });

      return {
        restrict: 'A',
        scope: {
          field: "=",
          getFields: "&",
          onChange: "&",
        },
        link: function postLink($scope, elem) {
          var $funcLink = $(funcSpanTemplate);

          $scope.functionMenu = functionMenu;

          $scope.changeFunction = function(func) {
            $scope.field.func = func;
            $scope.onChange();
          };

          function clickFuncParam() {
            /*jshint validthis:true */

            var $link = $(this);
            var $input = $link.next();

            $input.val($scope.field.name);
            $input.css('width', ($link.width() + 16) + 'px');

            $link.hide();
            $input.show();
            $input.focus();
            $input.select();

            var typeahead = $input.data('typeahead');
            if (typeahead) {
              $input.val('');
              typeahead.lookup();
            }
          }

          function inputBlur() {
            /*jshint validthis:true */

            var $input = $(this);
            var $link = $input.prev();

            if ($input.val() !== '') {
              $link.text($input.val());

              $scope.field.name = $input.val();
              $scope.$apply($scope.onChange());
            }

            $input.hide();
            $link.show();
          }

          function inputKeyPress(e) {
            /*jshint validthis:true */

            if(e.which === 13) {
              inputBlur.call(this);
            }
          }

          function inputKeyDown() {
            /*jshint validthis:true */
            this.style.width = (3 + this.value.length) * 8 + 'px';
          }

          function addTypeahead($input) {
            $input.attr('data-provide', 'typeahead');

            $input.typeahead({
              source: function (query, callback) {
                return $scope.getFields().then(function(results) {
                  callback(results);
                });
              },
              minLength: 0,
              items: 20,
              updater: function (value) {
                setTimeout(function() {
                  inputBlur.call($input[0]);
                }, 0);
                return value;
              }
            });

            var typeahead = $input.data('typeahead');
            typeahead.lookup = function () {
              var items;
              this.query = this.$element.val() || '';
              items = this.source(this.query, $.proxy(this.process, this));
              return items ? this.process(items) : items;
            };
          }

          function addElementsAndCompile() {
            $funcLink.appendTo(elem);

            var $paramLink = $('' + $scope.field.name + '');
            var $input = $(paramTemplate);

            $paramLink.appendTo(elem);
            $input.appendTo(elem);

            $input.blur(inputBlur);
            $input.keyup(inputKeyDown);
            $input.keypress(inputKeyPress);
            $paramLink.click(clickFuncParam);

            addTypeahead($input);

            $(')').appendTo(elem);

            $compile(elem.contents())($scope);
          }

          addElementsAndCompile();

        }
      };

    });

});
<|endoftext|>


<commit_before>var assign = require('object-assign');

var smooth = require('./smooth');

var easing = smooth.defaultEasing;

var cancelEvents = require('./cancel-events');

var events = require('./scroll-events');

/*
 * Function helper
 */
var functionWrapper = function(value) {
  return typeof value === 'function' ? value : function() { return value; };
};

/*
 * Sets the cancel trigger
 */

cancelEvents.register(function() {
  __cancel = true;
});

/*
 * Wraps window properties to allow server side rendering
 */
var currentWindowProperties = function() {
  if (typeof window !== 'undefined') {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame;
  }
};

/*
 * Helper function to never extend 60fps on the webpage.
 */
var requestAnimationFrameHelper = (function () {
  return  currentWindowProperties() ||
          function (callback, element, delay) {
              window.setTimeout(callback, delay || (1000/60), new Date().getTime());
          };
})();

var __currentPositionY  = 0;
var __startPositionY    = 0;
var __targetPositionY   = 0;
var __progress          = 0;
var __duration          = 0;
var __cancel            = false;

var __target;
var __containerElement;
var __to;
var __start;
var __deltaTop;
var __percent;
var __delayTimeout;

var currentPositionY = function() {
  if (__containerElement) {
        return __containerElement.scrollTop;
	} else {
    var supportPageOffset = window.pageXOffset !== undefined;
    var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
    return supportPageOffset ? window.pageYOffset : isCSS1Compat ?
           document.documentElement.scrollTop : document.body.scrollTop;
   }
};

var scrollContainerHeight = function() {
  if(__containerElement) {
    return Math.max(
      __containerElement.scrollHeight,
      __containerElement.offsetHeight,
      __containerElement.clientHeight
    );
  } else {
    var body = document.body;
    var html = document.documentElement;

    return Math.max(
      body.scrollHeight,
      body.offsetHeight,
      html.clientHeight,
      html.scrollHeight,
      html.offsetHeight
    );
  }
};

var animateTopScroll = function(timestamp) {
  // Cancel on specific events
  if(__cancel) { return };

  __deltaTop = Math.round(__targetPositionY - __startPositionY);

  if (__start === null) {
    __start = timestamp;
  }

  __progress = timestamp - __start;

  __percent = (__progress >= __duration ? 1 : easing(__progress/__duration));

  __currentPositionY = __startPositionY + Math.ceil(__deltaTop * __percent);

  if(__containerElement) {
    __containerElement.scrollTop = __currentPositionY;
  } else {
    window.scrollTo(0, __currentPositionY);
  }

  if(__percent < 1) {
    requestAnimationFrameHelper.call(window, animateTopScroll);
    return;
  }

  if(events.registered['end']) {
    events.registered['end'](__to, __target, __currentPositionY);
  }

};

var setContainer = function (options) {
  var containerId = options.containerId;
	__containerElement = containerId ? document.getElementById(containerId) : null;
};

var startAnimateTopScroll = function(y, options, to, target) {

  window.clearTimeout(__delayTimeout);

  if(!__containerElement) {
    setContainer(options);
  }

  __start           = null;
  __cancel          = false;
  __startPositionY  = currentPositionY();
  __targetPositionY = options.absolute ? y : y + __startPositionY;
  __deltaTop        = Math.round(__targetPositionY - __startPositionY);

  __duration        = functionWrapper(options.duration)(__deltaTop);
  __duration        = isNaN(parseFloat(__duration)) ? 1000 : parseFloat(__duration);
  __to              = to;
  __target          = target;

  if(options && options.delay > 0) {
    __delayTimeout = window.setTimeout(function animate() {
      requestAnimationFrameHelper.call(window, animateTopScroll);
    }, options.delay);
    return;
  }

  requestAnimationFrameHelper.call(window, animateTopScroll);

};

var scrollToTop = function (options) {
  startAnimateTopScroll(0, assign(options || {}, { absolute : true }));
};

var scrollTo = function (toY, options) {
  startAnimateTopScroll(toY, assign(options || {}, { absolute : true }));
};

var scrollToBottom = function(options) {
  setContainer(options);
  startAnimateTopScroll(scrollContainerHeight(), assign(options || {}, { absolute : true }));
};

var scrollMore = function(toY, options) {
  setContainer(options);
  startAnimateTopScroll(currentPositionY() + toY, assign(options || {}, { absolute : true }));
};

module.exports = {
  animateTopScroll: startAnimateTopScroll,
  scrollToTop: scrollToTop,
  scrollToBottom: scrollToBottom,
  scrollTo: scrollTo,
  scrollMore: scrollMore,
};
<commit_msg>fixed set container incase of no options.<commit_after>var assign = require('object-assign');

var smooth = require('./smooth');

var easing = smooth.defaultEasing;

var cancelEvents = require('./cancel-events');

var events = require('./scroll-events');

/*
 * Function helper
 */
var functionWrapper = function(value) {
  return typeof value === 'function' ? value : function() { return value; };
};

/*
 * Sets the cancel trigger
 */

cancelEvents.register(function() {
  __cancel = true;
});

/*
 * Wraps window properties to allow server side rendering
 */
var currentWindowProperties = function() {
  if (typeof window !== 'undefined') {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame;
  }
};

/*
 * Helper function to never extend 60fps on the webpage.
 */
var requestAnimationFrameHelper = (function () {
  return  currentWindowProperties() ||
          function (callback, element, delay) {
              window.setTimeout(callback, delay || (1000/60), new Date().getTime());
          };
})();

var __currentPositionY  = 0;
var __startPositionY    = 0;
var __targetPositionY   = 0;
var __progress          = 0;
var __duration          = 0;
var __cancel            = false;

var __target;
var __containerElement;
var __to;
var __start;
var __deltaTop;
var __percent;
var __delayTimeout;

var currentPositionY = function() {
  if (__containerElement) {
        return __containerElement.scrollTop;
	} else {
    var supportPageOffset = window.pageXOffset !== undefined;
    var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
    return supportPageOffset ? window.pageYOffset : isCSS1Compat ?
           document.documentElement.scrollTop : document.body.scrollTop;
   }
};

var scrollContainerHeight = function() {
  if(__containerElement) {
    return Math.max(
      __containerElement.scrollHeight,
      __containerElement.offsetHeight,
      __containerElement.clientHeight
    );
  } else {
    var body = document.body;
    var html = document.documentElement;

    return Math.max(
      body.scrollHeight,
      body.offsetHeight,
      html.clientHeight,
      html.scrollHeight,
      html.offsetHeight
    );
  }
};

var animateTopScroll = function(timestamp) {
  // Cancel on specific events
  if(__cancel) { return };

  __deltaTop = Math.round(__targetPositionY - __startPositionY);

  if (__start === null) {
    __start = timestamp;
  }

  __progress = timestamp - __start;

  __percent = (__progress >= __duration ? 1 : easing(__progress/__duration));

  __currentPositionY = __startPositionY + Math.ceil(__deltaTop * __percent);

  if(__containerElement) {
    __containerElement.scrollTop = __currentPositionY;
  } else {
    window.scrollTo(0, __currentPositionY);
  }

  if(__percent < 1) {
    requestAnimationFrameHelper.call(window, animateTopScroll);
    return;
  }

  if(events.registered['end']) {
    events.registered['end'](__to, __target, __currentPositionY);
  }

};

var setContainer = function (options) {
  if(!options || !options.containerId) { return; }
	__containerElement = document.getElementById(options.containerId);
};

var startAnimateTopScroll = function(y, options, to, target) {

  window.clearTimeout(__delayTimeout);

  if(!__containerElement) {
    setContainer(options);
  }

  __start           = null;
  __cancel          = false;
  __startPositionY  = currentPositionY();
  __targetPositionY = options.absolute ? y : y + __startPositionY;
  __deltaTop        = Math.round(__targetPositionY - __startPositionY);

  __duration        = functionWrapper(options.duration)(__deltaTop);
  __duration        = isNaN(parseFloat(__duration)) ? 1000 : parseFloat(__duration);
  __to              = to;
  __target          = target;

  if(options && options.delay > 0) {
    __delayTimeout = window.setTimeout(function animate() {
      requestAnimationFrameHelper.call(window, animateTopScroll);
    }, options.delay);
    return;
  }

  requestAnimationFrameHelper.call(window, animateTopScroll);

};

var scrollToTop = function (options) {
  startAnimateTopScroll(0, assign(options || {}, { absolute : true }));
};

var scrollTo = function (toY, options) {
  startAnimateTopScroll(toY, assign(options || {}, { absolute : true }));
};

var scrollToBottom = function(options) {
  setContainer(options);
  startAnimateTopScroll(scrollContainerHeight(), assign(options || {}, { absolute : true }));
};

var scrollMore = function(toY, options) {
  setContainer(options);
  startAnimateTopScroll(currentPositionY() + toY, assign(options || {}, { absolute : true }));
};

module.exports = {
  animateTopScroll: startAnimateTopScroll,
  scrollToTop: scrollToTop,
  scrollToBottom: scrollToBottom,
  scrollTo: scrollTo,
  scrollMore: scrollMore,
};
<|endoftext|>