<commit_before>(function() {
  'use strict';
  angular.module('civic.events')
    .directive('evidenceGrid', evidenceGrid)
    .controller('EvidenceGridController', EvidenceGridController);

  // @ngInject
  function evidenceGrid() {
    var directive = {
      restrict: 'E',
      replace: true,
      scope: {
        evidence: '=',
        variant: '=',
        rows: '=',
        showGeneCol: '=',
        showVariantCol: '=',
        context: '=',
        rounded: '='
      },
      templateUrl: 'app/views/events/variants/summary/evidenceGrid.tpl.html',
      controller: 'EvidenceGridController'
    };
    return directive;
  }

  // @ngInject
  function EvidenceGridController($scope, $stateParams, $state, $log, uiGridConstants, _) {
    /*jshint camelcase: false */
    var ctrl = $scope.ctrl = {};
    var statusFilters = ['accepted', 'submitted'];
    ctrl.showGridKey = false;

    ctrl.keyPopover = {
      templateUrl: 'app/views/events/variants/summary/evidenceGridPopoverKey.tpl.html',
      title: 'Evidence Grid Column Key'
    };

    ctrl.tooltipPopupDelay = 500;

    ctrl.evidenceLevels = {
      'A': 'A - Validated',
      'B': 'B - Clinical',
      'C': 'C - Case Study',
      'D': 'D - Preclinical',
      'E': 'E - Inferential'
    };

    ctrl.rowsToShow = $scope.rows === undefined ? 5 : $scope.rows;

    ctrl.evidenceGridOptions = {
      minRowsToShow: ctrl.rowsToShow - 1,

      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableVerticalScrollbar: uiGridConstants.scrollbars.ALWAYS,
      enableFiltering: true,
      enableColumnMenus: false,
      enableSorting: true,
      enableRowSelection: true,
      enableRowHeaderSelection: false,
      multiSelect: false,
      noUnselect: true,
      modifierKeysToMultiSelect: false,

      // grid menu
      enableGridMenu: true,
      gridMenuShowHideColumns: false,
      gridMenuCustomItems: [
        {
          title: 'Show Accepted',
          active: function() {
            return _.contains(statusFilters, 'accepted');
          },
          action: function($event) {
            filterByStatus('accepted', this.grid, $event);
          }
        },
        {
          title: 'Show Submitted',
          active: function() {
            return _.contains(statusFilters, 'submitted');
          },
          action: function($event) {
            filterByStatus('submitted', this.grid, $event);
          }
        },
        {
          title: 'Show Rejected',
          active: function() {
            return _.contains(statusFilters, 'rejected');
          },
          action: function($event) {
            filterByStatus('rejected', this.grid, $event);
          }
        }
      ],
      columnDefs: [
        {
          name: 'status',
          displayName: 'ST',
          type: 'string',
          visible: false,
          filter: {
            noTerm: true,
            condition: function(searchTerm, cellValue) {
              return _.contains(statusFilters, cellValue);
            }
          }
        },
        { name: 'id',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'EID',
          headerTooltip: 'Evidence ID',
          type: 'number',
          enableFiltering: false,
          allowCellFocus: false,
          minWidth: 50,
          width: '6%',
          cellTemplate: 'app/views/events/variants/summary/evidenceGridIdCell.tpl.html'
        },
        { name: 'gene',
          field: 'state_params.gene.name',
          displayName: 'GENE',
          visible: $scope.showGeneCol,
          headerTooltip: 'Gene',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          width: '6%'
        },
        { name: 'variant',
          field: 'state_params.variant.name',
          displayName: 'VARIANT',
          visible: $scope.showVariantCol,
          headerTooltip: 'Variant',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          width: '8%'
        },
        { name: 'description',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'DESC',
          headerTooltip: 'Description',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/events/variants/summary/evidenceGridEvidenceCell.tpl.html'
        },
        { name: 'disease',
          field: 'disease.name',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'DIS',
          headerTooltip: 'Disease',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: true,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/events/variants/summary/evidenceGridDiseaseCell.tpl.html'
        },
        { name: 'drugs',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'DRUGS',
          headerTooltip: 'Drugs',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: true,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/events/variants/summary/evidenceGridDrugCell.tpl.html'
        },
        { name: 'evidence_level',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'EL',
          headerTooltip: 'Evidence Level',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'A', label: 'A - Validated'},
              { value: 'B', label: 'B - Clinical'},
              { value: 'C', name: 'C - Case Study'},
              { value: 'D', name: 'D - Preclinical'},
              { value: 'E', label: 'E - Inferential'}]
          },
          sort: { direction: uiGridConstants.ASC },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridLevelCell.tpl.html'
        },
        { name: 'evidence_type',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'ET',
          headerTooltip: 'Evidence Type',
          type: 'string',
          allowCellFocus: false,
          //enableFiltering: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              {
                value: null,
                label: '--'
              },
              {
                value: 'Predictive',
                label: 'Predictive'
              },
              {
                value: 'Diagnostic',
                label: 'Diagnostic'
              },
              {
                value: 'Prognostic',
                label: 'Prognostic'
              }
            ]
          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridTypeCell.tpl.html'
        },
        { name: 'evidence_direction',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'ED',
          headerTooltip: 'Evidence Direction',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'Supports', label: 'Supports' },
              { value: 'Does not Support', label: 'Does not Support' }
            ]
          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceDirectionCell.tpl.html'
        },
        { name: 'clinical_significance',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'CS',
          headerTooltip: 'Clinical Significance',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'Sensitivity', label: 'Sensitivity' },
              { value: 'Resistance or Non-Response', label: 'Resistance or Non-Response' },
              { value: 'Better Outcome', label: 'Better Outcome' },
              { value: 'Poor Outcome', label: 'Poor Outcome' },
              { value: 'Positive', label: 'Positive' },
              { value: 'Negative', label: 'Negative' },
              { value: 'Adverse Response', label: 'Adverse Response' },
              { value: 'N/A', label: 'N/A' }
            ]

          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridClinicalSignificanceCell.tpl.html'
        },
        { name: 'variant_origin',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'VO',
          headerTooltip: 'Variant Origin',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'Somatic Mutation', label: 'Somatic Mutation'},
              { value: 'Germline Mutation', label: 'Germline Mutation' },
              { value: 'Germline Polymorphism', label: 'Germline Polymorphism' },
              { value: 'Unknown', label: 'Unknown' },
              { value: 'N/A', label: 'N/A' },
            ]
          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridVariantOriginCell.tpl.html'
        },
        { name: 'rating',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'TR',
          headerTooltip: 'Trust Rating',
          type: 'number',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            condition: uiGridConstants.filter.GREATER_THAN_OR_EQUAL,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: '5', label: '5 stars'},
              { value: '4', label: '4 stars'},
              { value: '3', label: '3 stars'},
              { value: '2', label: '2 stars'},
              { value: '1', label: '1 stars'},
            ]
          },
          sort: { direction: uiGridConstants.DESC },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridRatingCell.tpl.html'
          //cellTemplate: '<div>{{row.entity[col.field]}}</div>'
        }
      ]
    };

    function filterByStatus(status, grid) {
      if (_.has(grid.selection.lastSelectedRow, 'entity') &&
        status === 'rejected' &&
        grid.selection.lastSelectedRow.entity.status === 'rejected'
      ) {
        console.warn('Cannot hide rejected items if currently selected item is itself rejected.');
        return;
      }
      if (_.has(grid.selection.lastSelectedRow, 'entity') &&
        status === 'submitted' &&
        grid.selection.lastSelectedRow.entity.status === 'submitted'
      ) {
        console.warn('Cannot hide submitted items if currently selected item is itself submitted.');
        return;
      }

      if(_.contains(statusFilters, status)) {
        _.pull(statusFilters, status);
      } else {
        statusFilters.push(status);
      }
      grid.queueGridRefresh();
    }

    ctrl.evidenceGridOptions.onRegisterApi = function(gridApi){
      var evidence = $scope.evidence;
      ctrl.gridApi = gridApi;
      ctrl.evidenceGridOptions.minRowsToShow = evidence.length + 1;
      var suppressGo = false;

      // convert drug array into comma delimited list
      evidence = prepareDrugArray(evidence);

      // assign evidence data to grid
      ctrl.evidenceGridOptions.data = evidence;

      // setup watcher to update grid
      $scope.$watchCollection('evidence', function(evidence) {
        // if we get an evidence list that is rejected items only, let's show those instead of showing nothing
        if(_.every(evidence, 'status', 'rejected')) {
          statusFilters = ['accepted', 'submitted', 'rejected'];
        } else if (!_.includes(statusFilters, 'rejected')) {
          statusFilters = ['accepted', 'submitted'];
        }
        ctrl.evidenceGridOptions.data = prepareDrugArray(evidence);
      });

      // if we're loading an evidence view, highlight the correct row in the table
      gridApi.core.on.rowsRendered($scope, function() {
        if(_.has($stateParams, 'evidenceId')) {
          var rowEntity = _.find($scope.evidence, function (item) {
            return item.id === +$stateParams.evidenceId;
          });

          // if a highlighted row is a rejected item, show rejected items
          if(rowEntity.status === 'rejected') {
            $log.debug('highlight row is for rejected entity.');
            if(!_.includes(statusFilters, 'rejected')) {
              statusFilters.push('rejected');
            }
          }

          suppressGo = true;
          gridApi.selection.selectRow(rowEntity);
          gridApi.grid.scrollTo(rowEntity);
          suppressGo = false;
        }
      });

      gridApi.selection.on.rowSelectionChanged($scope, function(row){
        var params = {};
        if($stateParams.geneId !== undefined && $stateParams.variantId !== undefined) {
          params = _.merge($stateParams, { evidenceId: row.entity.id, '#': 'evidence' });

          // the highlight in onRowsRendered will trigger a state change unless we catch it here
          if(!suppressGo) {
            $state.go('events.genes.summary.variants.summary.evidence.summary', params);
          }
        } else if (row.entity.state_params !== undefined){
          params = {
            geneId: row.entity.state_params.gene.id,
            variantId: row.entity.state_params.variant.id,
            evidenceId: row.entity.id,
            '#': 'evidence'
          };
          if(!suppressGo) {
            $state.go('events.genes.summary.variants.summary.evidence.summary', params);
          }
        } else {
          console.error('Could not locate gene and variant params for evidence row link!');
        }
      });

      function prepareDrugArray(evidence) {
        return _.map(evidence, function(item){
          if (_.isArray(item.drugs) && item.drugs.length > 0) {
            item.drugs = _.chain(item.drugs).pluck('name').value().join(', ');
            return item;
          } else {
            item.drugs = 'N/A';
            return item;
          }
        });
      }
    };
  }

})();
<commit_msg>fixed drug list generation in evidence grid<commit_after>(function() {
  'use strict';
  angular.module('civic.events')
    .directive('evidenceGrid', evidenceGrid)
    .controller('EvidenceGridController', EvidenceGridController);

  // @ngInject
  function evidenceGrid() {
    var directive = {
      restrict: 'E',
      replace: true,
      scope: {
        evidence: '=',
        variant: '=',
        rows: '=',
        showGeneCol: '=',
        showVariantCol: '=',
        context: '=',
        rounded: '='
      },
      templateUrl: 'app/views/events/variants/summary/evidenceGrid.tpl.html',
      controller: 'EvidenceGridController'
    };
    return directive;
  }

  // @ngInject
  function EvidenceGridController($scope, $stateParams, $state, $log, uiGridConstants, _) {
    /*jshint camelcase: false */
    var ctrl = $scope.ctrl = {};
    var statusFilters = ['accepted', 'submitted'];
    ctrl.showGridKey = false;

    ctrl.keyPopover = {
      templateUrl: 'app/views/events/variants/summary/evidenceGridPopoverKey.tpl.html',
      title: 'Evidence Grid Column Key'
    };

    ctrl.tooltipPopupDelay = 500;

    ctrl.evidenceLevels = {
      'A': 'A - Validated',
      'B': 'B - Clinical',
      'C': 'C - Case Study',
      'D': 'D - Preclinical',
      'E': 'E - Inferential'
    };

    ctrl.rowsToShow = $scope.rows === undefined ? 5 : $scope.rows;

    ctrl.evidenceGridOptions = {
      minRowsToShow: ctrl.rowsToShow - 1,

      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableVerticalScrollbar: uiGridConstants.scrollbars.ALWAYS,
      enableFiltering: true,
      enableColumnMenus: false,
      enableSorting: true,
      enableRowSelection: true,
      enableRowHeaderSelection: false,
      multiSelect: false,
      noUnselect: true,
      modifierKeysToMultiSelect: false,

      // grid menu
      enableGridMenu: true,
      gridMenuShowHideColumns: false,
      gridMenuCustomItems: [
        {
          title: 'Show Accepted',
          active: function() {
            return _.contains(statusFilters, 'accepted');
          },
          action: function($event) {
            filterByStatus('accepted', this.grid, $event);
          }
        },
        {
          title: 'Show Submitted',
          active: function() {
            return _.contains(statusFilters, 'submitted');
          },
          action: function($event) {
            filterByStatus('submitted', this.grid, $event);
          }
        },
        {
          title: 'Show Rejected',
          active: function() {
            return _.contains(statusFilters, 'rejected');
          },
          action: function($event) {
            filterByStatus('rejected', this.grid, $event);
          }
        }
      ],
      columnDefs: [
        {
          name: 'status',
          displayName: 'ST',
          type: 'string',
          visible: false,
          filter: {
            noTerm: true,
            condition: function(searchTerm, cellValue) {
              return _.contains(statusFilters, cellValue);
            }
          }
        },
        { name: 'id',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'EID',
          headerTooltip: 'Evidence ID',
          type: 'number',
          enableFiltering: false,
          allowCellFocus: false,
          minWidth: 50,
          width: '6%',
          cellTemplate: 'app/views/events/variants/summary/evidenceGridIdCell.tpl.html'
        },
        { name: 'gene',
          field: 'state_params.gene.name',
          displayName: 'GENE',
          visible: $scope.showGeneCol,
          headerTooltip: 'Gene',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          width: '6%'
        },
        { name: 'variant',
          field: 'state_params.variant.name',
          displayName: 'VARIANT',
          visible: $scope.showVariantCol,
          headerTooltip: 'Variant',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          width: '8%'
        },
        { name: 'description',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'DESC',
          headerTooltip: 'Description',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/events/variants/summary/evidenceGridEvidenceCell.tpl.html'
        },
        { name: 'disease',
          field: 'disease.name',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'DIS',
          headerTooltip: 'Disease',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: true,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/events/variants/summary/evidenceGridDiseaseCell.tpl.html'
        },
        { name: 'druglist',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'DRUGS',
          headerTooltip: 'Drugs',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: true,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/events/variants/summary/evidenceGridDrugCell.tpl.html'
        },
        { name: 'evidence_level',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'EL',
          headerTooltip: 'Evidence Level',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'A', label: 'A - Validated'},
              { value: 'B', label: 'B - Clinical'},
              { value: 'C', name: 'C - Case Study'},
              { value: 'D', name: 'D - Preclinical'},
              { value: 'E', label: 'E - Inferential'}]
          },
          sort: { direction: uiGridConstants.ASC },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridLevelCell.tpl.html'
        },
        { name: 'evidence_type',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'ET',
          headerTooltip: 'Evidence Type',
          type: 'string',
          allowCellFocus: false,
          //enableFiltering: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              {
                value: null,
                label: '--'
              },
              {
                value: 'Predictive',
                label: 'Predictive'
              },
              {
                value: 'Diagnostic',
                label: 'Diagnostic'
              },
              {
                value: 'Prognostic',
                label: 'Prognostic'
              }
            ]
          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridTypeCell.tpl.html'
        },
        { name: 'evidence_direction',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'ED',
          headerTooltip: 'Evidence Direction',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'Supports', label: 'Supports' },
              { value: 'Does not Support', label: 'Does not Support' }
            ]
          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceDirectionCell.tpl.html'
        },
        { name: 'clinical_significance',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'CS',
          headerTooltip: 'Clinical Significance',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'Sensitivity', label: 'Sensitivity' },
              { value: 'Resistance or Non-Response', label: 'Resistance or Non-Response' },
              { value: 'Better Outcome', label: 'Better Outcome' },
              { value: 'Poor Outcome', label: 'Poor Outcome' },
              { value: 'Positive', label: 'Positive' },
              { value: 'Negative', label: 'Negative' },
              { value: 'Adverse Response', label: 'Adverse Response' },
              { value: 'N/A', label: 'N/A' }
            ]

          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridClinicalSignificanceCell.tpl.html'
        },
        { name: 'variant_origin',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'VO',
          headerTooltip: 'Variant Origin',
          type: 'string',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: 'Somatic Mutation', label: 'Somatic Mutation'},
              { value: 'Germline Mutation', label: 'Germline Mutation' },
              { value: 'Germline Polymorphism', label: 'Germline Polymorphism' },
              { value: 'Unknown', label: 'Unknown' },
              { value: 'N/A', label: 'N/A' },
            ]
          },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridVariantOriginCell.tpl.html'
        },
        { name: 'rating',
          headerCellTemplate: 'app/views/events/variants/summary/evidenceGridTooltipHeader.tpl.html',
          displayName: 'TR',
          headerTooltip: 'Trust Rating',
          type: 'number',
          allowCellFocus: false,
          filter: {
            type: uiGridConstants.filter.SELECT,
            condition: uiGridConstants.filter.GREATER_THAN_OR_EQUAL,
            term: null,
            disableCancelFilterButton: false,
            selectOptions: [
              { value: null, label: '--' },
              { value: '5', label: '5 stars'},
              { value: '4', label: '4 stars'},
              { value: '3', label: '3 stars'},
              { value: '2', label: '2 stars'},
              { value: '1', label: '1 stars'},
            ]
          },
          sort: { direction: uiGridConstants.DESC },
          width: '6%',
          minWidth: 50,
          cellTemplate: 'app/views/events/variants/summary/evidenceGridRatingCell.tpl.html'
          //cellTemplate: '<div>{{row.entity[col.field]}}</div>'
        }
      ]
    };

    function filterByStatus(status, grid) {
      if (_.has(grid.selection.lastSelectedRow, 'entity') &&
        status === 'rejected' &&
        grid.selection.lastSelectedRow.entity.status === 'rejected'
      ) {
        console.warn('Cannot hide rejected items if currently selected item is itself rejected.');
        return;
      }
      if (_.has(grid.selection.lastSelectedRow, 'entity') &&
        status === 'submitted' &&
        grid.selection.lastSelectedRow.entity.status === 'submitted'
      ) {
        console.warn('Cannot hide submitted items if currently selected item is itself submitted.');
        return;
      }

      if(_.contains(statusFilters, status)) {
        _.pull(statusFilters, status);
      } else {
        statusFilters.push(status);
      }
      grid.queueGridRefresh();
    }

    ctrl.evidenceGridOptions.onRegisterApi = function(gridApi){
      var evidence = $scope.evidence;
      ctrl.gridApi = gridApi;
      ctrl.evidenceGridOptions.minRowsToShow = evidence.length + 1;
      var suppressGo = false;

      // convert drug array into comma delimited list
      evidence = prepareDrugArray(evidence);

      // assign evidence data to grid
      ctrl.evidenceGridOptions.data = evidence;

      // setup watcher to update grid
      $scope.$watchCollection('evidence', function(evidence) {
        // if we get an evidence list that is rejected items only, let's show those instead of showing nothing
        if(_.every(evidence, 'status', 'rejected')) {
          statusFilters = ['accepted', 'submitted', 'rejected'];
        } else if (!_.includes(statusFilters, 'rejected')) {
          statusFilters = ['accepted', 'submitted'];
        }
        ctrl.evidenceGridOptions.data = prepareDrugArray(evidence);
      });

      // if we're loading an evidence view, highlight the correct row in the table
      gridApi.core.on.rowsRendered($scope, function() {
        if(_.has($stateParams, 'evidenceId')) {
          var rowEntity = _.find($scope.evidence, function (item) {
            return item.id === +$stateParams.evidenceId;
          });

          // if a highlighted row is a rejected item, show rejected items
          if(rowEntity.status === 'rejected') {
            $log.debug('highlight row is for rejected entity.');
            if(!_.includes(statusFilters, 'rejected')) {
              statusFilters.push('rejected');
            }
          }

          suppressGo = true;
          gridApi.selection.selectRow(rowEntity);
          gridApi.grid.scrollTo(rowEntity);
          suppressGo = false;
        }
      });

      gridApi.selection.on.rowSelectionChanged($scope, function(row){
        var params = {};
        if($stateParams.geneId !== undefined && $stateParams.variantId !== undefined) {
          params = _.merge($stateParams, { evidenceId: row.entity.id, '#': 'evidence' });

          // the highlight in onRowsRendered will trigger a state change unless we catch it here
          if(!suppressGo) {
            $state.go('events.genes.summary.variants.summary.evidence.summary', params);
          }
        } else if (row.entity.state_params !== undefined){
          params = {
            geneId: row.entity.state_params.gene.id,
            variantId: row.entity.state_params.variant.id,
            evidenceId: row.entity.id,
            '#': 'evidence'
          };
          if(!suppressGo) {
            $state.go('events.genes.summary.variants.summary.evidence.summary', params);
          }
        } else {
          console.error('Could not locate gene and variant params for evidence row link!');
        }
      });

      function prepareDrugArray(evidence) {
        return _.map(evidence, function(item){
          if (_.isArray(item.drugs) && item.drugs.length > 0) {
            item.druglist = _.chain(item.drugs).pluck('name').value().join(', ');
            return item;
          } else {
            item.druglist = 'N/A';
            return item;
          }
        });
      }
    };
  }

})();
<|endoftext|>


<commit_before>import constants from 'vets-json-schema/dist/constants.json';

// *** URLS ***
export const HLR_INFO_URL = '/decision-reviews/higher-level-review/';
// Same as "rootUrl" in manifest.json
export const BASE_URL = `${HLR_INFO_URL}request-higher-level-review-form-20-0996`;

export const FORM_URL = 'https://www.vba.va.gov/pubs/forms/VBA-20-0996-ARE.pdf';

export const BOARD_APPEALS_URL = '/decision-reviews/board-appeal/';
export const DECISION_REVIEWS_URL = '/decision-reviews/';
export const CLAIM_STATUS_TOOL_URL = '/claim-or-appeal-status/';
export const SUPPLEMENTAL_CLAIM_URL = '/decision-reviews/supplemental-claim/';
export const COVID_FAQ_URL =
  'https://www.va.gov/coronavirus-veteran-frequently-asked-questions/#more-benefit-and-claim-questio';
export const FACILITY_LOCATOR_URL = '/find-locations';
export const GET_HELP_REVIEW_REQUEST_URL =
  '/decision-reviews/get-help-with-review-request';
export const PROFILE_URL = '/profile';
export const LEGACY_APPEALS_URL = '/decision-reviews/legacy-appeals/';

// 8622 is the ID of the <li> wrapping the "Find addresses for other benefit
// types" accordion
export const BENEFIT_OFFICES_URL = `${HLR_INFO_URL}#find-addresses`;

export const CONTESTABLE_ISSUES_API =
  '/higher_level_reviews/contestable_issues/';

// key for contestedIssues to indicate that the user selected the issue
export const SELECTED = 'view:selected';

// Including a default until we determine how to get around the user restarting
// the application after using the "Finish this application later" link
// See https://dsva.slack.com/archives/C0113MPTGH5/p1600725048027200
export const DEFAULT_BENEFIT_TYPE = 'compensation';

export const errorMessages = {
  savedFormNotFound: 'Please start over to request a Higher-Level Review',
  savedFormNoAuth:
    'Please sign in again to continue your request for Higher-Level Review',
  forwardStartDate: 'Please select a date',
  startDateInPast: 'Start date must be in the future',
  endDateInPast: 'End date must be in the future',
  endDateBeforeStart: 'End date must be after start date',
  informalConferenceContactChoice: 'Please choose an option',
  informalConferenceContactName: 'Please enter your representative’s name',
  informalConferenceContactFirstName:
    'Please enter your representative’s first name',
  informalConferenceContactLastName:
    'Please enter your representative’s last name',
  informalConferenceContactPhone:
    'Please enter your representative’s phone number',
  informalConferenceContactPhonePattern:
    'Please enter a 10-digit phone number (with or without dashes)',
  informalConferenceTimes: 'Please select a time',
  contestedIssue: 'Please select an eligible issue',
};

export const NULL_CONDITION_STRING = 'Unknown Condition';

// contested issue dates
export const FORMAT_YMD = 'YYYY-MM-DD';
export const FORMAT_READABLE = 'LL';

// session storage keys
export const SAVED_CLAIM_TYPE = 'hlrClaimType';
export const WIZARD_STATUS = 'wizardStatus996';

export const MAX_SELECTIONS = 100;

// Values from benefitTypes in vets-json-schema constants
const supportedBenefitTypes = [
  'compensation', // Phase 1
  // 'pension',
  // 'fiduciary',
  // 'education',
  // 'vha',
  // 'voc_rehab',
  // 'loan_guaranty',
  // 'insurance',
  // 'nca',
];

export const SUPPORTED_BENEFIT_TYPES = constants.benefitTypes.map(type => ({
  ...type,
  isSupported: supportedBenefitTypes.includes(type.value),
}));

export const CONFERENCE_TIMES_V1 = {
  time0800to1000: {
    label: '8:00 a.m. to 10:00 a.m. ET',
    submit: '800-1000 ET',
  },
  time1000to1230: {
    label: '10:00 a.m. to 12:30 p.m. ET',
    submit: '1000-1230 ET',
  },
  time1230to1400: {
    label: '12:30 p.m. to 2:00 p.m. ET',
    submit: '1230-1400 ET',
  },
  time1400to1630: {
    label: '2:00 p.m. to 4:30 p.m. ET',
    submit: '1400-1630 ET',
  },
};

export const CONFERENCE_TIMES_V2 = {
  time0800to1200: {
    label: '8:00 a.m. to noon ET',
    submit: '800-1200 ET',
  },
  time1200to1630: {
    label: 'Noon to 4:30 p.m. ET',
    submit: '1200-1630 ET',
  },
};

// Values from Lighthouse maintained schema
// see https://github.com/department-of-veterans-affairs/vets-api/blob/master/modules/appeals_api/config/schemas/v2/200996.json
export const MAX_ISSUE_NAME_LENGTH = 140;
export const MAX_DISAGREEMENT_REASON_LENGTH = 90;

// Using MAX_DISAGREEMENT_REASON_LENGTH (90) and with all checkboxes selected,
// this string is submitted - the numbers constitute the "other" typed in value
// "service connection,effective date,disability evaluation,1234567890123456789012345678901234"
export const SUBMITTED_DISAGREEMENTS = {
  serviceConnection: 'service connection',
  effectiveDate: 'effective date',
  evaluation: 'disability evaluation',
};
<commit_msg>HLR: Fix other benefits anchor (#19554)<commit_after>import constants from 'vets-json-schema/dist/constants.json';

// *** URLS ***
export const HLR_INFO_URL = '/decision-reviews/higher-level-review/';
// Same as "rootUrl" in manifest.json
export const BASE_URL = `${HLR_INFO_URL}request-higher-level-review-form-20-0996`;

export const FORM_URL = 'https://www.vba.va.gov/pubs/forms/VBA-20-0996-ARE.pdf';

export const BOARD_APPEALS_URL = '/decision-reviews/board-appeal/';
export const DECISION_REVIEWS_URL = '/decision-reviews/';
export const CLAIM_STATUS_TOOL_URL = '/claim-or-appeal-status/';
export const SUPPLEMENTAL_CLAIM_URL = '/decision-reviews/supplemental-claim/';
export const COVID_FAQ_URL =
  'https://www.va.gov/coronavirus-veteran-frequently-asked-questions/#more-benefit-and-claim-questio';
export const FACILITY_LOCATOR_URL = '/find-locations';
export const GET_HELP_REVIEW_REQUEST_URL =
  '/decision-reviews/get-help-with-review-request';
export const PROFILE_URL = '/profile';
export const LEGACY_APPEALS_URL = '/decision-reviews/legacy-appeals/';

// 8622 is the ID of the <va-accordion-item> with a header of the "Find
// addresses for other benefit types"
export const BENEFIT_OFFICES_URL = `${HLR_INFO_URL}#find-addresses-for-other-benef-8622`;

export const CONTESTABLE_ISSUES_API =
  '/higher_level_reviews/contestable_issues/';

// key for contestedIssues to indicate that the user selected the issue
export const SELECTED = 'view:selected';

// Including a default until we determine how to get around the user restarting
// the application after using the "Finish this application later" link
// See https://dsva.slack.com/archives/C0113MPTGH5/p1600725048027200
export const DEFAULT_BENEFIT_TYPE = 'compensation';

export const errorMessages = {
  savedFormNotFound: 'Please start over to request a Higher-Level Review',
  savedFormNoAuth:
    'Please sign in again to continue your request for Higher-Level Review',
  forwardStartDate: 'Please select a date',
  startDateInPast: 'Start date must be in the future',
  endDateInPast: 'End date must be in the future',
  endDateBeforeStart: 'End date must be after start date',
  informalConferenceContactChoice: 'Please choose an option',
  informalConferenceContactName: 'Please enter your representative’s name',
  informalConferenceContactFirstName:
    'Please enter your representative’s first name',
  informalConferenceContactLastName:
    'Please enter your representative’s last name',
  informalConferenceContactPhone:
    'Please enter your representative’s phone number',
  informalConferenceContactPhonePattern:
    'Please enter a 10-digit phone number (with or without dashes)',
  informalConferenceTimes: 'Please select a time',
  contestedIssue: 'Please select an eligible issue',
};

export const NULL_CONDITION_STRING = 'Unknown Condition';

// contested issue dates
export const FORMAT_YMD = 'YYYY-MM-DD';
export const FORMAT_READABLE = 'LL';

// session storage keys
export const SAVED_CLAIM_TYPE = 'hlrClaimType';
export const WIZARD_STATUS = 'wizardStatus996';

export const MAX_SELECTIONS = 100;

// Values from benefitTypes in vets-json-schema constants
const supportedBenefitTypes = [
  'compensation', // Phase 1
  // 'pension',
  // 'fiduciary',
  // 'education',
  // 'vha',
  // 'voc_rehab',
  // 'loan_guaranty',
  // 'insurance',
  // 'nca',
];

export const SUPPORTED_BENEFIT_TYPES = constants.benefitTypes.map(type => ({
  ...type,
  isSupported: supportedBenefitTypes.includes(type.value),
}));

export const CONFERENCE_TIMES_V1 = {
  time0800to1000: {
    label: '8:00 a.m. to 10:00 a.m. ET',
    submit: '800-1000 ET',
  },
  time1000to1230: {
    label: '10:00 a.m. to 12:30 p.m. ET',
    submit: '1000-1230 ET',
  },
  time1230to1400: {
    label: '12:30 p.m. to 2:00 p.m. ET',
    submit: '1230-1400 ET',
  },
  time1400to1630: {
    label: '2:00 p.m. to 4:30 p.m. ET',
    submit: '1400-1630 ET',
  },
};

export const CONFERENCE_TIMES_V2 = {
  time0800to1200: {
    label: '8:00 a.m. to noon ET',
    submit: '800-1200 ET',
  },
  time1200to1630: {
    label: 'Noon to 4:30 p.m. ET',
    submit: '1200-1630 ET',
  },
};

// Values from Lighthouse maintained schema
// see https://github.com/department-of-veterans-affairs/vets-api/blob/master/modules/appeals_api/config/schemas/v2/200996.json
export const MAX_ISSUE_NAME_LENGTH = 140;
export const MAX_DISAGREEMENT_REASON_LENGTH = 90;

// Using MAX_DISAGREEMENT_REASON_LENGTH (90) and with all checkboxes selected,
// this string is submitted - the numbers constitute the "other" typed in value
// "service connection,effective date,disability evaluation,1234567890123456789012345678901234"
export const SUBMITTED_DISAGREEMENTS = {
  serviceConnection: 'service connection',
  effectiveDate: 'effective date',
  evaluation: 'disability evaluation',
};
<|endoftext|>


<commit_before>const { get, includes, snakeCase } = require('lodash')

const { getContactsForCompany } = require('../../contacts/repos')
const { getAdvisers } = require('../../adviser/repos')
const { filterActiveAdvisers } = require('../../adviser/filters')
const { getActiveEvents } = require('../../events/repos')
const { transformObjectToOption, transformContactToOption } = require('../../transformers')
const { getOptions } = require('../../../lib/options')
const { SERVICE_DELIVERY_STATUS_COMPLETED } = require('../constants')

async function getInteractionOptions (req, res) {
  const token = req.session.token
  const createdOn = get(res.locals, 'interaction.created_on')
  const companyId = get(res.locals, 'company.id')

  const contacts = await getContactsForCompany(token, companyId)
  const advisers = await getAdvisers(token)
  const currentAdviser = get(res.locals, 'interaction.dit_adviser.id')

  const activeAdvisers = filterActiveAdvisers({
    advisers: advisers.results,
    includeAdviser: currentAdviser,
  })

  const options = {
    advisers: activeAdvisers.map(transformObjectToOption),
    contacts: contacts.filter(contact => !contact.archived).map(transformContactToOption),
    teams: await getOptions(token, 'team', { createdOn }),
    services: await getServiceOptions(req, res, createdOn),
  }

  options.tapServices = options.services
    .filter(service => includes(service.label, '(TAP)'))
    .map(service => service.value)

  options.successfulServiceStatuses = [
    SERVICE_DELIVERY_STATUS_COMPLETED,
  ]

  if (req.params.kind === 'service-delivery') {
    const activeEvents = await getActiveEvents(token, createdOn)
    options.events = activeEvents.map(transformObjectToOption)

    options.statuses = await getOptions(token, 'service-delivery-status', { createdOn, sorted: false })
  } else {
    options.channels = await getOptions(token, 'communication-channel', { createdOn })
  }

  return options
}

async function getServiceOptions (req, res, createdOn) {
  const context = getContextForInteraction(req, res)
  const services = await getOptions(req.session.token, 'service', { createdOn, context })
  return services
}

function getContextForInteraction (req, res) {
  if (get(res, 'locals.investmentData.id') || get(res.locals, 'interaction.investment_project.id')) {
    return 'investment_project_interaction'
  }

  return snakeCase(get(req.params, 'kind', 'interaction'))
}

module.exports = { getInteractionOptions }
<commit_msg>Add policy feedback support to getInteractionOptions<commit_after>const { get, includes, snakeCase } = require('lodash')

const { getContactsForCompany } = require('../../contacts/repos')
const { getAdvisers } = require('../../adviser/repos')
const { filterActiveAdvisers } = require('../../adviser/filters')
const { getActiveEvents } = require('../../events/repos')
const { transformObjectToOption, transformContactToOption } = require('../../transformers')
const { getOptions } = require('../../../lib/options')
const { SERVICE_DELIVERY_STATUS_COMPLETED } = require('../constants')

async function getInteractionOptions (req, res) {
  const token = req.session.token
  const kind = req.params.kind
  const createdOn = get(res.locals, 'interaction.created_on')

  const commonOptions = await getCommonOptions(token, createdOn, req, res)

  let formOptions

  if (kind === 'service-delivery') {
    formOptions = await getServiceDeliveryFormOptions(token, createdOn, req, res)
  } else if (kind === 'policy-feedback') {
    formOptions = await getPolicyFeedbackFormOptions(token, createdOn)
  } else {
    formOptions = await getInteractionFormOptions(token, createdOn, req, res)
  }

  return {
    ...commonOptions,
    ...formOptions,
  }
}

async function getCommonOptions (token, createdOn, req, res) {
  const companyId = get(res.locals, 'company.id')
  const currentAdviser = get(res.locals, 'interaction.dit_adviser.id')

  const contacts = await getContactsForCompany(token, companyId)
  const advisers = await getAdvisers(token)

  const activeAdvisers = filterActiveAdvisers({
    advisers: advisers.results,
    includeAdviser: currentAdviser,
  })

  const commonOptions = {
    advisers: activeAdvisers.map(transformObjectToOption),
    contacts: contacts.filter(contact => !contact.archived).map(transformContactToOption),
    teams: await getOptions(token, 'team', { createdOn }),
  }

  return commonOptions
}

async function getInteractionFormOptions (token, createdOn, req, res) {
  const formOptions = {
    services: await getServiceOptions(req, res, createdOn),
    channels: await getOptions(token, 'communication-channel', { createdOn }),
  }

  return formOptions
}

async function getServiceDeliveryFormOptions (token, createdOn, req, res) {
  const services = await getServiceOptions(req, res, createdOn)

  const tapServices = services
    .filter(service => includes(service.label, '(TAP)'))
    .map(service => service.value)

  const activeEvents = await getActiveEvents(token, createdOn)
  const events = activeEvents.map(transformObjectToOption)
  const statuses = await getOptions(token, 'service-delivery-status', { createdOn, sorted: false })

  return {
    services,
    tapServices,
    events,
    statuses,
    successfulServiceStatuses: [SERVICE_DELIVERY_STATUS_COMPLETED],
  }
}

async function getPolicyFeedbackFormOptions (token, createdOn) {
  const formOptions = {
    areas: await getOptions(token, 'policy-area', { createdOn }),
    types: await getOptions(token, 'policy-issue-type', { createdOn }),
    channels: await getOptions(token, 'communication-channel', { createdOn }),
  }

  return formOptions
}

async function getServiceOptions (req, res, createdOn) {
  const context = getContextForInteraction(req, res)
  const services = await getOptions(req.session.token, 'service', { createdOn, context })
  return services
}

function getContextForInteraction (req, res) {
  if (get(res, 'locals.investmentData.id') || get(res.locals, 'interaction.investment_project.id')) {
    return 'investment_project_interaction'
  }

  return snakeCase(get(req.params, 'kind', 'interaction'))
}

module.exports = { getInteractionOptions }
<|endoftext|>


<commit_before>/**
 * React-related utilities
 */

import React from 'react';

/**
 * Like React.Children.forEach(), but traverses through all descendant children.
 *
 * @param children Children of a React element, i.e. `elem.props.children`
 * @param callback {function} A function to be run for each child; parameters passed: (child, indexOfChildInImmediateParent)
 */
export function reactChildrenForEachDeep(children, callback) {
  React.Children.forEach(children, (child, i) => {
    callback(child, i);
    if (child.props.children) {
      reactChildrenForEachDeep(child.props.children, callback);
    }
  });
}
<commit_msg>Add inline documentation for reactChildrenForEachDeep<commit_after>/**
 * React-related utilities
 */

import React from 'react';

/**
 * Like React.Children.forEach(), but traverses through all descendant children.
 *
 * @param children Children of a React element, i.e. `elem.props.children`
 * @param callback {forEachCallback} A function to be run for each child
 */
export function reactChildrenForEachDeep(children, callback) {
  React.Children.forEach(children, (child, i) => {
    callback(child, i);
    if (child.props.children) {
      reactChildrenForEachDeep(child.props.children, callback);
    }
  });
}

/**
 * This callback is displayed as part of the Requester class.
 *
 * @callback forEachCallback
 * @param {*} child The React child
 * @param {number} index The index of the child in its immediate parent
 * @param {number} depth The number of parents traversed to react this child (top-level children have depth === 1)
 */
<|endoftext|>


<commit_before>
/*
 * Tangram
 * Copyright 2009 Baidu Inc. All rights reserved.
 *
 * path: baidu/event/_eventFilter/_crossElementBoundary.js
 * author: Rocy, berg
 * version: 1.0.0
 * date: 2010/12/16
 */

///import baidu.event._eventFilter;

///import baidu.dom.contains;
///import baidu.dom.getDocument;
/**
 * 事件仅在鼠标进入/离开元素区域触发一次，当鼠标在元素区域内部移动的时候不会触发，用于为非IE浏览器添加mouseleave/mouseenter支持。
 *
 * @name baidu.event._eventFilter._crossElementBoundary
 * @function
 * @grammar baidu.event._eventFilter._crossElementBoundary(listener, e)
 *
 * @param {function} listener	要触发的函数
 * @param {DOMEvent} e 			DOM事件
 */

baidu.event._eventFilter._crossElementBoundary = function(listener, e){
    var related = e.relatedTarget,
        current = e.currentTarget;
    if(
       related === false ||
       // 如果current和related都是body，contains函数会返回false
       current == related ||
       // Firefox有时会把XUL元素作为relatedTarget
       // 这些元素不能访问parentNode属性
       // thanks jquery & mootools
       (related && related.prefix == 'xul') ||
       //如果current包含related，说明没有经过current的边界
       baidu.dom.contains(current, related)
      ){
        return ;
    }
    return listener.call(current, e);
};
<commit_msg>修复mouseenter firefox下可能抛错的bug<commit_after>
/*
 * Tangram
 * Copyright 2009 Baidu Inc. All rights reserved.
 *
 * path: baidu/event/_eventFilter/_crossElementBoundary.js
 * author: Rocy, berg
 * version: 1.0.0
 * date: 2010/12/16
 */

///import baidu.event._eventFilter;

///import baidu.dom.contains;
///import baidu.dom.getDocument;
/**
 * 事件仅在鼠标进入/离开元素区域触发一次，当鼠标在元素区域内部移动的时候不会触发，用于为非IE浏览器添加mouseleave/mouseenter支持。
 *
 * @name baidu.event._eventFilter._crossElementBoundary
 * @function
 * @grammar baidu.event._eventFilter._crossElementBoundary(listener, e)
 *
 * @param {function} listener	要触发的函数
 * @param {DOMEvent} e 			DOM事件
 */

baidu.event._eventFilter._crossElementBoundary = function(listener, e){
    var related = e.relatedTarget,
        current = e.currentTarget;
    if(
       related === false ||
       // 如果current和related都是body，contains函数会返回false
       current == related ||
       // Firefox有时会把XUL元素作为relatedTarget
       // 这些元素不能访问parentNode属性
       // thanks jquery & mootools
       (related && (related.prefix == 'xul' ||
       //如果current包含related，说明没有经过current的边界
       baidu.dom.contains(current, related)))
      ){
        return ;
    }
    return listener.call(current, e);
};
<|endoftext|>


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

var userStatements = {}, dojoStatement, loginStatement,
    loginAttemptsStatement, sessionsStatement, countriesStatement;

var connString = process.argv[2] ? process.argv[2] : "mysql://root@127.0.0.1/zen_live"

console.log("DB: ", connString);

var userQueries = {};

//SQL statemennts
userStatements.users =  "select `zen_live`.`users`.`id`, `zen_live`.`users`.`username`," +
                        "`zen_live`.`users`.`email`, `zen_live`.`users`.`level`,`zen_live`.`users`.`activated`," +
                        "`zen_live`.`users`.`banned` ,`zen_live`.`users`.`last_ip`," +
                        "`zen_live`.`users`.`last_login` ,`zen_live`.`users`.`created`," +
                        "`zen_live`.`users`.`modified` from `zen_live`.`users`;";

userStatements.agreements = "SELECT * FROM zen_live.charter_agreement;";
userStatements.profiles = "SELECT * FROM `zen_live`.`user_profiles`;"
userStatements.usersDojos = "SELECT * FROM zen_live.user_dojos;"

countriesStatement = "SELECT * FROM zen_live.countries";

dojoStatement = "SELECT * FROM zen_live.dojos join `zen_live`.`countries` on((`zen_live`.`dojos`.`country` = `zen_live`.`countries`.`alpha2`));";
loginStatement = "SELECT * FROM zen_live.user_autologin;";

loginAttemptsStatement = "SELECT * FROM zen_live.login_attempts;";
sessionsStatement = "SELECT * FROM zen_live.ci_sessions;";

var connection = mysql.createConnection(connString);

connection.connect();

_.forEach(userStatements, function(v, k){
  var execQuery  = function(cb){
    connection.query(v, function(err, data, fields) {
      if (err){
        return cb(err);
      }

      return cb(null, data);
    });
  }

  userQueries[k] = execQuery;
});

//Transformers

var tUsersAgreements = function(results){
  _.forEach(results.users, function(v, k){
    var result = _.where(results.agreements, {user_id: v.id});
    var agreements = result ? result : [];
    v.agreements = agreements;
  });

}

var tUsersProfiles =  function(results){
  _.forEach(results.users, function(v, k){
    var result = _.where(results.profiles, {user_id: v.id});
    var profiles = result ? result : [];
    v.profiles = profiles;
  });
}

var tUserDojos = function(results){
  _.forEach(results.users, function(v, k){
    var result = _.where(results.usersDojos, {user_id: v.id});
    var usersDojos = result ? result : [];
    v.usersDojos = usersDojos;
  });
}

// Individual query cb
var writeFile = function(filename){

  return function(err, data){
    if(err){
      throw err;
    }

    fs.writeFileSync(filename, JSON.stringify(data));
    console.log("%s finished", filename);
  }
}

//users - extract, transform and write file
async.parallel(userQueries, function(err, results) {
  if(err){
    throw err;
  }
  tUsersAgreements(results);
  tUsersProfiles(results);
  tUserDojos(results);

  fs.writeFileSync('./data/users.json', JSON.stringify(results.users));
  console.log("./data/users.json finished");
});

var execIndividualQueries = function(statement){
  return function(cb){
    connection.query(statement, function(err, data, fields) {
      if (err){
        return cb(err);
      }
      return cb(null, data);
    });
  }
}

function execDojoQuery(cb){
  execIndividualQueries(dojoStatement)(cb);
}

function execLoginQuery(cb){
  execIndividualQueries(loginStatement)(cb);
}

function execLoginAttemptsQuery(cb){
  execIndividualQueries(loginAttemptsStatement)(cb);
}

function execSessionQuery(cb){
  execIndividualQueries(sessionsStatement)(cb);
}

function execCountriesQuery(cb){
  execIndividualQueries(countriesStatement)(cb);
}

execLoginQuery(writeFile("./data/login.json"));
execLoginAttemptsQuery(writeFile("./data/loginAttempts.json"));
execSessionQuery(writeFile("./data/sessions.json"))
execDojoQuery(writeFile("./data/dojos.json"));
execCountriesQuery(writeFile("./data/countries.json"));

connection.end();<commit_msg>Add ban reason<commit_after>var mysql = require('mysql');
var _ = require('lodash');
var async = require('async');
var fs = require('fs');

var userStatements = {}, dojoStatement, loginStatement,
    loginAttemptsStatement, sessionsStatement, countriesStatement;

var connString = process.argv[2] ? process.argv[2] : "mysql://root@127.0.0.1/zen_live"

console.log("DB: ", connString);

var userQueries = {};

//SQL statemennts
userStatements.users =  "select `zen_live`.`users`.`id`, `zen_live`.`users`.`username`," +
                        "`zen_live`.`users`.`email`, `zen_live`.`users`.`level`,`zen_live`.`users`.`activated`," +
                        "`zen_live`.`users`.`banned` ,`zen_live`.`users`.`ban_reason`,`zen_live`.`users`.`last_ip`," +
                        "`zen_live`.`users`.`last_login` ,`zen_live`.`users`.`created`," +
                        "`zen_live`.`users`.`modified` from `zen_live`.`users`;";

userStatements.agreements = "SELECT * FROM zen_live.charter_agreement;";
userStatements.profiles = "SELECT * FROM `zen_live`.`user_profiles`;"
userStatements.usersDojos = "SELECT * FROM zen_live.user_dojos;"

countriesStatement = "SELECT * FROM zen_live.countries";

dojoStatement = "SELECT * FROM zen_live.dojos join `zen_live`.`countries` on((`zen_live`.`dojos`.`country` = `zen_live`.`countries`.`alpha2`));";
loginStatement = "SELECT * FROM zen_live.user_autologin;";

loginAttemptsStatement = "SELECT * FROM zen_live.login_attempts;";
sessionsStatement = "SELECT * FROM zen_live.ci_sessions;";

var connection = mysql.createConnection(connString);

connection.connect();

_.forEach(userStatements, function(v, k){
  var execQuery  = function(cb){
    connection.query(v, function(err, data, fields) {
      if (err){
        return cb(err);
      }

      return cb(null, data);
    });
  }

  userQueries[k] = execQuery;
});

//Transformers

var tUsersAgreements = function(results){
  _.forEach(results.users, function(v, k){
    var result = _.where(results.agreements, {user_id: v.id});
    var agreements = result ? result : [];
    v.agreements = agreements;
  });

}

var tUsersProfiles =  function(results){
  _.forEach(results.users, function(v, k){
    var result = _.where(results.profiles, {user_id: v.id});
    var profiles = result ? result : [];
    v.profiles = profiles;
  });
}

var tUserDojos = function(results){
  _.forEach(results.users, function(v, k){
    var result = _.where(results.usersDojos, {user_id: v.id});
    var usersDojos = result ? result : [];
    v.usersDojos = usersDojos;
  });
}

// Individual query cb
var writeFile = function(filename){

  return function(err, data){
    if(err){
      throw err;
    }

    fs.writeFileSync(filename, JSON.stringify(data));
    console.log("%s finished", filename);
  }
}

//users - extract, transform and write file
async.parallel(userQueries, function(err, results) {
  if(err){
    throw err;
  }
  tUsersAgreements(results);
  tUsersProfiles(results);
  tUserDojos(results);

  fs.writeFileSync('./data/users.json', JSON.stringify(results.users));
  console.log("./data/users.json finished");
});

var execIndividualQueries = function(statement){
  return function(cb){
    connection.query(statement, function(err, data, fields) {
      if (err){
        return cb(err);
      }
      return cb(null, data);
    });
  }
}

function execDojoQuery(cb){
  execIndividualQueries(dojoStatement)(cb);
}

function execLoginQuery(cb){
  execIndividualQueries(loginStatement)(cb);
}

function execLoginAttemptsQuery(cb){
  execIndividualQueries(loginAttemptsStatement)(cb);
}

function execSessionQuery(cb){
  execIndividualQueries(sessionsStatement)(cb);
}

function execCountriesQuery(cb){
  execIndividualQueries(countriesStatement)(cb);
}

execLoginQuery(writeFile("./data/login.json"));
execLoginAttemptsQuery(writeFile("./data/loginAttempts.json"));
execSessionQuery(writeFile("./data/sessions.json"))
execDojoQuery(writeFile("./data/dojos.json"));
execCountriesQuery(writeFile("./data/countries.json"));

connection.end();<|endoftext|>


<commit_before>const fetch = require('isomorphic-fetch')
const searchBuilder = require('../utils/searchBuilder')

/*
function mergeAggregation (aggregationResult, searchResult) {
  // merge work level aggregations (audiences & fictionNonficiton) into facets
  aggregationResult.aggregations.facets.audiences = aggregationResult.aggregations.audiences
  aggregationResult.aggregations.facets.fictionNonfiction = aggregationResult.aggregations.fictionNonfiction
  searchResult.aggregations.facets.audiences = searchResult.aggregations.audiences
  searchResult.aggregations.facets.fictionNonfiction = searchResult.aggregations.fictionNonfiction

  Object.keys(aggregationResult.aggregations.facets).forEach(facet => {
    const searchResultFacet = searchResult.aggregations.facets[ facet ]
    if (typeof searchResultFacet === 'object') {
      if (!searchResultFacet) {
        searchResult.aggregations.facets[ facet ] = aggregationResult.aggregations.facets[ facet ]
      } else {
        aggregationResult.aggregations.facets[ facet ].buckets.forEach(aggBucket => {
          if (!searchResultFacet.buckets.find(bucket => { return bucket.key === aggBucket.key })) {
            searchResultFacet.buckets.push({
              key: aggBucket.key,
              doc_count: 0,
              parents: { value: 0 }
            })
          }
        })
      }
    }
  })
  return searchResult
}
*/

module.exports = (app) => {
  app.get('/q', (request, response) => {
    const queryString = request.originalUrl.substr(request.originalUrl.indexOf('?') + 1)

    fetch('http://elasticsearch:9200/search/work/_search', {
      method: 'POST',
      body: JSON.stringify(searchBuilder.buildQuery(queryString))
    }).then(res => {
      if (res.ok) {
        return res.json()
      } else {
        return res.text().then(error => { return Promise.reject({ message: error, queryString: queryString }) })
      }
    }).then(json => response.status(200).send(json))
      .catch(error => {
        response.status(500).send({ message: error, queryString: queryString })
    })
  })
}
<commit_msg>patron-client: linting<commit_after>const fetch = require('isomorphic-fetch')
const searchBuilder = require('../utils/searchBuilder')

/*
function mergeAggregation (aggregationResult, searchResult) {
  // merge work level aggregations (audiences & fictionNonficiton) into facets
  aggregationResult.aggregations.facets.audiences = aggregationResult.aggregations.audiences
  aggregationResult.aggregations.facets.fictionNonfiction = aggregationResult.aggregations.fictionNonfiction
  searchResult.aggregations.facets.audiences = searchResult.aggregations.audiences
  searchResult.aggregations.facets.fictionNonfiction = searchResult.aggregations.fictionNonfiction

  Object.keys(aggregationResult.aggregations.facets).forEach(facet => {
    const searchResultFacet = searchResult.aggregations.facets[ facet ]
    if (typeof searchResultFacet === 'object') {
      if (!searchResultFacet) {
        searchResult.aggregations.facets[ facet ] = aggregationResult.aggregations.facets[ facet ]
      } else {
        aggregationResult.aggregations.facets[ facet ].buckets.forEach(aggBucket => {
          if (!searchResultFacet.buckets.find(bucket => { return bucket.key === aggBucket.key })) {
            searchResultFacet.buckets.push({
              key: aggBucket.key,
              doc_count: 0,
              parents: { value: 0 }
            })
          }
        })
      }
    }
  })
  return searchResult
}
*/

module.exports = (app) => {
  app.get('/q', (request, response) => {
    const queryString = request.originalUrl.substr(request.originalUrl.indexOf('?') + 1)

    fetch('http://elasticsearch:9200/search/work/_search', {
      method: 'POST',
      body: JSON.stringify(searchBuilder.buildQuery(queryString))
    }).then(res => {
      if (res.ok) {
        return res.json()
      } else {
        return res.text().then(error => { return Promise.reject({ message: error, queryString: queryString }) })
      }
    }).then(json => response.status(200).send(json))
      .catch(error => {
        response.status(500).send({ message: error, queryString: queryString })
      })
  })
}
<|endoftext|>


<commit_before>/* RUN: LOG_LEVEL=off mocha test/18-exchange-promises.js */

var util = require('util');

module.exports = SeeAbove;

function SeeAbove() {}

SeeAbove.prototype.methodName1 = function(opts, callback) {
  if (opts.errorAs === 'callback') return callback(new Error('THIS IS JUST A TEST'));
  if (opts.errorAs === 'throw') throw new Error('THIS IS JUST A TEST');

  opts.number++;
  callback(null, opts);
};

SeeAbove.prototype.callCallbackTwice = function(opts, callback) {
  opts.number++;
  callback(null, opts);

  setTimeout(function() {
    callback(null, { number: opts.number + 1 });
  }, 100);
};

SeeAbove.prototype.fireAndForget = function() {
  //do nothing
};

SeeAbove.prototype.promiseMethod = util.promisify(function(opts, callback) {
  if (opts.errorAs === 'callback')
    return callback(new Error('THIS IS JUST A TEST WITH CALLBACK ERROR'));
  if (opts.errorAs === 'throw') throw new Error('THIS IS JUST A TEST THAT THROWS AN ERROR');

  opts.number++;
  callback(null, opts);
});

SeeAbove.prototype.promisePromiseCaller = util.promisify(function(opts, callback) {
  this.promiseMethod(opts)
    .then(function() {
      callback(null, opts);
    })
    .catch(callback);
});

SeeAbove.prototype.promiseCaller = function(opts, callback) {
  this.promiseMethod(opts)
    .then(function() {
      callback(null, opts);
    })
    .catch(callback);
};

SeeAbove.prototype.promiseReturnerNoCallback = function(opts) {
  return this.promiseMethod(opts);
};

SeeAbove.prototype.promiseReturner = util.promisify(function(opts, callback) {
  return this.promiseMethod(opts, callback);
});

SeeAbove.prototype.synchronousMethodHappnOrigin = function(opts, opts2, $happn, $origin) {
  if (!$happn) throw new Error('$happn is meant to exist');
  if (!$origin) throw new Error('$origin is meant to exist');

  return opts + opts2;
};

SeeAbove.prototype.synchronousMethod = function(opts, opts2) {
  return opts + opts2;
};

SeeAbove.prototype.$happner = {
  config: {
    component: {
      schema: {
        methods: {
          methodName1: {
            alias: 'ancientmoth'
          },
          synchronousMethod: {
            type: 'sync-promise' //NB - this is how you can wrap a synchronous method with a promise
          },
          synchronousMethodHappnOrigin: {
            type: 'sync-promise' //NB - this is how you can wrap a synchronous method with a promise
          },
          fireAndForget: {
            type: 'sync'
          }
        }
      }
    }
  }
};

if (global.TESTING_18) return; // When 'requiring' the module above,
// don't run the tests below
//.............
require('chai').should();

describe(
  require('../../__fixtures/utils/test_helper')
    .create()
    .testName(__filename, 3),
  function() {
    var Mesh = require('../../..');
    var mesh;

    this.timeout(120000);

    before(function(done) {
      global.TESTING_18 = true; //.............

      mesh = this.mesh = new Mesh();

      mesh.initialize(
        {
          dataLayer: {
            setOptions: {
              timeout: 1000
            }
          },
          util: {
            //logLevel: 'trace'
          },
          modules: {
            component: {
              path: __filename // .............
            }
          },
          components: {
            component: {}
          }
        },
        function(err) {
          delete global.TESTING_18; //.............
          if (err) return done(err);
          done();
        }
      );
    });

    after(function(done) {
      mesh.stop({ reconnect: false }, done);
    });

    it('supports non-promises in the exchange', function(done) {
      this.mesh.exchange.component.methodName1({ number: 1 }, function(err, res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports promises in the exchange', function(done) {
      this.mesh.exchange.component
        .methodName1({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('the promise implementation supports .catch from callback error', function(done) {
      this.mesh.exchange.component
        .methodName1({ errorAs: 'callback' })

        .then(function() {
          done(new Error('did not catch'));
        })

        .catch(function(err) {
          err.should.match(/THIS IS JUST A TEST/);
          done();
        });
    });

    it('the promise implementation supports .catch from thrown error', function(done) {
      this.mesh.exchange.component
        .methodName1({ errorAs: 'throw' })

        .then(function(res) {
          //eslint-disable-next-line
          console.log(res);
          done(new Error('did not catch'));
        })

        .catch(function(err) {
          err.should.match(/THIS IS JUST A TEST/);
          done();
        });
    });

    it('supports non-promises on the alias', function(done) {
      this.mesh.exchange.component.ancientmoth({ number: 1 }, function(err, res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports promises on the alias', function(done) {
      this.mesh.exchange.component
        .ancientmoth({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('supports fire and forget', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component.methodName1({ errorAs: 'throw' });
      done();
    });

    it('supports calling a synchronous method and getting a promise back', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .synchronousMethod(1, 2)

        .then(function(res) {
          res.should.eql(3);
          done();
        })

        .catch(function(err) {
          done(err);
        });
    });

    it('supports calling a synchronous method with $happn and $origin and getting a promise back', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .synchronousMethodHappnOrigin(1, 2)

        .then(function(res) {
          res.should.eql(3);
          done();
        })

        .catch(function(err) {
          done(err);
        });
    });

    it('supports calling a synchronous method fire and forget', function(done) {
      this.timeout(1500);
      this.mesh.exchange.component.synchronousMethod(1, 2);
      done();
    });

    it('supports exposing a promise on the exchange', function(done) {
      this.mesh.exchange.component
        .promiseMethod({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('supports calling a promise from a promise on the exchange', function(done) {
      this.timeout(1500);
      var _this = this;

      this.mesh.exchange.component
        .promisePromiseCaller({ number: 1 })

        .then(
          function(res) {
            res.should.eql({ number: 2 });
            done();
          }.bind(_this)
        );
    });

    it('supports calling a promise from a method on the exchange', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .promiseCaller({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('supports returning a promise from a method on the exchange', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component.promiseReturner({ number: 1 }).then(function(res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports returning a promise from a method on the exchange with no callback', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component.promiseReturnerNoCallback({ number: 1 }).then(function(res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports returning a promise from a method on the exchange that throws an error', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .promiseReturnerNoCallback({ number: 1, errorAs: 'throw' })
        .then(function() {
          done(new Error('should not get here'));
        })
        .catch(function(err) {
          err.message.should.eql('THIS IS JUST A TEST THAT THROWS AN ERROR');
          done();
        });
    });

    it('supports returning a promise from a method on the exchange that callbacks an error', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .promiseReturnerNoCallback({ number: 1, errorAs: 'callback' })
        .then(function() {
          done(new Error('should not get here'));
        })
        .catch(function(err) {
          err.message.should.eql('THIS IS JUST A TEST WITH CALLBACK ERROR');
          done();
        });
    });

    it('does not time out a sync function', function(done) {
      this.timeout(2500);

      this.mesh.exchange.component
        .fireAndForget({ number: 1 })
        .then(function() {
          // should never get here
          done(new Error('Should not get a result'));
        })
        .catch(function(err) {
          done(err);
        });

      setTimeout(done, 2000);
    });

    it('does not fire a callback twice', function(done) {
      this.timeout(2000);

      this.mesh.exchange.component.callCallbackTwice({ number: 1 }, function(err, result) {
        result.number.should.eql(2);
        setTimeout(done, 500);
      });
    });
  }
);
<commit_msg>SMC-734: fixed failing test exchange-promises<commit_after>/* RUN: LOG_LEVEL=off mocha test/18-exchange-promises.js */

var util = require('util');

module.exports = SeeAbove;

function SeeAbove() {}

SeeAbove.prototype.methodName1 = function(opts, callback) {
  if (opts.errorAs === 'callback') return callback(new Error('THIS IS JUST A TEST'));
  if (opts.errorAs === 'throw') throw new Error('THIS IS JUST A TEST');

  opts.number++;
  callback(null, opts);
};

SeeAbove.prototype.callCallbackTwice = function(opts, callback) {
  opts.number++;
  callback(null, opts);

  setTimeout(function() {
    callback(null, { number: opts.number + 1 });
  }, 100);
};

SeeAbove.prototype.fireAndForget = function() {
  //do nothing
};

SeeAbove.prototype.promiseMethod = util.promisify(function(opts, callback) {
  if (opts.errorAs === 'callback')
    return callback(new Error('THIS IS JUST A TEST WITH CALLBACK ERROR'));
  if (opts.errorAs === 'throw') throw new Error('THIS IS JUST A TEST THAT THROWS AN ERROR');

  opts.number++;
  callback(null, opts);
});

SeeAbove.prototype.promisePromiseCaller = util.promisify(function(opts, callback) {
  this.promiseMethod(opts)
    .then(function() {
      callback(null, opts);
    })
    .catch(callback);
});

SeeAbove.prototype.promiseCaller = function(opts, callback) {
  this.promiseMethod(opts)
    .then(function() {
      callback(null, opts);
    })
    .catch(callback);
};

SeeAbove.prototype.promiseReturnerNoCallback = function(opts) {
  return this.promiseMethod(opts);
};

SeeAbove.prototype.promiseReturner = util.promisify(function(opts, callback) {
  return this.promiseMethod(opts, callback);
});

SeeAbove.prototype.synchronousMethodHappnOrigin = function(opts, opts2, $happn, $origin) {
  if (!$happn) throw new Error('$happn is meant to exist');
  if (!$origin) throw new Error('$origin is meant to exist');

  return opts + opts2;
};

SeeAbove.prototype.synchronousMethod = function(opts, opts2) {
  return opts + opts2;
};

SeeAbove.prototype.$happner = {
  config: {
    component: {
      schema: {
        methods: {
          methodName1: {
            alias: 'ancientmoth'
          },
          synchronousMethod: {
            type: 'sync-promise' //NB - this is how you can wrap a synchronous method with a promise
          },
          synchronousMethodHappnOrigin: {
            type: 'sync-promise' //NB - this is how you can wrap a synchronous method with a promise
          },
          fireAndForget: {
            type: 'sync'
          }
        }
      }
    }
  }
};

if (global.TESTING_18) return; // When 'requiring' the module above,
// don't run the tests below
//.............
require('chai').should();

describe(
  require('../../__fixtures/utils/test_helper')
    .create()
    .testName(__filename, 3),
  function() {
    var Mesh = require('../../..');
    var mesh;

    this.timeout(120000);

    before(function(done) {
      global.TESTING_18 = true; //.............

      mesh = this.mesh = new Mesh();

      mesh.initialize(
        {
          dataLayer: {
            setOptions: {
              timeout: 1000
            }
          },
          util: {
            //logLevel: 'trace'
          },
          modules: {
            component: {
              path: __filename // .............
            }
          },
          components: {
            component: {}
          }
        },
        function(err) {
          delete global.TESTING_18; //.............
          if (err) return done(err);
          done();
        }
      );
    });

    after(function(done) {
      mesh.stop({ reconnect: false }, done);
    });

    it('supports non-promises in the exchange', function(done) {
      this.mesh.exchange.component.methodName1({ number: 1 }, function(err, res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports promises in the exchange', function(done) {
      this.mesh.exchange.component
        .methodName1({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('the promise implementation supports .catch from callback error', function(done) {
      this.mesh.exchange.component
        .methodName1({ errorAs: 'callback' })

        .then(function() {
          done(new Error('did not catch'));
        })

        .catch(function(err) {
          err.should.match(/THIS IS JUST A TEST/);
          done();
        });
    });

    it('the promise implementation supports .catch from thrown error', function(done) {
      this.mesh.exchange.component
        .methodName1({ errorAs: 'throw' })

        .then(function(res) {
          //eslint-disable-next-line
          console.log(res);
          done(new Error('did not catch'));
        })

        .catch(function(err) {
          err.should.match(/THIS IS JUST A TEST/);
          done();
        });
    });

    it('supports non-promises on the alias', function(done) {
      this.mesh.exchange.component.ancientmoth({ number: 1 }, function(err, res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports promises on the alias', function(done) {
      this.mesh.exchange.component
        .ancientmoth({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('supports fire and forget', function(done) {
      this.timeout(1500);
      try {
        this.mesh.exchange.component.methodName1({ errorAs: 'throw' });
      } catch (err) {
        err.should.match(/THIS IS JUST A TEST/);
      }
      done();
    });

    it('supports calling a synchronous method and getting a promise back', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .synchronousMethod(1, 2)

        .then(function(res) {
          res.should.eql(3);
          done();
        })

        .catch(function(err) {
          done(err);
        });
    });

    it('supports calling a synchronous method with $happn and $origin and getting a promise back', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .synchronousMethodHappnOrigin(1, 2)

        .then(function(res) {
          res.should.eql(3);
          done();
        })

        .catch(function(err) {
          done(err);
        });
    });

    it('supports calling a synchronous method fire and forget', function(done) {
      this.timeout(1500);
      this.mesh.exchange.component.synchronousMethod(1, 2);
      done();
    });

    it('supports exposing a promise on the exchange', function(done) {
      this.mesh.exchange.component
        .promiseMethod({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('supports calling a promise from a promise on the exchange', function(done) {
      this.timeout(1500);
      var _this = this;

      this.mesh.exchange.component
        .promisePromiseCaller({ number: 1 })

        .then(
          function(res) {
            res.should.eql({ number: 2 });
            done();
          }.bind(_this)
        );
    });

    it('supports calling a promise from a method on the exchange', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .promiseCaller({ number: 1 })

        .then(function(res) {
          res.should.eql({ number: 2 });
          done();
        });
    });

    it('supports returning a promise from a method on the exchange', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component.promiseReturner({ number: 1 }).then(function(res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports returning a promise from a method on the exchange with no callback', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component.promiseReturnerNoCallback({ number: 1 }).then(function(res) {
        res.should.eql({ number: 2 });
        done();
      });
    });

    it('supports returning a promise from a method on the exchange that throws an error', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .promiseReturnerNoCallback({ number: 1, errorAs: 'throw' })
        .then(function() {
          done(new Error('should not get here'));
        })
        .catch(function(err) {
          err.message.should.eql('THIS IS JUST A TEST THAT THROWS AN ERROR');
          done();
        });
    });

    it('supports returning a promise from a method on the exchange that callbacks an error', function(done) {
      this.timeout(1500);

      this.mesh.exchange.component
        .promiseReturnerNoCallback({ number: 1, errorAs: 'callback' })
        .then(function() {
          done(new Error('should not get here'));
        })
        .catch(function(err) {
          err.message.should.eql('THIS IS JUST A TEST WITH CALLBACK ERROR');
          done();
        });
    });

    it('does not time out a sync function', function(done) {
      this.timeout(2500);

      this.mesh.exchange.component
        .fireAndForget({ number: 1 })
        .then(function() {
          // should never get here
          done(new Error('Should not get a result'));
        })
        .catch(function(err) {
          done(err);
        });

      setTimeout(done, 2000);
    });

    it('does not fire a callback twice', function(done) {
      this.timeout(2000);

      this.mesh.exchange.component.callCallbackTwice({ number: 1 }, function(err, result) {
        result.number.should.eql(2);
        setTimeout(done, 500);
      });
    });
  }
);
<|endoftext|>


<commit_before>var _        = require('underscore');
var fs       = require('fs');
var getSlug  = require('speakingurl');
var path     = require('path');

var names = _.chain(fs.readFileSync(path.join(__dirname, 'node_modules/seanherron_Gov-Webicons/README.markdown'), 'utf8').split('\n'))
	.filter(function(line) {
		return line.match(/^\* /);
	})
	.invoke('substring', 2)
	.splice(34, 0, 'United States Social Security Administration')
	.value();

module.exports = _.chain(fs.readdirSync(path.join(__dirname, 'node_modules/seanherron_Gov-Webicons/images')))
	.filter(function(file) {
		return file.match(/\.svg$/);
	})
	.map(function(file, i) {
		file = file.replace(/\.svg$/, '');
		return {
			id:          getSlug(names[i] || file),
			name:        names[i] || file,
			keywords:    ['government', 'america', 'states', 'united', 'usa'],
			contributor: {
				name:      'Sean Herron',
				shortname: 'seanherron'
			},
			source: {
				name:      'Gov-Webicons',
				shortname: getSlug('Gov-Webicons'),
				url:       'https://github.com/seanherron/Gov-Webicons'
			},
			svg: {
				path: {
					directory: path.join(__dirname, 'node_modules/seanherron_Gov-Webicons/images'),
					filename:  file + '.svg'
				}
			}
		};
	})
	.value();
<commit_msg>make the government names better<commit_after>var _        = require('underscore');
var fs       = require('fs');
var getSlug  = require('speakingurl');
var path     = require('path');

var names = _.chain(fs.readFileSync(path.join(__dirname, 'node_modules/seanherron_Gov-Webicons/README.markdown'), 'utf8').split('\n'))
	.filter(function(line) {
		return line.match(/^\* /);
	})
	.invoke('substring', 2)
	.splice(34, 0, 'United States Social Security Administration')
	.value();

module.exports = _.chain(fs.readdirSync(path.join(__dirname, 'node_modules/seanherron_Gov-Webicons/images')))
	.filter(function(file) {
		return file.match(/\.svg$/);
	})
	.map(function(file, i) {
		file = file.replace(/\.svg$/, '');
		var shortname = file.replace(/gov-/, '');
		return {
			id:          getSlug(shortname),
			name:        names[i] + (names[i].toLowerCase().includes(shortname.replace('-', ' ')) ? '' : (' (' + shortname.toUpperCase() + ')')),
			keywords:    ['government', 'america', 'states', 'united', 'usa'],
			contributor: {
				name:      'Sean Herron',
				shortname: 'seanherron'
			},
			source: {
				name:      'Gov-Webicons',
				shortname: getSlug('Gov-Webicons'),
				url:       'https://github.com/seanherron/Gov-Webicons'
			},
			svg: {
				path: {
					directory: path.join(__dirname, 'node_modules/seanherron_Gov-Webicons/images'),
					filename:  file + '.svg'
				}
			}
		};
	})
	.value();
<|endoftext|>