<commit_before>module.exports = function PgConnectionArgFilterOperatorsPlugin(
  builder,
  { connectionFilterUsesShortNames = false } = {}
) {
  builder.hook(
    "init",
    (
      _,
      {
        getTypeByName,
        addConnectionFilterOperator,
        pgSql: sql,
        graphql: { GraphQLBoolean, GraphQLList, GraphQLNonNull },
      }
    ) => {
      addConnectionFilterOperator(
        "null",
        "If set to true, checks for null values.  If set to false, checks for non-null values.",
        () => GraphQLBoolean,
        (identifier, val) =>
          sql.query`${identifier} ${val
            ? sql.query`IS NULL`
            : sql.query`IS NOT NULL`}`
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "eq" : "equalTo",
        "Checks for values equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} = ${val}`;
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "ne" : "notEqualTo",
        "Checks for values not equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} <> ${val}`;
        }
      );
      addConnectionFilterOperator(
        "distinctFrom",
        "Checks for values not equal to this value, treating null like an ordinary value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} IS DISTINCT FROM ${val}`;
        }
      );
      addConnectionFilterOperator(
        "notDistinctFrom",
        "Checks for values equal to this value, treating null like an ordinary value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} IS NOT DISTINCT FROM ${val}`;
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "lt" : "lessThan",
        "Checks for values less than this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} < ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "lte" : "lessThanOrEqualTo",
        "Checks for values less than or equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} <= ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "gt" : "greaterThan",
        "Checks for values greater than this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} > ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "gte" : "greaterThanOrEqualTo",
        "Checks for values greater than or equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} >= ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "in" : "in",
        "Checks for values in this list.",
        typeName =>
          new GraphQLList(new GraphQLNonNull(getTypeByName(typeName))),
        (identifier, val) => {
          return sql.query`${identifier} IN ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "nin" : "notIn",
        "Checks for values not in this list.",
        typeName =>
          new GraphQLList(new GraphQLNonNull(getTypeByName(typeName))),
        (identifier, val) => {
          return sql.query`${identifier} NOT IN ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "cont" : "contains",
        "Checks for strings containing this string.  Case sensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} like ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `%${input}%`,
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "conti" : "containsInsensitive",
        "Checks for strings containing this value.  Case insensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} ilike ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `%${input}%`,
        }
      );
      return _;
    }
  );
};
<commit_msg>added case (in)sensitive starts/endswith as well as raw like/ilike.  Wildcards NOT yet escaped.<commit_after>module.exports = function PgConnectionArgFilterOperatorsPlugin(
  builder,
  { connectionFilterUsesShortNames = false } = {}
) {
  builder.hook(
    "init",
    (
      _,
      {
        getTypeByName,
        addConnectionFilterOperator,
        pgSql: sql,
        graphql: { GraphQLBoolean, GraphQLList, GraphQLNonNull },
      }
    ) => {
      addConnectionFilterOperator(
        "null",
        "If set to true, checks for null values.  If set to false, checks for non-null values.",
        () => GraphQLBoolean,
        (identifier, val) =>
          sql.query`${identifier} ${val
            ? sql.query`IS NULL`
            : sql.query`IS NOT NULL`}`
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "eq" : "equalTo",
        "Checks for values equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} = ${val}`;
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "ne" : "notEqualTo",
        "Checks for values not equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} <> ${val}`;
        }
      );
      addConnectionFilterOperator(
        "distinctFrom",
        "Checks for values not equal to this value, treating null like an ordinary value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} IS DISTINCT FROM ${val}`;
        }
      );
      addConnectionFilterOperator(
        "notDistinctFrom",
        "Checks for values equal to this value, treating null like an ordinary value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} IS NOT DISTINCT FROM ${val}`;
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "lt" : "lessThan",
        "Checks for values less than this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} < ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "lte" : "lessThanOrEqualTo",
        "Checks for values less than or equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} <= ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "gt" : "greaterThan",
        "Checks for values greater than this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} > ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "gte" : "greaterThanOrEqualTo",
        "Checks for values greater than or equal to this value.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} >= ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "in" : "in",
        "Checks for values in this list.",
        typeName =>
          new GraphQLList(new GraphQLNonNull(getTypeByName(typeName))),
        (identifier, val) => {
          return sql.query`${identifier} IN ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "nin" : "notIn",
        "Checks for values not in this list.",
        typeName =>
          new GraphQLList(new GraphQLNonNull(getTypeByName(typeName))),
        (identifier, val) => {
          return sql.query`${identifier} NOT IN ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
            "Int",
            "Float",
            "Datetime",
            "Date",
            "Time",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "cont" : "contains",
        "Checks for strings containing this string.  Case sensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} like ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `%${input}%`,
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "conti" : "containsInsensitive",
        "Checks for strings containing this value.  Case insensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} ilike ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `%${input}%`,
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "starts" : "startsWith",
        "Checks for strings starting with this string.  Case sensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} like ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `${input}%`,
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "startsi" : "startsWithInsensitive",
        "Checks for strings starting with this string.  Case sensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} ilike ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `${input}%`,
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "ends" : "endsWith",
        "Checks for strings ending with this string.  Case sensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} like ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `${input}%`,
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "endsi" : "endsWithInsensitive",
        "Checks for strings ending with this string.  Case insensitive.",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} ilike ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
          inputResolver: input => `%${input}`,
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "like" : "like",
        "Raw SQL 'like', wildcards must be present and are not escaped",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} like ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
        }
      );
      addConnectionFilterOperator(
        connectionFilterUsesShortNames ? "ilike" : "ilike",
        "Raw SQL 'ilike', wildcards must be present and are not escaped",
        typeName => getTypeByName(typeName),
        (identifier, val) => {
          return sql.query`${identifier} ilike ${val}`;
        },
        {
          allowedFieldTypes: [
            "String",
          ],
        }
      );
      return _;
    }
  );
};
<|endoftext|>


<commit_before>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015  John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function EquipmentInventoryController($scope,NumberOfYears,DeleteEquipmentInventory, UserFacilityList, EquipmentInventories, ManageEquipmentInventoryProgramList, ManageEquipmentInventoryFacilityProgramList, EquipmentTypesByProgram, EquipmentOperationalStatus, $routeParams, messageService, UpdateEquipmentInventoryStatus, $timeout, SaveEquipmentInventory,localStorageService,$dialog) {

  $scope.loadPrograms = function (initialLoad) {
    // Get home facility for user
    UserFacilityList.get({}, function (data) {
      $scope.myFacility = data.facilityList[0];
      if ($scope.myFacility) {
        // Home facility found, show home facility
        $scope.facilityDisplayName = $scope.myFacility.name;

        // Home facility found and my facility type selected, get home facility programs
        if ($scope.selectedType === "0") {
          ManageEquipmentInventoryFacilityProgramList.get({facilityId: $scope.myFacility.id}, function (data) {
            $scope.programs = data.programs;
            if (initialLoad && $routeParams.program) {
              $scope.selectedProgram = _.findWhere($scope.programs, {id: parseInt($routeParams.program,10)});
              $scope.loadEquipmentTypes(initialLoad);
            } else if ($scope.programs.length === 1) {
              $scope.selectedProgram = $scope.programs[0];
              $scope.loadEquipmentTypes();
            }
          }, {});
        }
      } else {
        // Home facility not found, show none assigned message
        $scope.facilityDisplayName = messageService.get("label.none.assigned");
      }
    }, {});

    // Supervised facility type selected, get supervised facility programs
    if ($scope.selectedType === "1") {
      ManageEquipmentInventoryProgramList.get({}, function (data) {
        $scope.programs = data.programs;
        if (initialLoad && $routeParams.program) {
          $scope.selectedProgram = _.findWhere($scope.programs, {id: parseInt($routeParams.program, 10)});
          $scope.loadEquipmentTypes(initialLoad);
        } else if ($scope.programs.length === 1) {
          $scope.selectedProgram = $scope.programs[0];
          $scope.loadEquipmentTypes();
        }
      }, {});
    }
  };

  $scope.loadEquipmentTypes = function (initialLoad) {
    EquipmentTypesByProgram.get({programId: $scope.selectedProgram.id}, function (data) {
      $scope.equipmentTypes = data.equipment_types;
      if (initialLoad && $routeParams.equipmentType) {
        $scope.selectedEquipmentType = _.findWhere($scope.equipmentTypes, {id: parseInt($routeParams.equipmentType,10)});
        $scope.loadInventory();
      } else if ($scope.equipmentTypes.length === 1) {
        $scope.selectedEquipmentType = $scope.equipmentTypes[0];
        $scope.loadInventory();
      }
    }, {});
  };

  $scope.loadInventory = function () {
    if ($scope.selectedProgram && $scope.selectedEquipmentType) {
      EquipmentInventories.get({
        typeId: $scope.selectedType,
        programId: $scope.selectedProgram.id,
        equipmentTypeId: $scope.selectedEquipmentType.id,
        page: $scope.page
      }, function (data) {
        $scope.inventory = data.inventory;

        var groupedInventoryData = _.groupBy($scope.inventory,function(item){
              return item.equipment.designation.name;
            });

        $scope.inventoryList = $.map(groupedInventoryData, function(value, index) {
          return {"designation":index,"inventory":value};
        });

        $scope.pagination = data.pagination;
        $scope.totalItems = $scope.pagination.totalRecords;
        $scope.currentPage = $scope.pagination.page;
        $scope.groups = _.groupBy($scope.inventory, function (item) {
          return item.facility.geographicZone.parent.name;
        });
        for (var prop in $scope.groups) {
          $scope.groups[prop] = _.groupBy($scope.groups[prop], getGeographicZone);
        }
      });
    }
  };

  $scope.changeFacilityType = function () {
    $scope.programs = undefined;
    $scope.selectedProgram = undefined;
    $scope.equipmentTypes = undefined;
    $scope.selectedEquipmentType = undefined;

    $scope.loadPrograms();
  };

  $scope.changeProgram = function () {
    $scope.equipmentTypes = undefined;
    $scope.selectedEquipmentType = undefined;

    $scope.loadEquipmentTypes();
  };

  $scope.updateStatus = function (item) {
    // Create original inventory item to use later if user cancels
    $scope.origModalItem = angular.copy(item);
    $scope.origModalItem.operationalStatusId = $scope.origModalItem.prevStatusId;

    // updateStatus is called on dropdown load, so only do something if previous value set and is different
    if (item.prevStatusId && item.prevStatusId !== item.operationalStatusId) {
      var operationalStatus = _.findWhere($scope.operationalStatusList, {id: parseInt(item.operationalStatusId, 10)});
      // If status is "bad", open modal, otherwise just save to the server
      if (operationalStatus.isBad) {
        $scope.notFunctionalModal = true;
        $scope.modalItem = item;

        $scope.checkForBadFunctionalStatus($scope.modalItem.notFunctionalStatusId);
        $scope.prevStatusId = item.prevStatusId; // Need to save previous since item.prevStatusId gets overwritten
                                                 // at the end of this function
      } else {
        item.notFunctionalStatusId = null; // Reset for the UI
        UpdateEquipmentInventoryStatus.save({}, item, function () {
          // Success
          item.showSuccess = true;
          $timeout(function () {
            item.showSuccess = false;
          }, 3000);
        });
      }
    }

    // Set a previous value to compare with
    item.prevStatusId = item.operationalStatusId;
  };

  $scope.checkForBadFunctionalStatus = function (statusId) {
    if (statusId) {

      var notFunctionalStatus = _.findWhere($scope.notFunctionalStatusList, {id: parseInt(statusId, 10)});

      $scope.modalItem.badFunctionalStatusSelected = notFunctionalStatus.isBad;
      $scope.modalItem.needSpareFunctionalStatusSelected = notFunctionalStatus.needSparePart;
    }
  };
  $scope.saveModal = function () {
    $scope.modalError = '';
    if (!$scope.notFunctionalForm.$invalid) {
      SaveEquipmentInventory.save($scope.modalItem, function () {
        // Success
        $scope.notFunctionalModal = false;
        $scope.modalItem.badFunctionalStatusSelected = false;
        $scope.modalItem.needSpareFunctionalStatusSelected = false;
        $scope.modalItem.showSuccess = true;
        $timeout(function () {
          $scope.modalItem.showSuccess = false;
        }, 3000);
      }, function (data) {
        $scope.modalError = data.error;
      });
    } else {
      $scope.modalError = messageService.get('message.equipment.inventory.data.invalid');
    }
  };

  $scope.closeModal = function () {
    $scope.notFunctionalModal = false;

    // Reset inventory with original inventory item
    // Doing this with map because underscore version doesn't support findIndex
    $scope.inventory = _.map($scope.inventory, function (obj) {
      if (obj.id === $scope.modalItem.id) {
        return $scope.origModalItem;
      } else {
        return obj;
      }
    });

    // Reset other values
    $scope.modalItem.needSpareFunctionalStatusSelected = false;
    $scope.modalItem.badFunctionalStatusSelected = false;
    $scope.modalError = '';
  };

  $scope.getAge = function (yearOfInstallation) {
    if (yearOfInstallation) {
      return (new Date().getFullYear()) - yearOfInstallation;
    } else {
      return null;
    }
  };

  $scope.getReplacementYear = function (yearOfInstallation) {

    if (yearOfInstallation) {

      return yearOfInstallation + parseInt(NumberOfYears,10);

    } else {
      return null;
    }
  };

  $scope.updateTemperatureStatusModal = function (equipment){
    if(!isUndefined(equipment)){
      $scope.temperatureStatusModal = true;
       $scope.coldChain = equipment;
    }

  };

  $scope.closeColdChainTemperatureModal= function () {
    $scope.temperatureStatusModal = false;
  };

  $scope.$watch('currentPage', function () {
    if ($scope.currentPage > 0) {
      $scope.page = $scope.currentPage;
      $scope.loadInventory();
    }
  });
  function getGeographicZone(item) {
    return item.facility.geographicZone.name;
  }

  $scope.selectedType = $routeParams.from || "0";
  $scope.page = $routeParams.page || "1";
  $scope.loadPrograms(true);

  EquipmentOperationalStatus.get(function(data){
    $scope.operationalStatusList = _.where(data.status, {category: 'CCE'});
    $scope.notFunctionalStatusList = _.where(data.status, {category: 'CCE Not Functional'});
  });

  $scope.deleteInventory=function(id){
      var callBack=function(result){
        if(result){
           DeleteEquipmentInventory.get({inventoryId:id},function(data){
                 $scope.loadInventory();
           });
         }
       }
        var options = {
                           id: "confirmDialog",
                           header: "label.confirm.delete.equipment.inventory",
                           body: "msg.question.delete.equipment.inventory.confirmation"
                       };
      OpenLmisDialog.newDialog(options, callBack, $dialog);
  }

  $scope.loadRights = function () {
        $scope.rights = localStorageService.get(localStorageKeys.RIGHT);
  }();

  $scope.hasPermission = function (permission) {
              if ($scope.rights !== undefined && $scope.rights !== null) {
                var rights = JSON.parse($scope.rights);
                var rightNames = _.pluck(rights, 'name');
                return rightNames.indexOf(permission) > -1;
              }
              return false;
  };

}

EquipmentInventoryController.resolve = {

  NumberOfYears: function ($q, $timeout, SettingsByKey) {
    var deferred = $q.defer();
    $timeout(function () {

      SettingsByKey.get({key: 'YEARS_TO_REPLACE_EQUIPMENT'}, function (data) {
        if (isUndefined(data.settings) || isUndefined(data.settings.value)) {
          deferred.resolve(10);
        } else {

          deferred.resolve(data.settings.value);
        }

      });

    }, 100);

    return deferred.promise;

  }

};
<commit_msg>Fix jsHint<commit_after>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015  John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function EquipmentInventoryController($scope,NumberOfYears,DeleteEquipmentInventory, UserFacilityList, EquipmentInventories, ManageEquipmentInventoryProgramList, ManageEquipmentInventoryFacilityProgramList, EquipmentTypesByProgram, EquipmentOperationalStatus, $routeParams, messageService, UpdateEquipmentInventoryStatus, $timeout, SaveEquipmentInventory,localStorageService,$dialog) {

  $scope.loadPrograms = function (initialLoad) {
    // Get home facility for user
    UserFacilityList.get({}, function (data) {
      $scope.myFacility = data.facilityList[0];
      if ($scope.myFacility) {
        // Home facility found, show home facility
        $scope.facilityDisplayName = $scope.myFacility.name;

        // Home facility found and my facility type selected, get home facility programs
        if ($scope.selectedType === "0") {
          ManageEquipmentInventoryFacilityProgramList.get({facilityId: $scope.myFacility.id}, function (data) {
            $scope.programs = data.programs;
            if (initialLoad && $routeParams.program) {
              $scope.selectedProgram = _.findWhere($scope.programs, {id: parseInt($routeParams.program,10)});
              $scope.loadEquipmentTypes(initialLoad);
            } else if ($scope.programs.length === 1) {
              $scope.selectedProgram = $scope.programs[0];
              $scope.loadEquipmentTypes();
            }
          }, {});
        }
      } else {
        // Home facility not found, show none assigned message
        $scope.facilityDisplayName = messageService.get("label.none.assigned");
      }
    }, {});

    // Supervised facility type selected, get supervised facility programs
    if ($scope.selectedType === "1") {
      ManageEquipmentInventoryProgramList.get({}, function (data) {
        $scope.programs = data.programs;
        if (initialLoad && $routeParams.program) {
          $scope.selectedProgram = _.findWhere($scope.programs, {id: parseInt($routeParams.program, 10)});
          $scope.loadEquipmentTypes(initialLoad);
        } else if ($scope.programs.length === 1) {
          $scope.selectedProgram = $scope.programs[0];
          $scope.loadEquipmentTypes();
        }
      }, {});
    }
  };

  $scope.loadEquipmentTypes = function (initialLoad) {
    EquipmentTypesByProgram.get({programId: $scope.selectedProgram.id}, function (data) {
      $scope.equipmentTypes = data.equipment_types;
      if (initialLoad && $routeParams.equipmentType) {
        $scope.selectedEquipmentType = _.findWhere($scope.equipmentTypes, {id: parseInt($routeParams.equipmentType,10)});
        $scope.loadInventory();
      } else if ($scope.equipmentTypes.length === 1) {
        $scope.selectedEquipmentType = $scope.equipmentTypes[0];
        $scope.loadInventory();
      }
    }, {});
  };

  $scope.loadInventory = function () {
    if ($scope.selectedProgram && $scope.selectedEquipmentType) {
      EquipmentInventories.get({
        typeId: $scope.selectedType,
        programId: $scope.selectedProgram.id,
        equipmentTypeId: $scope.selectedEquipmentType.id,
        page: $scope.page
      }, function (data) {
        $scope.inventory = data.inventory;

        var groupedInventoryData = _.groupBy($scope.inventory,function(item){
              return item.equipment.designation.name;
            });

        $scope.inventoryList = $.map(groupedInventoryData, function(value, index) {
          return {"designation":index,"inventory":value};
        });

        $scope.pagination = data.pagination;
        $scope.totalItems = $scope.pagination.totalRecords;
        $scope.currentPage = $scope.pagination.page;
        $scope.groups = _.groupBy($scope.inventory, function (item) {
          return item.facility.geographicZone.parent.name;
        });
        for (var prop in $scope.groups) {
          $scope.groups[prop] = _.groupBy($scope.groups[prop], getGeographicZone);
        }
      });
    }
  };

  $scope.changeFacilityType = function () {
    $scope.programs = undefined;
    $scope.selectedProgram = undefined;
    $scope.equipmentTypes = undefined;
    $scope.selectedEquipmentType = undefined;

    $scope.loadPrograms();
  };

  $scope.changeProgram = function () {
    $scope.equipmentTypes = undefined;
    $scope.selectedEquipmentType = undefined;

    $scope.loadEquipmentTypes();
  };

  $scope.updateStatus = function (item) {
    // Create original inventory item to use later if user cancels
    $scope.origModalItem = angular.copy(item);
    $scope.origModalItem.operationalStatusId = $scope.origModalItem.prevStatusId;

    // updateStatus is called on dropdown load, so only do something if previous value set and is different
    if (item.prevStatusId && item.prevStatusId !== item.operationalStatusId) {
      var operationalStatus = _.findWhere($scope.operationalStatusList, {id: parseInt(item.operationalStatusId, 10)});
      // If status is "bad", open modal, otherwise just save to the server
      if (operationalStatus.isBad) {
        $scope.notFunctionalModal = true;
        $scope.modalItem = item;

        $scope.checkForBadFunctionalStatus($scope.modalItem.notFunctionalStatusId);
        $scope.prevStatusId = item.prevStatusId; // Need to save previous since item.prevStatusId gets overwritten
                                                 // at the end of this function
      } else {
        item.notFunctionalStatusId = null; // Reset for the UI
        UpdateEquipmentInventoryStatus.save({}, item, function () {
          // Success
          item.showSuccess = true;
          $timeout(function () {
            item.showSuccess = false;
          }, 3000);
        });
      }
    }

    // Set a previous value to compare with
    item.prevStatusId = item.operationalStatusId;
  };

  $scope.checkForBadFunctionalStatus = function (statusId) {
    if (statusId) {

      var notFunctionalStatus = _.findWhere($scope.notFunctionalStatusList, {id: parseInt(statusId, 10)});

      $scope.modalItem.badFunctionalStatusSelected = notFunctionalStatus.isBad;
      $scope.modalItem.needSpareFunctionalStatusSelected = notFunctionalStatus.needSparePart;
    }
  };
  $scope.saveModal = function () {
    $scope.modalError = '';
    if (!$scope.notFunctionalForm.$invalid) {
      SaveEquipmentInventory.save($scope.modalItem, function () {
        // Success
        $scope.notFunctionalModal = false;
        $scope.modalItem.badFunctionalStatusSelected = false;
        $scope.modalItem.needSpareFunctionalStatusSelected = false;
        $scope.modalItem.showSuccess = true;
        $timeout(function () {
          $scope.modalItem.showSuccess = false;
        }, 3000);
      }, function (data) {
        $scope.modalError = data.error;
      });
    } else {
      $scope.modalError = messageService.get('message.equipment.inventory.data.invalid');
    }
  };

  $scope.closeModal = function () {
    $scope.notFunctionalModal = false;

    // Reset inventory with original inventory item
    // Doing this with map because underscore version doesn't support findIndex
    $scope.inventory = _.map($scope.inventory, function (obj) {
      if (obj.id === $scope.modalItem.id) {
        return $scope.origModalItem;
      } else {
        return obj;
      }
    });

    // Reset other values
    $scope.modalItem.needSpareFunctionalStatusSelected = false;
    $scope.modalItem.badFunctionalStatusSelected = false;
    $scope.modalError = '';
  };

  $scope.getAge = function (yearOfInstallation) {
    if (yearOfInstallation) {
      return (new Date().getFullYear()) - yearOfInstallation;
    } else {
      return null;
    }
  };

  $scope.getReplacementYear = function (yearOfInstallation) {

    if (yearOfInstallation) {

      return yearOfInstallation + parseInt(NumberOfYears,10);

    } else {
      return null;
    }
  };

  $scope.updateTemperatureStatusModal = function (equipment){
    if(!isUndefined(equipment)){
      $scope.temperatureStatusModal = true;
       $scope.coldChain = equipment;
    }

  };

  $scope.closeColdChainTemperatureModal= function () {
    $scope.temperatureStatusModal = false;
  };

  $scope.$watch('currentPage', function () {
    if ($scope.currentPage > 0) {
      $scope.page = $scope.currentPage;
      $scope.loadInventory();
    }
  });
  function getGeographicZone(item) {
    return item.facility.geographicZone.name;
  }

  $scope.selectedType = $routeParams.from || "0";
  $scope.page = $routeParams.page || "1";
  $scope.loadPrograms(true);

  EquipmentOperationalStatus.get(function(data){
    $scope.operationalStatusList = _.where(data.status, {category: 'CCE'});
    $scope.notFunctionalStatusList = _.where(data.status, {category: 'CCE Not Functional'});
  });

  $scope.deleteInventory=function(id){
      var callBack=function(result){
        if(result){
           DeleteEquipmentInventory.get({inventoryId:id},function(data){
                 $scope.loadInventory();
           });
         }
       };
        var options = {
                           id: "confirmDialog",
                           header: "label.confirm.delete.equipment.inventory",
                           body: "msg.question.delete.equipment.inventory.confirmation"
                       };
      OpenLmisDialog.newDialog(options, callBack, $dialog);
  };

  $scope.loadRights = function () {
        $scope.rights = localStorageService.get(localStorageKeys.RIGHT);
  }();

  $scope.hasPermission = function (permission) {
              if ($scope.rights !== undefined && $scope.rights !== null) {
                var rights = JSON.parse($scope.rights);
                var rightNames = _.pluck(rights, 'name');
                return rightNames.indexOf(permission) > -1;
              }
              return false;
  };

}

EquipmentInventoryController.resolve = {

  NumberOfYears: function ($q, $timeout, SettingsByKey) {
    var deferred = $q.defer();
    $timeout(function () {

      SettingsByKey.get({key: 'YEARS_TO_REPLACE_EQUIPMENT'}, function (data) {
        if (isUndefined(data.settings) || isUndefined(data.settings.value)) {
          deferred.resolve(10);
        } else {

          deferred.resolve(data.settings.value);
        }

      });

    }, 100);

    return deferred.promise;

  }

};
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
var Store = require("../storage/file");

var Logger = module.exports;

/* Every line in the log should contain:
    * timestamp
    * public key of initiator
    * the action
    * the event's tag
*/
var messageTemplate = function (type, time, tag, info) {
    return JSON.stringify([type.toUpperCase(), time, tag, info]);
};

var write = function (ctx, content) {
    if (!ctx.store) { return; }
    ctx.store.log(ctx.channelName, content);
};

// various degrees of logging
const logLevels = ['silly', 'debug', 'verbose', 'feedback', 'info', 'warn', 'error'];

var handlers = {
    silly: function (ctx, time, tag, info) {
        console.log('[SILLY]', time, tag, info);
    },
    debug: function (ctx, time, tag, info) {
        console.log('[DEBUG]', time, tag, info);
    },
    verbose: function (ctx, time, tag, info) {
        console.log('[VERBOSE]', time, tag, info);
    },
    feedback: function (ctx, time, tag, info) {
        console.log('[FEEDBACK]', time, tag, info);
    },
    info: function (ctx, time, tag, info) {
        console.info('[INFO]', time, tag, info);
    },
    warn: function (ctx, time, tag, info) {
        console.warn('[WARN]', time, tag, info);
    },
    error: function (ctx, time, tag, info) {
        console.error('[ERROR]', time, tag, info);
    }
};

var noop = function () {};

var createLogType = function (ctx, type) {
    if (logLevels.indexOf(type) < logLevels.indexOf(ctx.logLevel)) {
        return noop;
    }
    return function (tag, info) {
        var time = new Date().toISOString();
        var content;
        try {
            content = messageTemplate(type, time, tag, info);
        } catch (e) {
            return;
        }
        if (ctx.logToStdout && typeof(handlers[type]) === 'function') {
            handlers[type](ctx, time, tag, info);
        }
        write(ctx, content);
    };
};

var createMethods = function (ctx) {
    var log = {};
    logLevels.forEach(function (type) {
        log[type] = createLogType(ctx, type);
    });
    return log;
};

Logger.create = function (config, cb) {
    if (typeof(config.logLevel) !== 'string') {
        config.logLevel = 'info';
    }

    var date = new Date();
    var launchTime = ('' + date.getUTCFullYear()).slice(-2) + date.toISOString();

    var ctx = {
        channelName: launchTime,
        logFeedback: Boolean(config.logFeedback),
        logLevel: config.logLevel,
        logToStdout: config.logToStdout,
    };

    if (!config.logPath) {
        console.log("No logPath configured. Logging to file disabled");
        return void cb(Object.freeze(createMethods(ctx)));
    }

    Store.create({
        filePath: config.logPath,
    }, function (store) {
        ctx.store = store;
        cb(Object.freeze(createMethods(ctx)));
    });
};

<commit_msg>reorder logLevel priority<commit_after>/*jshint esversion: 6 */
var Store = require("../storage/file");

var Logger = module.exports;

/* Every line in the log should contain:
    * timestamp
    * public key of initiator
    * the action
    * the event's tag
*/
var messageTemplate = function (type, time, tag, info) {
    return JSON.stringify([type.toUpperCase(), time, tag, info]);
};

var write = function (ctx, content) {
    if (!ctx.store) { return; }
    ctx.store.log(ctx.channelName, content);
};

// various degrees of logging
const logLevels = ['silly', 'verbose', 'debug', 'feedback', 'info', 'warn', 'error'];

var handlers = {
    silly: function (ctx, time, tag, info) {
        console.log('[SILLY]', time, tag, info);
    },
    debug: function (ctx, time, tag, info) {
        console.log('[DEBUG]', time, tag, info);
    },
    verbose: function (ctx, time, tag, info) {
        console.log('[VERBOSE]', time, tag, info);
    },
    feedback: function (ctx, time, tag, info) {
        console.log('[FEEDBACK]', time, tag, info);
    },
    info: function (ctx, time, tag, info) {
        console.info('[INFO]', time, tag, info);
    },
    warn: function (ctx, time, tag, info) {
        console.warn('[WARN]', time, tag, info);
    },
    error: function (ctx, time, tag, info) {
        console.error('[ERROR]', time, tag, info);
    }
};

var noop = function () {};

var createLogType = function (ctx, type) {
    if (logLevels.indexOf(type) < logLevels.indexOf(ctx.logLevel)) {
        return noop;
    }
    return function (tag, info) {
        var time = new Date().toISOString();
        var content;
        try {
            content = messageTemplate(type, time, tag, info);
        } catch (e) {
            return;
        }
        if (ctx.logToStdout && typeof(handlers[type]) === 'function') {
            handlers[type](ctx, time, tag, info);
        }
        write(ctx, content);
    };
};

var createMethods = function (ctx) {
    var log = {};
    logLevels.forEach(function (type) {
        log[type] = createLogType(ctx, type);
    });
    return log;
};

Logger.create = function (config, cb) {
    if (typeof(config.logLevel) !== 'string') {
        config.logLevel = 'info';
    }

    var date = new Date();
    var launchTime = ('' + date.getUTCFullYear()).slice(-2) + date.toISOString();

    var ctx = {
        channelName: launchTime,
        logFeedback: Boolean(config.logFeedback),
        logLevel: config.logLevel,
        logToStdout: config.logToStdout,
    };

    if (!config.logPath) {
        console.log("No logPath configured. Logging to file disabled");
        return void cb(Object.freeze(createMethods(ctx)));
    }

    Store.create({
        filePath: config.logPath,
    }, function (store) {
        ctx.store = store;
        cb(Object.freeze(createMethods(ctx)));
    });
};

<|endoftext|>


<commit_before>var promise     = require("bluebird");
var _           = require('lodash');
var minimatch   = require('minimatch');
var Handlebars  = require('handlebars');
var merge       = require('deepmerge');
var swag        = require('swag');
var cheerio     = require('cheerio');

var Directory   = require('./fs/directory');
var File        = require('./fs/file');
var DataFetcher = require('./data');
var config      = require('./config');
var output      = require('./output');
var fractal     = require('../fractal');

module.exports = Component;

function Component(config){
    this.id             = config.id;
    this.path           = config.path;
    this.title          = config.title;
    this.hidden         = config.hidden;
    this.order          = config.order || 0;
    this.data           = config.data || {};
    this.type           = 'component';
    this.files          = config.files || {};
    this.layoutComponent = null;
};

Component.fromFile = function(file){
    return new Component({
        id:     file.getId(),
        title:  file.getTitle(),
        path:   file.fauxInfo.urlStylePath,
        order:  file.order,
        hidden: file.isHidden(),
        data:   file.data,
        files: {
            markup: file
        }
    });
};

Component.fromDirectory = function(dir){
    var main            = findRelated(dir, dir.children, 'markup');
    var data            = merge(main.data, DataFetcher.fetchFromFile(findRelated(main, dir.children, 'data')) || {});
    return new Component({
        id:     data.id || main.getId(),
        title:  data.title || main.getTitle(),
        path:   dir.fauxInfo.urlStylePath,
        order:  dir.order,
        hidden: data.hidden || main.isHidden(),
        data:   data,
        files: {
            markup: main,
            readme: findRelated(main, dir.children, 'readme'),
            styles: findAllRelated(main, dir.children, 'styles')
        }
    });
};

Component.prototype.render = function(variant, withoutLayout){
    return output.render(this, variant, withoutLayout);
};

Component.prototype.getData = function(){
    return merge(this.data, {
        id: this.id,
        title: this.title,
        hidden: this.hidden
    });
};

Component.prototype.getNotes = function(){
    var readmeFile = _.get(this, 'files.readme');
    if (readmeFile) {
        console.log(cheerio);
        var $ = cheerio.load(readmeFile.content.toString());
        $('h1').remove();
        return $.html();
    }
    return null;
};

Component.prototype.getStyles = function(){
    var styleFiles = _.get(this, 'files.styles');
    if (styleFiles) {
        if (styleFiles.length === 1) {
            var content = styleFiles[0].content.toString();
        } else {
            var content = styleFiles.map(function(file){
                return "/* " + file.fauxInfo.base + " *\/\n\n" + file.content.toString() + "\n\n";
            }).join("\n")
        }
        return content;
    }
    return null;
};

Component.prototype.getTemplateContext = function(variant){
    var variants = this.getVariants();
    if (variant) {
        var data = _.find(variants, 'name', variant) || variants[0];
    } else {
        data = variants[0];
    }
    return data.context || {};
};

Component.prototype.getVariants = function(){
    var base = _.clone(this.getData());
    var variants = this.data.variants || {};
    delete base.variants;
    base.name = 'base';
    base.title = 'Base';
    variants = _.map(variants, function(variant, key){
        variant.name = key;
        variant.title = variant.title || titleize(variant.name);
        variant.id = base.id + '--' + key;
        return merge(base, variant);
    });
    if (!_.find(variants, 'name', 'base')) {
        variants.unshift(base);
    }
    return variants;
};

Component.prototype.getTemplateMarkup = function(){
    return promise.resolve(this.files.markup.content.toString());
};

Component.prototype.getLayoutMarkup = function(){
    return this.getLayout().then(function(layout){
        if (!layout) {
            return '{{{content}}}';
        }
        if (_.isString(layout)) {
            return layout;
        }
        return layout.files.markup.content.toString();
    });
};

Component.prototype.isComponent = function(){
    return true;
};

Component.prototype.getLayout = function(){
    var self = this;
    if (!this.layoutComponent) {
        this.layoutComponent = fractal.getSources().then(function(sources){
            var layout = null;
            var checkLayout = self.data.layout || config.get('source.components.layout');
            if (checkLayout && checkLayout !== self.id && checkLayout !== self.path ) {
                layout = sources.components.tryFindComponent(checkLayout);
            }
            return layout;
        });
    }
    return this.layoutComponent;
};

function getFileMatcher(name, match){
    return match.replace('__name__', name);
}

function findRelated(file, files, matches, multiple) {
    var name = _.get(file, 'name');
    var results = _.filter(files, function(f){
        return minimatch(f.fauxInfo.base, getFileMatcher(name, config.get('source.components.matches.' + matches)));
    });
    if (results.length) {
        if (multiple) {
            return results;
        } else {
            return _.first(results);
        }
    }
    return null;
}

function findAllRelated(file, files, matches) {
    return findRelated(file, files, matches, true);
}

function titleize(str){
    return swag.helpers['titleize'](str);
}<commit_msg>Don't merge variants with base data<commit_after>var promise     = require("bluebird");
var _           = require('lodash');
var minimatch   = require('minimatch');
var Handlebars  = require('handlebars');
var merge       = require('deepmerge');
var swag        = require('swag');
var cheerio     = require('cheerio');

var Directory   = require('./fs/directory');
var File        = require('./fs/file');
var DataFetcher = require('./data');
var config      = require('./config');
var output      = require('./output');
var fractal     = require('../fractal');

module.exports = Component;

function Component(config){
    this.id             = config.id;
    this.path           = config.path;
    this.title          = config.title;
    this.hidden         = config.hidden;
    this.order          = config.order || 0;
    this.data           = config.data || {};
    this.type           = 'component';
    this.files          = config.files || {};
    this.layoutComponent = null;
};

Component.fromFile = function(file){
    return new Component({
        id:     file.getId(),
        title:  file.getTitle(),
        path:   file.fauxInfo.urlStylePath,
        order:  file.order,
        hidden: file.isHidden(),
        data:   file.data,
        files: {
            markup: file
        }
    });
};

Component.fromDirectory = function(dir){
    var main            = findRelated(dir, dir.children, 'markup');
    var data            = merge(main.data, DataFetcher.fetchFromFile(findRelated(main, dir.children, 'data')) || {});
    return new Component({
        id:     data.id || main.getId(),
        title:  data.title || main.getTitle(),
        path:   dir.fauxInfo.urlStylePath,
        order:  dir.order,
        hidden: data.hidden || main.isHidden(),
        data:   data,
        files: {
            markup: main,
            readme: findRelated(main, dir.children, 'readme'),
            styles: findAllRelated(main, dir.children, 'styles')
        }
    });
};

Component.prototype.render = function(variant, withoutLayout){
    return output.render(this, variant, withoutLayout);
};

Component.prototype.getData = function(){
    return merge(this.data, {
        id: this.id,
        title: this.title,
        hidden: this.hidden
    });
};

Component.prototype.getNotes = function(){
    var readmeFile = _.get(this, 'files.readme');
    if (readmeFile) {
        console.log(cheerio);
        var $ = cheerio.load(readmeFile.content.toString());
        $('h1').remove();
        return $.html();
    }
    return null;
};

Component.prototype.getStyles = function(){
    var styleFiles = _.get(this, 'files.styles');
    if (styleFiles) {
        if (styleFiles.length === 1) {
            var content = styleFiles[0].content.toString();
        } else {
            var content = styleFiles.map(function(file){
                return "/* " + file.fauxInfo.base + " *\/\n\n" + file.content.toString() + "\n\n";
            }).join("\n")
        }
        return content;
    }
    return null;
};

Component.prototype.getTemplateContext = function(variant){
    var variants = this.getVariants();
    if (variant) {
        var data = _.find(variants, 'name', variant) || variants[0];
    } else {
        data = variants[0];
    }
    return data.context || {};
};

Component.prototype.getVariants = function(){
    var base = _.clone(this.getData());
    var variants = this.data.variants || {};
    delete base.variants;
    base.name = 'base';
    base.title = 'Base';
    variants = _.map(variants, function(variant, key){
        if (!variant.hidden) {
            variant.name = key;
            variant.title = variant.title || titleize(variant.name);
            variant.id = base.id + '--' + key;
            variant.status = variant.status || base.status;
            return variant;
        }
    });
    if (!_.find(variants, 'name', 'base')) {
        variants.unshift(base);
    }
    return variants;
};

Component.prototype.getTemplateMarkup = function(){
    return promise.resolve(this.files.markup.content.toString());
};

Component.prototype.getLayoutMarkup = function(){
    return this.getLayout().then(function(layout){
        if (!layout) {
            return '{{{content}}}';
        }
        if (_.isString(layout)) {
            return layout;
        }
        return layout.files.markup.content.toString();
    });
};

Component.prototype.isComponent = function(){
    return true;
};

Component.prototype.getLayout = function(){
    var self = this;
    if (!this.layoutComponent) {
        this.layoutComponent = fractal.getSources().then(function(sources){
            var layout = null;
            var checkLayout = self.data.layout || config.get('source.components.layout');
            if (checkLayout && checkLayout !== self.id && checkLayout !== self.path ) {
                layout = sources.components.tryFindComponent(checkLayout);
            }
            return layout;
        });
    }
    return this.layoutComponent;
};

function getFileMatcher(name, match){
    return match.replace('__name__', name);
}

function findRelated(file, files, matches, multiple) {
    var name = _.get(file, 'name');
    var results = _.filter(files, function(f){
        return minimatch(f.fauxInfo.base, getFileMatcher(name, config.get('source.components.matches.' + matches)));
    });
    if (results.length) {
        if (multiple) {
            return results;
        } else {
            return _.first(results);
        }
    }
    return null;
}

function findAllRelated(file, files, matches) {
    return findRelated(file, files, matches, true);
}

function titleize(str){
    return swag.helpers['titleize'](str);
}<|endoftext|>


<commit_before>Package.describe({
  summary: "Help managing adverts.",
  version: "0.0.1",
  name: "elie:ad-manager",
  git: "https://github.com/elie222/meteor-ad-manager.git"
});

Package.onUse(function(api) {
  configure(api);

  api.export('AdManager');
  api.export('AdManagerAdverts');
});

Package.onTest(function(api) {
  configure(api);

  api.use('tinytest');

  api.addFiles('tests/helpers.js')
  api.addFiles('tests/adManagerTests.js')

  api.export('AdManagerAdverts');
});

function configure(api) {
  api.versionsFrom('1.2');

  api.use('ecmascript');
  api.use('check');
  api.use('mongo');
  api.use('random');
  api.use('templating');
  api.use('reactive-var');
  api.use('ddp-rate-limiter@1.0.0')
  api.use('aldeed:simple-schema@1.4.0');
  api.use('aldeed:collection2@2.6.0');
  api.use('aldeed:autoform@4.0.0 || 5.0.0');
  api.use('aldeed:delete-button@2.0.0');
  api.use('mdg:validated-method@0.2.2');
  api.use('alanning:roles@1.2.14');

  // both
  api.addFiles('lib/helpers.js');
  api.addFiles('lib/AdManagerAdverts.js');
  api.addFiles('lib/AdManager.js');

  // server
  api.addFiles('server/publications.js', 'server');
  api.addFiles('server/AdManager.js', 'server');

  // client
  api.addFiles('client/views/adManagerAdmin.html', 'client');
  api.addFiles('client/views/adManagerAdmin.js', 'client');
  api.addFiles('client/views/adManagerRandomAd.html', 'client');
  api.addFiles('client/views/adManagerRandomAd.js', 'client');
}<commit_msg>changed package version<commit_after>Package.describe({
  summary: "Help managing adverts.",
  version: "1.0.0",
  name: "elie:ad-manager",
  git: "https://github.com/elie222/meteor-ad-manager.git"
});

Package.onUse(function(api) {
  configure(api);

  api.export('AdManager');
  api.export('AdManagerAdverts');
});

Package.onTest(function(api) {
  configure(api);

  api.use('tinytest');

  api.addFiles('tests/helpers.js')
  api.addFiles('tests/adManagerTests.js')

  api.export('AdManagerAdverts');
});

function configure(api) {
  api.versionsFrom('1.2');

  api.use('ecmascript');
  api.use('check');
  api.use('mongo');
  api.use('random');
  api.use('templating');
  api.use('reactive-var');
  api.use('ddp-rate-limiter@1.0.0')
  api.use('aldeed:simple-schema@1.4.0');
  api.use('aldeed:collection2@2.6.0');
  api.use('aldeed:autoform@4.0.0 || 5.0.0');
  api.use('aldeed:delete-button@2.0.0');
  api.use('mdg:validated-method@0.2.2');
  api.use('alanning:roles@1.2.14');

  // both
  api.addFiles('lib/helpers.js');
  api.addFiles('lib/AdManagerAdverts.js');
  api.addFiles('lib/AdManager.js');

  // server
  api.addFiles('server/publications.js', 'server');
  api.addFiles('server/AdManager.js', 'server');

  // client
  api.addFiles('client/views/adManagerAdmin.html', 'client');
  api.addFiles('client/views/adManagerAdmin.js', 'client');
  api.addFiles('client/views/adManagerRandomAd.html', 'client');
  api.addFiles('client/views/adManagerRandomAd.js', 'client');
}<|endoftext|>


<commit_before>/**
 * @author mikael emtinger / http://gomo.se/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Animation = function ( root, data ) {

	this.root = root;
	this.data = THREE.AnimationHandler.init( data );
	this.hierarchy = THREE.AnimationHandler.parse( root );

	this.currentTime = 0;
	this.timeScale = 1;

	this.isPlaying = false;
	this.loop = true;
	this.weight = 0;

	this.interpolationType = THREE.AnimationHandler.LINEAR;

};

THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];

THREE.Animation.prototype.play = function ( startTime, weight ) {

	this.currentTime = startTime !== undefined ? startTime : 0;
	this.weight = weight !== undefined ? weight: 1;

	this.isPlaying = true;

	this.reset();

	THREE.AnimationHandler.play( this );

};

THREE.Animation.prototype.stop = function() {

	this.isPlaying = false;

	THREE.AnimationHandler.stop( this );

};

THREE.Animation.prototype.reset = function () {

	for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {

		var object = this.hierarchy[ h ];

		object.matrixAutoUpdate = true;

		if ( object.animationCache === undefined ) {

			object.animationCache = {
				animations: {},
				blending: {
					positionWeight: 0.0,
					quaternionWeight: 0.0,
					scaleWeight: 0.0
				}
			};
		}

		if ( object.animationCache.animations[this.data.name] === undefined ) {

			object.animationCache.animations[this.data.name] = {};
			object.animationCache.animations[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
			object.animationCache.animations[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
			object.animationCache.animations[this.data.name].originalMatrix = object.matrix;

		}

		var animationCache = object.animationCache.animations[this.data.name];

		// Get keys to match our current time

		for ( var t = 0; t < 3; t ++ ) {

			var type = this.keyTypes[ t ];

			var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
			var nextKey = this.getNextKeyWith( type, h, 1 );

			while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {

				prevKey = nextKey;
				nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );

			}

			animationCache.prevKey[ type ] = prevKey;
			animationCache.nextKey[ type ] = nextKey;

		}

	}

};

THREE.Animation.prototype.resetBlendWeights = function () {

	for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {

		var object = this.hierarchy[ h ];

		if ( object.animationCache !== undefined ) {

			object.animationCache.blending.positionWeight = 0.0;
			object.animationCache.blending.quaternionWeight = 0.0;
			object.animationCache.blending.scaleWeight = 0.0;

		}

	}

};

THREE.Animation.prototype.update = (function(){

	var points = [];
	var target = new THREE.Vector3();
	var newVector = new THREE.Vector3();
	var newQuat = new THREE.Quaternion();

	// Catmull-Rom spline

	var interpolateCatmullRom = function ( points, scale ) {

		var c = [], v3 = [],
		point, intPoint, weight, w2, w3,
		pa, pb, pc, pd;

		point = ( points.length - 1 ) * scale;
		intPoint = Math.floor( point );
		weight = point - intPoint;

		c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
		c[ 1 ] = intPoint;
		c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
		c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;

		pa = points[ c[ 0 ] ];
		pb = points[ c[ 1 ] ];
		pc = points[ c[ 2 ] ];
		pd = points[ c[ 3 ] ];

		w2 = weight * weight;
		w3 = weight * w2;

		v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
		v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
		v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );

		return v3;

	};

	var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {

		var v0 = ( p2 - p0 ) * 0.5,
			v1 = ( p3 - p1 ) * 0.5;

		return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;

	};

	return function ( delta ) {

		if ( this.isPlaying === false ) return;

		this.currentTime += delta * this.timeScale;

		if ( this.weight === 0 )
			return;

		//

		var duration = this.data.length;

		if ( this.currentTime > duration || this.currentTime < 0 ) {

			if ( this.loop ) {

				this.currentTime %= duration;

				if ( this.currentTime < 0 )
					this.currentTime += duration;

				this.reset();

			} else {

				this.stop();
				return;

			}

		}

		for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {

			var object = this.hierarchy[ h ];
			var animationCache = object.animationCache.animations[this.data.name];
			var blending = object.animationCache.blending;

			// loop through pos/rot/scl

			for ( var t = 0; t < 3; t ++ ) {

				// get keys

				var type    = this.keyTypes[ t ];
				var prevKey = animationCache.prevKey[ type ];
				var nextKey = animationCache.nextKey[ type ];

				if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
					( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {

					prevKey = this.data.hierarchy[ h ].keys[ 0 ];
					nextKey = this.getNextKeyWith( type, h, 1 );

					while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {

						prevKey = nextKey;
						nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );

					}

					animationCache.prevKey[ type ] = prevKey;
					animationCache.nextKey[ type ] = nextKey;

				}

				object.matrixAutoUpdate = true;
				object.matrixWorldNeedsUpdate = true;

				var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );

				var prevXYZ = prevKey[ type ];
				var nextXYZ = nextKey[ type ];

				if ( scale < 0 ) scale = 0;
				if ( scale > 1 ) scale = 1;

				// interpolate

				if ( type === "pos" ) {

					if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {

						newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
						newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
						newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;

						// blend
						var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
						object.position.lerp( newVector, proportionalWeight );
						blending.positionWeight += this.weight;

					} else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
								this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

						points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
						points[ 1 ] = prevXYZ;
						points[ 2 ] = nextXYZ;
						points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];

						scale = scale * 0.33 + 0.33;

						var currentPoint = interpolateCatmullRom( points, scale );
						var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
						blending.positionWeight += this.weight;

						// blend

						var vector = object.position;

						vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
						vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
						vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;

						if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

							var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );

							target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
							target.sub( vector );
							target.y = 0;
							target.normalize();

							var angle = Math.atan2( target.x, target.z );
							object.rotation.set( 0, angle, 0 );

						}

					}

				} else if ( type === "rot" ) {

					THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );

					// Avoid paying the cost of an additional slerp if we don't have to
					if ( blending.quaternionWeight === 0 ) {

						object.quaternion.copy(newQuat);
						blending.quaternionWeight = this.weight;

					} else {

						var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
						THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
						blending.quaternionWeight += this.weight;

					}

				} else if ( type === "scl" ) {

					newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
					newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
					newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;

					var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
					object.scale.lerp( newVector, proportionalWeight );
					blending.scaleWeight += this.weight;

				}

			}

		}

		return true;

	};

})();

// Get next key with

THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {

	var keys = this.data.hierarchy[ h ].keys;

	if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
		 this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

		key = key < keys.length - 1 ? key : keys.length - 1;

	} else {

		key = key % keys.length;

	}

	for ( ; key < keys.length; key ++ ) {

		if ( keys[ key ][ type ] !== undefined ) {

			return keys[ key ];

		}

	}

	return this.data.hierarchy[ h ].keys[ 0 ];

};

// Get previous key with

THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {

	var keys = this.data.hierarchy[ h ].keys;

	if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
		this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

		key = key > 0 ? key : 0;

	} else {

		key = key >= 0 ? key : key + keys.length;

	}

	for ( ; key >= 0; key -- ) {

		if ( keys[ key ][ type ] !== undefined ) {

			return keys[ key ];

		}

	}

	return this.data.hierarchy[ h ].keys[ keys.length - 1 ];

};
<commit_msg>Removed MatrixAutoUpdate From Aniamtion<commit_after>/**
 * @author mikael emtinger / http://gomo.se/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Animation = function ( root, data ) {

	this.root = root;
	this.data = THREE.AnimationHandler.init( data );
	this.hierarchy = THREE.AnimationHandler.parse( root );

	this.currentTime = 0;
	this.timeScale = 1;

	this.isPlaying = false;
	this.loop = true;
	this.weight = 0;

	this.interpolationType = THREE.AnimationHandler.LINEAR;

};

THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];

THREE.Animation.prototype.play = function ( startTime, weight ) {

	this.currentTime = startTime !== undefined ? startTime : 0;
	this.weight = weight !== undefined ? weight: 1;

	this.isPlaying = true;

	this.reset();

	THREE.AnimationHandler.play( this );

};

THREE.Animation.prototype.stop = function() {

	this.isPlaying = false;

	THREE.AnimationHandler.stop( this );

};

THREE.Animation.prototype.reset = function () {

	for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {

		var object = this.hierarchy[ h ];

		if ( object.animationCache === undefined ) {

			object.animationCache = {
				animations: {},
				blending: {
					positionWeight: 0.0,
					quaternionWeight: 0.0,
					scaleWeight: 0.0
				}
			};
		}

		if ( object.animationCache.animations[this.data.name] === undefined ) {

			object.animationCache.animations[this.data.name] = {};
			object.animationCache.animations[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
			object.animationCache.animations[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
			object.animationCache.animations[this.data.name].originalMatrix = object.matrix;

		}

		var animationCache = object.animationCache.animations[this.data.name];

		// Get keys to match our current time

		for ( var t = 0; t < 3; t ++ ) {

			var type = this.keyTypes[ t ];

			var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
			var nextKey = this.getNextKeyWith( type, h, 1 );

			while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {

				prevKey = nextKey;
				nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );

			}

			animationCache.prevKey[ type ] = prevKey;
			animationCache.nextKey[ type ] = nextKey;

		}

	}

};

THREE.Animation.prototype.resetBlendWeights = function () {

	for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {

		var object = this.hierarchy[ h ];

		if ( object.animationCache !== undefined ) {

			object.animationCache.blending.positionWeight = 0.0;
			object.animationCache.blending.quaternionWeight = 0.0;
			object.animationCache.blending.scaleWeight = 0.0;

		}

	}

};

THREE.Animation.prototype.update = (function(){

	var points = [];
	var target = new THREE.Vector3();
	var newVector = new THREE.Vector3();
	var newQuat = new THREE.Quaternion();

	// Catmull-Rom spline

	var interpolateCatmullRom = function ( points, scale ) {

		var c = [], v3 = [],
		point, intPoint, weight, w2, w3,
		pa, pb, pc, pd;

		point = ( points.length - 1 ) * scale;
		intPoint = Math.floor( point );
		weight = point - intPoint;

		c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
		c[ 1 ] = intPoint;
		c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
		c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;

		pa = points[ c[ 0 ] ];
		pb = points[ c[ 1 ] ];
		pc = points[ c[ 2 ] ];
		pd = points[ c[ 3 ] ];

		w2 = weight * weight;
		w3 = weight * w2;

		v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
		v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
		v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );

		return v3;

	};

	var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {

		var v0 = ( p2 - p0 ) * 0.5,
			v1 = ( p3 - p1 ) * 0.5;

		return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;

	};

	return function ( delta ) {

		if ( this.isPlaying === false ) return;

		this.currentTime += delta * this.timeScale;

		if ( this.weight === 0 )
			return;

		//

		var duration = this.data.length;

		if ( this.currentTime > duration || this.currentTime < 0 ) {

			if ( this.loop ) {

				this.currentTime %= duration;

				if ( this.currentTime < 0 )
					this.currentTime += duration;

				this.reset();

			} else {

				this.stop();
				return;

			}

		}

		for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {

			var object = this.hierarchy[ h ];
			var animationCache = object.animationCache.animations[this.data.name];
			var blending = object.animationCache.blending;

			// loop through pos/rot/scl

			for ( var t = 0; t < 3; t ++ ) {

				// get keys

				var type    = this.keyTypes[ t ];
				var prevKey = animationCache.prevKey[ type ];
				var nextKey = animationCache.nextKey[ type ];

				if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
					( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {

					prevKey = this.data.hierarchy[ h ].keys[ 0 ];
					nextKey = this.getNextKeyWith( type, h, 1 );

					while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {

						prevKey = nextKey;
						nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );

					}

					animationCache.prevKey[ type ] = prevKey;
					animationCache.nextKey[ type ] = nextKey;

				}

				var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );

				var prevXYZ = prevKey[ type ];
				var nextXYZ = nextKey[ type ];

				if ( scale < 0 ) scale = 0;
				if ( scale > 1 ) scale = 1;

				// interpolate

				if ( type === "pos" ) {

					if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {

						newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
						newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
						newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;

						// blend
						var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
						object.position.lerp( newVector, proportionalWeight );
						blending.positionWeight += this.weight;

					} else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
								this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

						points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
						points[ 1 ] = prevXYZ;
						points[ 2 ] = nextXYZ;
						points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];

						scale = scale * 0.33 + 0.33;

						var currentPoint = interpolateCatmullRom( points, scale );
						var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
						blending.positionWeight += this.weight;

						// blend

						var vector = object.position;

						vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
						vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
						vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;

						if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

							var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );

							target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
							target.sub( vector );
							target.y = 0;
							target.normalize();

							var angle = Math.atan2( target.x, target.z );
							object.rotation.set( 0, angle, 0 );

						}

					}

				} else if ( type === "rot" ) {

					THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );

					// Avoid paying the cost of an additional slerp if we don't have to
					if ( blending.quaternionWeight === 0 ) {

						object.quaternion.copy(newQuat);
						blending.quaternionWeight = this.weight;

					} else {

						var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
						THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
						blending.quaternionWeight += this.weight;

					}

				} else if ( type === "scl" ) {

					newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
					newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
					newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;

					var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
					object.scale.lerp( newVector, proportionalWeight );
					blending.scaleWeight += this.weight;

				}

			}

		}

		return true;

	};

})();

// Get next key with

THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {

	var keys = this.data.hierarchy[ h ].keys;

	if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
		 this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

		key = key < keys.length - 1 ? key : keys.length - 1;

	} else {

		key = key % keys.length;

	}

	for ( ; key < keys.length; key ++ ) {

		if ( keys[ key ][ type ] !== undefined ) {

			return keys[ key ];

		}

	}

	return this.data.hierarchy[ h ].keys[ 0 ];

};

// Get previous key with

THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {

	var keys = this.data.hierarchy[ h ].keys;

	if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
		this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

		key = key > 0 ? key : 0;

	} else {

		key = key >= 0 ? key : key + keys.length;

	}

	for ( ; key >= 0; key -- ) {

		if ( keys[ key ][ type ] !== undefined ) {

			return keys[ key ];

		}

	}

	return this.data.hierarchy[ h ].keys[ keys.length - 1 ];

};
<|endoftext|>


<commit_before>MeteorDeveloperAccounts = {};

Oauth.registerService("meteor-developer", 2, null, function (query) {
  var response = getTokens(query);
  var accessToken = response.accessToken;
  var identity = getIdentity(accessToken);

  var serviceData = {
    accessToken: accessToken,
    expiresAt: (+new Date) + (1000 * response.expiresIn)
  };

  _.extend(serviceData, identity);

  // only set the token in serviceData if it's there. this ensures
  // that we don't lose old ones (since we only get this on the first
  // log in attempt)
  if (response.refreshToken)
    serviceData.refreshToken = response.refreshToken;

  return {
    serviceData: serviceData,
    options: {profile: {name: serviceData.username}}
    // XXX use username for name until meteor accounts has a profile with a name
  };
});

// returns an object containing:
// - accessToken
// - expiresIn: lifetime of token in seconds
// - refreshToken, if this is the first authorization request and we got a
//   refresh token from the server
var getTokens = function (query) {
  var config = ServiceConfiguration.configurations.findOne({
    service: 'meteor-developer'
  });
  if (!config)
    throw new ServiceConfiguration.ConfigError("Service not configured");

  var response;
  try {
    response = HTTP.post(
      METEOR_DEVELOPER_URL + "/oauth2/token", {
        params: {
          grant_type: "authorization_code",
          code: query.code,
          client_id: config.clientId,
          client_secret: config.secret,
          redirect_uri: Meteor.absoluteUrl("_oauth/meteor-developer?close")
        }
      }
    );
  } catch (err) {
    throw _.extend(
      new Error(
        "Failed to complete OAuth handshake with Meteor Developer Accounts. "
          + err.message
      ),
      {response: err.response}
    );
  }

  if (! response.data || response.data.error) {
    // if the http response was a json object with an error attribute
    throw new Error(
      "Failed to complete OAuth handshake with Meteor Developer Accounts. " +
        (response.data ? response.data.error :
         "No response data")
    );
  } else {
    return {
      accessToken: response.data.access_token,
      refreshToken: response.data.refresh_token,
      expiresIn: response.data.expires_in
    };
  }
};

var getIdentity = function (accessToken) {
  try {
    return HTTP.get(
      METEOR_DEVELOPER_URL + "/api/v1/identity",
      {params: {access_token: accessToken}}).data;
  } catch (err) {
    throw _.extend(
      new Error("Failed to fetch identity from Meteor Developer Accounts. " +
                err.message),
      {response: err.response}
    );
  }
};

MeteorDeveloperAccounts.retrieveCredential = function (credentialToken) {
  return Oauth.retrieveCredential(credentialToken);
};
<commit_msg>Send access token in Authorization header instead of query string<commit_after>MeteorDeveloperAccounts = {};

Oauth.registerService("meteor-developer", 2, null, function (query) {
  var response = getTokens(query);
  var accessToken = response.accessToken;
  var identity = getIdentity(accessToken);

  var serviceData = {
    accessToken: accessToken,
    expiresAt: (+new Date) + (1000 * response.expiresIn)
  };

  _.extend(serviceData, identity);

  // only set the token in serviceData if it's there. this ensures
  // that we don't lose old ones (since we only get this on the first
  // log in attempt)
  if (response.refreshToken)
    serviceData.refreshToken = response.refreshToken;

  return {
    serviceData: serviceData,
    options: {profile: {name: serviceData.username}}
    // XXX use username for name until meteor accounts has a profile with a name
  };
});

// returns an object containing:
// - accessToken
// - expiresIn: lifetime of token in seconds
// - refreshToken, if this is the first authorization request and we got a
//   refresh token from the server
var getTokens = function (query) {
  var config = ServiceConfiguration.configurations.findOne({
    service: 'meteor-developer'
  });
  if (!config)
    throw new ServiceConfiguration.ConfigError("Service not configured");

  var response;
  try {
    response = HTTP.post(
      METEOR_DEVELOPER_URL + "/oauth2/token", {
        params: {
          grant_type: "authorization_code",
          code: query.code,
          client_id: config.clientId,
          client_secret: config.secret,
          redirect_uri: Meteor.absoluteUrl("_oauth/meteor-developer?close")
        }
      }
    );
  } catch (err) {
    throw _.extend(
      new Error(
        "Failed to complete OAuth handshake with Meteor Developer Accounts. "
          + err.message
      ),
      {response: err.response}
    );
  }

  if (! response.data || response.data.error) {
    // if the http response was a json object with an error attribute
    throw new Error(
      "Failed to complete OAuth handshake with Meteor Developer Accounts. " +
        (response.data ? response.data.error :
         "No response data")
    );
  } else {
    return {
      accessToken: response.data.access_token,
      refreshToken: response.data.refresh_token,
      expiresIn: response.data.expires_in
    };
  }
};

var getIdentity = function (accessToken) {
  try {
    return HTTP.get(
      METEOR_DEVELOPER_URL + "/api/v1/identity",
      {
        headers: { Authorization: "Bearer " + accessToken }
      }
    ).data;
  } catch (err) {
    throw _.extend(
      new Error("Failed to fetch identity from Meteor Developer Accounts. " +
                err.message),
      {response: err.response}
    );
  }
};

MeteorDeveloperAccounts.retrieveCredential = function (credentialToken) {
  return Oauth.retrieveCredential(credentialToken);
};
<|endoftext|>