<commit_before>angular.module('npact')
  .constant('PUBLIC_CONFIG_KEYS',
            ['first_page_title', 'following_page_title', 'nucleotides',
             'significance', 'startBase', 'endBase', 'basesPerGraph',
             'offset', 'mycoplasma'])

  .service('GraphConfig', function(Err, npactConstants, Evt, PUBLIC_CONFIG_KEYS, Track,
                            $location, $log, $rootScope, $cookies, $window) {
    'use strict';
    var self = this;
    $window.GraphConfig = this;
    self.cookieBools = ["colorBlindFriendly"];
    self.colorBlindFriendly = false;
    self.cookieInit = function() {
      _.each(self.cookieBools, function(v){
        var cv = $cookies.get(v);
        if( cv === "true" ) self[v] = true;
        else if(cv === "false") self[v] = false;
      });
    };
    self.cookiePersist  = function(){
      _.each(self.cookieBools, function(v){
        if(self[v]) $cookies.put(v, "true");
        else $cookies.put(v, "false");
      });
    };
    self.tracks = [];
    self.cookieInit();

    self.basesPerGraph = 10000;
    self.nucleotides = ['C', 'G'];
    self.offset = 0; // how much the graph is panned left/right

    //Get values from the querystring during intialization
    _.forEach(PUBLIC_CONFIG_KEYS, function(k) {
      var v = $location.search()[k];
      if(v) {
        $log.log(k, v);
        if(v === true || v === false) {
          self[k] = v;
        }
        else if(!isNaN(v)) {
          self[k] = Number(v);
        }
        else {
          self[k] = v;
        }
      }
    });

    /**
     * what's the right title for the current nucleotides?
     */
    self.profileTitle = function() {
      return self.nucleotides ? '% ' + self.nucleotides.join('') : null;
    };

    self.activeTracks = function() {
      return _.filter(self.tracks, 'active');
    };

    /**
     * do we have a track with a given name?
     */
    this.findTrack = function(name){
      return _.find(self.tracks, {name: name});
    };

    /**
     * register a track to be displayed on the graph
     */
    this.loadTrack = function(track) {
      $log.log('loading new track', track);
      _.remove(self.tracks, {name: track.name});  //mutates
      self.tracks.push(track);
      self.tracks = _.sortBy(self.tracks, 'weight');
    };
  })

  /*
   * Run a VERB (e.g. extract, acgt_gamma) on server.
   * Get back a config dictionary (which automatically updates GraphConfig)
   */
  .factory('processOnServer', function(GraphConfig, KICKSTART_URL,
                                PUBLIC_CONFIG_KEYS, Utils,
                                $http, $log, $location) {
    'use strict';
    //The keys the server is going to accept from our GraphConfig
    return function(verb) {
      var url = KICKSTART_URL;
      var postconfig = angular.extend({verb: verb}, $location.search());
      $log.log('Going to request', verb, url, postconfig);
      _.forEach(PUBLIC_CONFIG_KEYS, function(k) {
        if(GraphConfig[k])
          postconfig[k] = GraphConfig[k];
      });
      postconfig['x-tics'] = Utils.orderOfMagnitude(GraphConfig.basesPerGraph, -1);

      return $http.get(url, { cache: true, params: postconfig })
        .then(function(res) {
          $log.log('Server process successful:', res.data);
          angular.extend(GraphConfig, res.data);
          return res.data;
        });
    };
  })

  .directive('npactGraphConfig', function npactGraphConfig(STATIC_BASE_URL) {
    'use strict';
    return {
      restrict: 'A',
      templateUrl: STATIC_BASE_URL + 'js/graphs/config.html',
      controller: 'npactGraphConfigCtrl as gcctrl'
    };
  })
  .controller('npactGraphConfigCtrl', function($scope, $window, $location, $log,
                                        $timeout,
                                        GraphConfig, PredictionManager,
                                        PUBLIC_CONFIG_KEYS) {
    'use strict';
    $scope.gc = GraphConfig;
    //  If any of the GraphConfig values change update the querystring
    var gcpubkeys = _.map(PUBLIC_CONFIG_KEYS, function(k) { return 'gc.' + k; });
    $scope.$watchGroup(gcpubkeys, function(newVals) {
      $location.search(_.object(PUBLIC_CONFIG_KEYS, newVals));
    });
    $scope.$watch('gc.mycoplasma', function() {
      $timeout(PredictionManager.start, 50);
    });
  })

  .directive('npactOrfFinder', function(GraphConfig, MessageBus, $q, $log, $timeout) {
    'use strict';
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function($scope, element, attrs, ngModel) {
        function resultInRange(result) {
          return result.start >= GraphConfig.startBase &&
            result.end <= GraphConfig.endBase;
        }

        function doSearch(val) {
          $log.log("Searching for:", val);
          delete $scope.results;
          delete $scope.resultsIndex;
          if(!val) return $q.when(true);
          return $q
            .all(_.map(GraphConfig.activeTracks(), function(t) { return t.findByName(val); }))
            .then(function(values) {
              return $timeout(function() {  // let other code run
                $scope.results = _(values).flatten().filter(resultInRange).sortBy('start').value();
                $log.log("Total results", $scope.results.length);
                if($scope.results.length > 0) {
                  $scope.resultsIndex = 0;
                  GraphConfig.gotoBase = $scope.results[$scope.resultsIndex].start;
                  return true;
                }
                else {
                  MessageBus.warning("No matches found");
                  return $q.reject("No matches found for: '" + val + "'");
                }
              });
            });
        }
        ngModel.$asyncValidators.matchingOrfs = doSearch;
        $scope.$watchGroup(['gc.startBase', 'gc.endBase'], function() {
          if(GraphConfig.findORF) {
            doSearch(GraphConfig.findORF);
          }
        });
        $scope.$watch('resultsIndex', function(idx) {
          if(!$scope.results || $scope.results.length === 0) return;
          if(idx < 0) { $scope.resultsIndex = 0; }
          if(idx >= $scope.results.length) { $scope.resultsIndex = $scope.results.length - 1; }
          GraphConfig.gotoBase = $scope.results[$scope.resultsIndex].start;
        });
      }
    };
  })

  .controller('TooltipCtrl', function($scope, $sce) {
  })
;
<commit_msg>Parse 'true'/'false' strings into boolean values<commit_after>angular.module('npact')
  .constant('PUBLIC_CONFIG_KEYS',
            ['first_page_title', 'following_page_title', 'nucleotides',
             'significance', 'startBase', 'endBase', 'basesPerGraph',
             'offset', 'mycoplasma'])

  .service('GraphConfig', function(Err, npactConstants, Evt, PUBLIC_CONFIG_KEYS, Track,
                            $location, $log, $rootScope, $cookies, $window) {
    'use strict';
    var self = this;
    $window.GraphConfig = this;
    self.cookieBools = ["colorBlindFriendly"];
    self.colorBlindFriendly = false;
    self.cookieInit = function() {
      _.each(self.cookieBools, function(v){
        var cv = $cookies.get(v);
        if( cv === "true" ) self[v] = true;
        else if(cv === "false") self[v] = false;
      });
    };
    self.cookiePersist  = function(){
      _.each(self.cookieBools, function(v){
        if(self[v]) $cookies.put(v, "true");
        else $cookies.put(v, "false");
      });
    };
    self.tracks = [];
    self.cookieInit();

    self.basesPerGraph = 10000;
    self.nucleotides = ['C', 'G'];
    self.offset = 0; // how much the graph is panned left/right

    //Get values from the querystring during intialization
    _.forEach(PUBLIC_CONFIG_KEYS, function(k) {
      var v = $location.search()[k];
      if(v) {
        $log.log(k, v);
        if(v === true || v === false) {
          self[k] = v;
        }
        else if (v === "true") {
          self[k] = true;
        }
        else if (v === "false") {
          self[k] = false;
        }
        else if(!isNaN(v)) {
          self[k] = Number(v);
        }
        else {
          self[k] = v;
        }
      }
    });

    /**
     * what's the right title for the current nucleotides?
     */
    self.profileTitle = function() {
      return self.nucleotides ? '% ' + self.nucleotides.join('') : null;
    };

    self.activeTracks = function() {
      return _.filter(self.tracks, 'active');
    };

    /**
     * do we have a track with a given name?
     */
    this.findTrack = function(name){
      return _.find(self.tracks, {name: name});
    };

    /**
     * register a track to be displayed on the graph
     */
    this.loadTrack = function(track) {
      $log.log('loading new track', track);
      _.remove(self.tracks, {name: track.name});  //mutates
      self.tracks.push(track);
      self.tracks = _.sortBy(self.tracks, 'weight');
    };
  })

  /*
   * Run a VERB (e.g. extract, acgt_gamma) on server.
   * Get back a config dictionary (which automatically updates GraphConfig)
   */
  .factory('processOnServer', function(GraphConfig, KICKSTART_URL,
                                PUBLIC_CONFIG_KEYS, Utils,
                                $http, $log, $location) {
    'use strict';
    //The keys the server is going to accept from our GraphConfig
    return function(verb) {
      var url = KICKSTART_URL;
      var postconfig = angular.extend({verb: verb}, $location.search());
      $log.log('Going to request', verb, url, postconfig);
      _.forEach(PUBLIC_CONFIG_KEYS, function(k) {
        if(GraphConfig[k])
          postconfig[k] = GraphConfig[k];
      });
      postconfig['x-tics'] = Utils.orderOfMagnitude(GraphConfig.basesPerGraph, -1);

      return $http.get(url, { cache: true, params: postconfig })
        .then(function(res) {
          $log.log('Server process successful:', res.data);
          angular.extend(GraphConfig, res.data);
          return res.data;
        });
    };
  })

  .directive('npactGraphConfig', function npactGraphConfig(STATIC_BASE_URL) {
    'use strict';
    return {
      restrict: 'A',
      templateUrl: STATIC_BASE_URL + 'js/graphs/config.html',
      controller: 'npactGraphConfigCtrl as gcctrl'
    };
  })
  .controller('npactGraphConfigCtrl', function($scope, $window, $location, $log,
                                        $timeout,
                                        GraphConfig, PredictionManager,
                                        PUBLIC_CONFIG_KEYS) {
    'use strict';
    $scope.gc = GraphConfig;
    //  If any of the GraphConfig values change update the querystring
    var gcpubkeys = _.map(PUBLIC_CONFIG_KEYS, function(k) { return 'gc.' + k; });
    $scope.$watchGroup(gcpubkeys, function(newVals) {
      $location.search(_.object(PUBLIC_CONFIG_KEYS, newVals));
    });
    $scope.$watch('gc.mycoplasma', function(val, old) {
      $log.debug("mycoplasma changed from", old, "to", val);
      // Wait so that the above update to $location has a chance to complete
      $timeout(PredictionManager.start, 50);
    });
  })

  .directive('npactOrfFinder', function(GraphConfig, MessageBus, $q, $log, $timeout) {
    'use strict';
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function($scope, element, attrs, ngModel) {
        function resultInRange(result) {
          return result.start >= GraphConfig.startBase &&
            result.end <= GraphConfig.endBase;
        }

        function doSearch(val) {
          $log.log("Searching for:", val);
          delete $scope.results;
          delete $scope.resultsIndex;
          if(!val) return $q.when(true);
          return $q
            .all(_.map(GraphConfig.activeTracks(), function(t) { return t.findByName(val); }))
            .then(function(values) {
              return $timeout(function() {  // let other code run
                $scope.results = _(values).flatten().filter(resultInRange).sortBy('start').value();
                $log.log("Total results", $scope.results.length);
                if($scope.results.length > 0) {
                  $scope.resultsIndex = 0;
                  GraphConfig.gotoBase = $scope.results[$scope.resultsIndex].start;
                  return true;
                }
                else {
                  MessageBus.warning("No matches found");
                  return $q.reject("No matches found for: '" + val + "'");
                }
              });
            });
        }
        ngModel.$asyncValidators.matchingOrfs = doSearch;
        $scope.$watchGroup(['gc.startBase', 'gc.endBase'], function() {
          if(GraphConfig.findORF) {
            doSearch(GraphConfig.findORF);
          }
        });
        $scope.$watch('resultsIndex', function(idx) {
          if(!$scope.results || $scope.results.length === 0) return;
          if(idx < 0) { $scope.resultsIndex = 0; }
          if(idx >= $scope.results.length) { $scope.resultsIndex = $scope.results.length - 1; }
          GraphConfig.gotoBase = $scope.results[$scope.resultsIndex].start;
        });
      }
    };
  })

  .controller('TooltipCtrl', function($scope, $sce) {
  })
;
<|endoftext|>


<commit_before>'use strict';

var User = require('../user/user.model');

exports.defaultUser = function(req, res, next) {
  console.log('in default user');
  var user = new User();
  res.json(user);
}
<commit_msg>cleanup<commit_after>'use strict';

var User = require('../user/user.model');

exports.defaultUser = function(req, res, next) {
  var user = new User();
  res.json(user);
}
<|endoftext|>


<commit_before>/**
 * Created by Peter on 2017. 6. 5..
 */
"use strict";

var fs = require('fs');
var async = require('async');

var modelAqi = require('../../models/worldWeather/modelAqi');

var config = require('../../config/config');
var controllerKeys = require('./controllerKeys');
var aqiRequester = require('../../lib/AQI/aqiRequester');
var controllerCollector = require('./controllerCollector');

function controllerAqi() {
    var self = this;

    self.cKeys = new controllerKeys();
}

controllerAqi.prototype._getAQIKey = function(){
    var self = this;
    return self.cKeys.getAqiKey();
};

/**
 *
 * @param time
 * @returns {Date|global.Date}
 * @private
 */
controllerAqi.prototype._getUtcTime = function(time) {
    var now = new Date();

    now.setTime(time);

    return now;
};

controllerAqi.prototype._getDiffDate = function (utcTime, localTime) {
    if (utcTime.getUTCFullYear() < localTime.getUTCFullYear()) {
        return 1;
    }
    else if (utcTime.getUTCFullYear() > localTime.getUTCFullYear()) {
        return -1;
    }
    else if (utcTime.getUTCFullYear() == localTime.getUTCFullYear()) {
        if (utcTime.getUTCMonth() < localTime.getUTCMonth()) {
            return 1;
        }
        else if (utcTime.getUTCMonth() > localTime.getUTCMonth()) {
            return -1;
        }
        else if (utcTime.getUTCMonth() == localTime.getUTCMonth()) {
            if (utcTime.getUTCDate() < localTime.getUTCDate()) {
                return 1;
            }
            else if (utcTime.getUTCDate() > localTime.getUTCDate()) {
                return -1;
            }
            else if (utcTime.getUTCDate() == localTime.getUTCDate()) {
                return 0;
            }
        }
    }
    log.error("Invalid time");
    return 0;
};
/**
 *
 * @param timeOffset
 * @returns {Date|global.Date}
 * @private
 */
controllerAqi.prototype._getLocalLast0H = function (timeOffset) {
    var utcTime = new Date();
    var localTime = new Date();
    localTime.setUTCMinutes(localTime.getUTCMinutes()+timeOffset);

    var diffDate = this._getDiffDate(utcTime, localTime);
    if (diffDate == 0) {
        log.info('same day');
    }
    else if (diffDate == 1) {
        log.info('next day');
        utcTime.setUTCDate(utcTime.getUTCDate()+1);
    }
    else if (diffDate == -1) {
        log.info('previous day');
        utcTime.setUTCDate(utcTime.getUTCDate()-1);
    }
    utcTime.setUTCHours(0);
    utcTime.setUTCMinutes(0);
    utcTime.setUTCSeconds(0);
    utcTime.setUTCMilliseconds(0);
    utcTime.setUTCMinutes(-timeOffset);

    return utcTime;
};

controllerAqi.prototype._removeAllAqiDb = function(geocode, callback){
    var geo = [];

    if(typeof parseFloat(geocode.lan) != 'number' || typeof parseFloat(geocode.lat) != 'number'){
        log.error('Aqi DB> _removeAllAqiDb : Wrong geocode', geocode);
        return callback(new Error('Fail to remove Aqi data'));
    }

    geo.push(parseFloat(geocode.lon));
    geo.push(parseFloat(geocode.lat));

    modelAqi.remove({geo:geo}).lean().exec(function(err, list){
        if(err){
            log.error('Aqi DB> fail to get db data', err);
            return callback(err);
        }
        log.silly('Aqi DB > remove all data');
        callback(undefined);
    });
};

controllerAqi.prototype._getItemValue = function(item, name){
    if(item[name] == undefined){
        return -100;
    }

    if(item[name].v == undefined){
        return -100;
    }

    return parseFloat(item[name].v);
};

controllerAqi.prototype._parseAQIData = function(data){
    var self = this;

    if(data == undefined || data.data === undefined){
        return undefined;
    }

    var aqi = data.data;
    var timeOffset = 0;
    if(aqi.time != undefined && aqi.time.tz != undefined && aqi.time.tz.length > 5){
        timeOffset = parseInt(aqi.time.tz.slice(0, 3));
    }

    var ret = {
        aqi: (aqi.aqi != undefined)? parseFloat(aqi.aqi):-100,
        idx: (aqi.idx != undefined)? parseFloat(aqi.idx):-100,
        timeOffset: timeOffset,
        co: -100,
        h: -100,
        no2: -100,
        o3: -100,
        p: -100,
        pm10: -100,
        pm25: -100,
        so2: -100,
        t: -100
    };

    if(aqi.iaqi != undefined){
        var iaqi = aqi.iaqi;

        ret.co = self._getItemValue(iaqi, 'co');
        ret.h = self._getItemValue(iaqi, 'h');
        ret.no2 = self._getItemValue(iaqi, 'no2');
        ret.o3 = self._getItemValue(iaqi, 'o3');
        ret.p = self._getItemValue(iaqi, 'p');
        ret.pm10 = self._getItemValue(iaqi, 'pm10');
        ret.pm25 = self._getItemValue(iaqi, 'pm25');
        ret.so2 = self._getItemValue(iaqi, 'so2');
        ret.t = self._getItemValue(iaqi, 't');
    }

    return ret;
};

controllerAqi.prototype._saveAQI = function(geocode, date, data, callback){
    var self = this;

    try{
        var newData = self._parseAQIData(data);
        if(isNaN(newData.aqi)){
            newData.aqi = -100;
        }

        log.info('AQI> New Data : ', newData);
        var res = {
            geo: [],
            address: {},
            date: date,
            dateObj: self._getUtcTime('' + date + '000'),
            timeOffset: newData.timeOffset,
            aqi: newData.aqi,
            idx: newData.idx,
            co: newData.co,
            h: newData.h,
            no2: newData.no2,
            o3: newData.o3,
            p: newData.p,
            pm10: newData.pm10,
            pm25: newData.pm25,
            so2: newData.so2,
            t: newData.t
        };

        res.geo.push(parseFloat(geocode.lon));
        res.geo.push(parseFloat(geocode.lat));

        log.info('Aqi> res : ', res);

        modelAqi.update({geo: res.geo, dateObj: res.dateObj}, res, {upsert:true}, function (err) {
            if(err){
                log.error('Aqi> Fail to update db data: ', geocode, err);
            }
        });

        if(callback){
            callback(0, res);
        }
    }
    catch(e){
        log.error('Aqi> Exception!!!');
        if(callback){
            callback(e);
        }
    }
};

controllerAqi.prototype.requestAqiData = function(geocode, From, To, timeOffset, callback){
    var self = this;
    var key = self._getAQIKey().key;
    var dataList = [];
    var requester = new aqiRequester;

    if(timeOffset > 14 || timeOffset < -11){
        timeOffset = 0;
    }

    var reqTime = self._getLocalLast0H(timeOffset*60);
    //day light saving위해 1시간 margin을 둠.
    reqTime.setUTCHours(reqTime.getUTCHours()+1);
    for(var i=From ; i<To ; i++){
        reqTime.setUTCDate(reqTime.getUTCDate()-i);
        //log.info("reqTime="+reqTime.toISOString());
        var nTime = parseInt(reqTime.getTime()/1000);
        dataList.push(nTime);
    }

    dataList.push('cur');

    self._removeAllAqiDb(geocode, function(err){
        if(err){
            log.error('Req Aqi> fail to delete all data');
            return callback(err);
        }

        async.mapSeries(dataList,
            function(date, cb){
                if(date === 'cur'){
                    date = undefined;
                }
                else {
                    log.info('date : ', (new Date(date*1000)).toISOString());
                }

                requester.getAqiData(geocode, key, function(err, result){
                    if(err){
                        log.error('Req Aqi> get fail', geocode, date);
                        log.warn(err);
                        cb(null, {err: 'fail to get AQI'});
                        return;
                    }

                    if(date === undefined){
                        var curTime = new Date();
                        date = parseInt(curTime.getTime() / 1000);
                        log.info('Req Aqi> cur : ', date.toString());
                    }

                    self._saveAQI(geocode, date, result, function(err, savedData){
                        return cb(null, savedData);
                    });
                });
            },
            function(err, aqiData){
                if(err){
                    log.error('Req Aqi> Fail to get AQI data');
                }
                var res = {
                    type : 'AQI',
                    geocode: geocode,
                    address: {},
                    date: 0,
                    dateObj: new Date(0),
                    timeOffset: timeOffset,
                    data: []
                };

                if(aqiData != undefined){
                    aqiData.forEach(function(item){
                        if(item.date === undefined){
                            return;
                        }

                        if(res.date === 0 || res.date < item.date){
                            res.date = item.date;
                        }
                        if(res.dateObj === 0 || res.dateObj.getTime() < item.dateObj.getTime()){
                            res.dateObj = item.dateObj;
                        }
                        if(item.timeOffset){
                            res.timeOffset = item.timeOffset;
                        }

                        res.data.push(item);
                    });
                }

                if(callback){
                    callback(err, res);
                }
            }
        );
    });

};

module.exports = controllerAqi;<commit_msg>#1752 adjusted log level<commit_after>/**
 * Created by Peter on 2017. 6. 5..
 */
"use strict";

var fs = require('fs');
var async = require('async');

var modelAqi = require('../../models/worldWeather/modelAqi');

var config = require('../../config/config');
var controllerKeys = require('./controllerKeys');
var aqiRequester = require('../../lib/AQI/aqiRequester');
var controllerCollector = require('./controllerCollector');

function controllerAqi() {
    var self = this;

    self.cKeys = new controllerKeys();
}

controllerAqi.prototype._getAQIKey = function(){
    var self = this;
    return self.cKeys.getAqiKey();
};

/**
 *
 * @param time
 * @returns {Date|global.Date}
 * @private
 */
controllerAqi.prototype._getUtcTime = function(time) {
    var now = new Date();

    now.setTime(time);

    return now;
};

controllerAqi.prototype._getDiffDate = function (utcTime, localTime) {
    if (utcTime.getUTCFullYear() < localTime.getUTCFullYear()) {
        return 1;
    }
    else if (utcTime.getUTCFullYear() > localTime.getUTCFullYear()) {
        return -1;
    }
    else if (utcTime.getUTCFullYear() == localTime.getUTCFullYear()) {
        if (utcTime.getUTCMonth() < localTime.getUTCMonth()) {
            return 1;
        }
        else if (utcTime.getUTCMonth() > localTime.getUTCMonth()) {
            return -1;
        }
        else if (utcTime.getUTCMonth() == localTime.getUTCMonth()) {
            if (utcTime.getUTCDate() < localTime.getUTCDate()) {
                return 1;
            }
            else if (utcTime.getUTCDate() > localTime.getUTCDate()) {
                return -1;
            }
            else if (utcTime.getUTCDate() == localTime.getUTCDate()) {
                return 0;
            }
        }
    }
    log.error("Invalid time");
    return 0;
};
/**
 *
 * @param timeOffset
 * @returns {Date|global.Date}
 * @private
 */
controllerAqi.prototype._getLocalLast0H = function (timeOffset) {
    var utcTime = new Date();
    var localTime = new Date();
    localTime.setUTCMinutes(localTime.getUTCMinutes()+timeOffset);

    var diffDate = this._getDiffDate(utcTime, localTime);
    if (diffDate == 0) {
        log.info('same day');
    }
    else if (diffDate == 1) {
        log.info('next day');
        utcTime.setUTCDate(utcTime.getUTCDate()+1);
    }
    else if (diffDate == -1) {
        log.info('previous day');
        utcTime.setUTCDate(utcTime.getUTCDate()-1);
    }
    utcTime.setUTCHours(0);
    utcTime.setUTCMinutes(0);
    utcTime.setUTCSeconds(0);
    utcTime.setUTCMilliseconds(0);
    utcTime.setUTCMinutes(-timeOffset);

    return utcTime;
};

controllerAqi.prototype._removeAllAqiDb = function(geocode, callback){
    var geo = [];

    if(typeof parseFloat(geocode.lan) != 'number' || typeof parseFloat(geocode.lat) != 'number'){
        log.error('Aqi DB> _removeAllAqiDb : Wrong geocode', geocode);
        return callback(new Error('Fail to remove Aqi data'));
    }

    geo.push(parseFloat(geocode.lon));
    geo.push(parseFloat(geocode.lat));

    modelAqi.remove({geo:geo}).lean().exec(function(err, list){
        if(err){
            log.error('Aqi DB> fail to get db data', err);
            return callback(err);
        }
        log.silly('Aqi DB > remove all data');
        callback(undefined);
    });
};

controllerAqi.prototype._getItemValue = function(item, name){
    if(item[name] == undefined){
        return -100;
    }

    if(item[name].v == undefined){
        return -100;
    }

    return parseFloat(item[name].v);
};

controllerAqi.prototype._parseAQIData = function(data){
    var self = this;

    if(data == undefined || data.data === undefined){
        return undefined;
    }

    var aqi = data.data;
    var timeOffset = 0;
    if(aqi.time != undefined && aqi.time.tz != undefined && aqi.time.tz.length > 5){
        timeOffset = parseInt(aqi.time.tz.slice(0, 3));
    }

    var ret = {
        aqi: (aqi.aqi != undefined)? parseFloat(aqi.aqi):-100,
        idx: (aqi.idx != undefined)? parseFloat(aqi.idx):-100,
        timeOffset: timeOffset,
        co: -100,
        h: -100,
        no2: -100,
        o3: -100,
        p: -100,
        pm10: -100,
        pm25: -100,
        so2: -100,
        t: -100
    };

    if(aqi.iaqi != undefined){
        var iaqi = aqi.iaqi;

        ret.co = self._getItemValue(iaqi, 'co');
        ret.h = self._getItemValue(iaqi, 'h');
        ret.no2 = self._getItemValue(iaqi, 'no2');
        ret.o3 = self._getItemValue(iaqi, 'o3');
        ret.p = self._getItemValue(iaqi, 'p');
        ret.pm10 = self._getItemValue(iaqi, 'pm10');
        ret.pm25 = self._getItemValue(iaqi, 'pm25');
        ret.so2 = self._getItemValue(iaqi, 'so2');
        ret.t = self._getItemValue(iaqi, 't');
    }

    return ret;
};

controllerAqi.prototype._saveAQI = function(geocode, date, data, callback){
    var self = this;

    try{
        var newData = self._parseAQIData(data);
        if(isNaN(newData.aqi)){
            newData.aqi = -100;
            log.error('AQI> Invalid AQI Data: ', JSON.stringify(newData));
        }

        log.info('AQI> New Data : ', newData);
        var res = {
            geo: [],
            address: {},
            date: date,
            dateObj: self._getUtcTime('' + date + '000'),
            timeOffset: newData.timeOffset,
            aqi: newData.aqi,
            idx: newData.idx,
            co: newData.co,
            h: newData.h,
            no2: newData.no2,
            o3: newData.o3,
            p: newData.p,
            pm10: newData.pm10,
            pm25: newData.pm25,
            so2: newData.so2,
            t: newData.t
        };

        res.geo.push(parseFloat(geocode.lon));
        res.geo.push(parseFloat(geocode.lat));

        log.info('Aqi> res : ', res);

        modelAqi.update({geo: res.geo, dateObj: res.dateObj}, res, {upsert:true}, function (err) {
            if(err){
                log.error('Aqi> Fail to update db data: ', geocode, err);
            }
        });

        if(callback){
            callback(0, res);
        }
    }
    catch(e){
        log.error('Aqi> Exception!!!');
        if(callback){
            callback(e);
        }
    }
};

controllerAqi.prototype.requestAqiData = function(geocode, From, To, timeOffset, callback){
    var self = this;
    var key = self._getAQIKey().key;
    var dataList = [];
    var requester = new aqiRequester;

    if(timeOffset > 14 || timeOffset < -11){
        timeOffset = 0;
    }

    var reqTime = self._getLocalLast0H(timeOffset*60);
    //day light saving위해 1시간 margin을 둠.
    reqTime.setUTCHours(reqTime.getUTCHours()+1);
    for(var i=From ; i<To ; i++){
        reqTime.setUTCDate(reqTime.getUTCDate()-i);
        //log.info("reqTime="+reqTime.toISOString());
        var nTime = parseInt(reqTime.getTime()/1000);
        dataList.push(nTime);
    }

    dataList.push('cur');

    self._removeAllAqiDb(geocode, function(err){
        if(err){
            log.error('Req Aqi> fail to delete all data');
            return callback(err);
        }

        async.mapSeries(dataList,
            function(date, cb){
                if(date === 'cur'){
                    date = undefined;
                }
                else {
                    log.info('date : ', (new Date(date*1000)).toISOString());
                }

                requester.getAqiData(geocode, key, function(err, result){
                    if(err){
                        log.error('Req Aqi> get fail', geocode, date);
                        log.warn(err);
                        cb(null, {err: 'fail to get AQI'});
                        return;
                    }

                    if(date === undefined){
                        var curTime = new Date();
                        date = parseInt(curTime.getTime() / 1000);
                        log.info('Req Aqi> cur : ', date.toString());
                    }

                    self._saveAQI(geocode, date, result, function(err, savedData){
                        return cb(null, savedData);
                    });
                });
            },
            function(err, aqiData){
                if(err){
                    log.error('Req Aqi> Fail to get AQI data');
                }
                var res = {
                    type : 'AQI',
                    geocode: geocode,
                    address: {},
                    date: 0,
                    dateObj: new Date(0),
                    timeOffset: timeOffset,
                    data: []
                };

                if(aqiData != undefined){
                    aqiData.forEach(function(item){
                        if(item.date === undefined){
                            return;
                        }

                        if(res.date === 0 || res.date < item.date){
                            res.date = item.date;
                        }
                        if(res.dateObj === 0 || res.dateObj.getTime() < item.dateObj.getTime()){
                            res.dateObj = item.dateObj;
                        }
                        if(item.timeOffset){
                            res.timeOffset = item.timeOffset;
                        }

                        res.data.push(item);
                    });
                }

                if(callback){
                    callback(err, res);
                }
            }
        );
    });

};

module.exports = controllerAqi;<|endoftext|>


<commit_before>const DrawCard = require('../../drawcard');

class OverwhelmingNumbers extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Put characters into play',
            condition: context => this.getNumberOfAttackingDothraki(context) >= 2,
            target: {
                type: 'select',
                numCards: 2,
                cardCondition: (card, context) => (
                    card.isMatch({ trait: 'Dothraki', type: 'character', location: 'hand' }) &&
                    card.controller === context.player &&
                    context.player.canPutIntoPlay(card)
                )
            },
            handler: context => {
                for(const card of context.target) {
                    context.player.putIntoPlay(card, 'play', { kneeled: true });
                    this.game.currentChallenge.addAttacker(card);
                    this.atEndOfChallenge(ability => ({
                        match: card,
                        effect: ability.effects.returnToHandIfStillInPlay(true, 'challenge')
                    }));
                }

                this.game.addMessage('{0} plays {1} to put {2} into play from their hand knelt, participating as attackers',
                    context.player, this, context.target);
            },
            max: ability.limit.perChallenge(1)
        });
    }

    getNumberOfAttackingDothraki(context) {
        return context.player.getNumberOfCardsInPlay({ trait: 'Dothraki', type: 'character', attacking: true });
    }
}

OverwhelmingNumbers.code = '15022';

module.exports = OverwhelmingNumbers;
<commit_msg>Allow Overwhelming Numbers to choose from discard (#2846)<commit_after>const DrawCard = require('../../drawcard');

class OverwhelmingNumbers extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Put characters into play',
            condition: context => this.getNumberOfAttackingDothraki(context) >= 2,
            target: {
                type: 'select',
                numCards: 2,
                cardCondition: (card, context) => (
                    card.isMatch({ trait: 'Dothraki', type: 'character', location: ['hand', 'discard pile'] }) &&
                    card.controller === context.player &&
                    context.player.canPutIntoPlay(card)
                )
            },
            handler: context => {
                for(const card of context.target) {
                    context.player.putIntoPlay(card, 'play', { kneeled: true });
                    this.game.currentChallenge.addAttacker(card);
                    this.atEndOfChallenge(ability => ({
                        match: card,
                        effect: ability.effects.returnToHandIfStillInPlay(true, 'challenge')
                    }));
                }

                this.game.addMessage('{0} plays {1} to put {2} into play from their hand knelt, participating as attackers',
                    context.player, this, context.target);
            },
            max: ability.limit.perChallenge(1)
        });
    }

    getNumberOfAttackingDothraki(context) {
        return context.player.getNumberOfCardsInPlay({ trait: 'Dothraki', type: 'character', attacking: true });
    }
}

OverwhelmingNumbers.code = '15022';

module.exports = OverwhelmingNumbers;
<|endoftext|>


<commit_before>const DrawCard = require('../../../drawcard.js');

class IronFleetScout extends DrawCard {
    setupCardAbilities() {
        this.action({
            title: 'Kneel this card to give a character +1 STR',
            method: 'kneel'
        });
    }

    kneel(player) {
        if(this.location !== 'play area' || !this.game.currentChallenge || this.kneeled) {
            return false;
        }

        this.game.promptForSelect(player, {
            cardCondition: card => this.cardCondition(card),
            activePromptTitle: 'Select character to gain STR',
            waitingPromptTitle: 'Waiting for opponent to use ' + this.name,
            onSelect: (player, card) => this.onCardSelected(player, card)
        });
    }

    cardCondition(card) {
        return card.getType() === 'character' && card.location === 'play area' && this.game.currentChallenge.isParticipating(card) && card.getFaction() === 'greyjoy';
    }

    onCardSelected(player, card) {
        var strength = player.firstPlayer ? 2 : 1;
        player.kneelCard(this);
        this.game.addMessage('{0} kneels {1} to give {2} +{3} STR until the end of the challenge', player, this, card, strength);
        this.untilEndOfPhase(ability => ({
            match: card,
            effect: ability.effects.modifyStrength(strength)
        }));

        return true;
    }
}

IronFleetScout.code = '01079';

module.exports = IronFleetScout;
<commit_msg>Make Iron Fleet Scout last until end of challenge (#321)<commit_after>const DrawCard = require('../../../drawcard.js');

class IronFleetScout extends DrawCard {
    setupCardAbilities() {
        this.action({
            title: 'Kneel this card to give a character +1 STR',
            method: 'kneel'
        });
    }

    kneel(player) {
        if(this.location !== 'play area' || !this.game.currentChallenge || this.kneeled) {
            return false;
        }

        this.game.promptForSelect(player, {
            cardCondition: card => this.cardCondition(card),
            activePromptTitle: 'Select character to gain STR',
            waitingPromptTitle: 'Waiting for opponent to use ' + this.name,
            onSelect: (player, card) => this.onCardSelected(player, card)
        });
    }

    cardCondition(card) {
        return card.getType() === 'character' && card.location === 'play area' && this.game.currentChallenge.isParticipating(card) && card.getFaction() === 'greyjoy';
    }

    onCardSelected(player, card) {
        var strength = player.firstPlayer ? 2 : 1;
        player.kneelCard(this);
        this.game.addMessage('{0} kneels {1} to give {2} +{3} STR until the end of the challenge', player, this, card, strength);
        this.untilEndOfChallenge(ability => ({
            match: card,
            effect: ability.effects.modifyStrength(strength)
        }));

        return true;
    }
}

IronFleetScout.code = '01079';

module.exports = IronFleetScout;
<|endoftext|>


<commit_before>module.exports = {
    "Dagens bedrift": "PRESENTATIONS",
    "Fest og moro": "NIGHTLIFE",
    "Konsert": "MUSIC",
    "Kurs og events": "PRESENTATIONS",
    "Revy og teater": "PERFORMANCES",
    "Foredrag": "PRESENTATIONS",
    "Møte": "DEBATE",
    "Happening": "NIGHTLIFE",
    "Kurs": "OTHER",
    "Show": "PERFORMANCES",
    "Fotballkamp": "SPORT",
    "Film": "PRESENTATIONS",
    "Samfundsmøte": "DEBATE",
    "Excenteraften": "DEBATE",
    "Temafest": "NIGHTLIFE",
    "Bokstavelig talt": "DEBATE",
    "Quiz": "OTHER",
    "DJ": "MUSIC",
    "Teater": "PERFORMANCES",
    "Annet": "OTHER",
    "Kurs": "PRESENTATIONS",
    "Omvising": "PRESENTATIONS",
    "Samfunn": "DEBATE",
    "Festival": "PERFORMANCES",
    "Sport": "SPORT",
    "Forestilling": "PERFORMANCES",
    "Utstilling" : "EXHIBITIONS"
};
<commit_msg>Add category mapping for "festmøte"<commit_after>module.exports = {
    "Dagens bedrift": "PRESENTATIONS",
    "Fest og moro": "NIGHTLIFE",
    "Konsert": "MUSIC",
    "Kurs og events": "PRESENTATIONS",
    "Revy og teater": "PERFORMANCES",
    "Foredrag": "PRESENTATIONS",
    "Møte": "DEBATE",
    "Happening": "NIGHTLIFE",
    "Kurs": "OTHER",
    "Show": "PERFORMANCES",
    "Fotballkamp": "SPORT",
    "Film": "PRESENTATIONS",
    "Samfundsmøte": "DEBATE",
    "Excenteraften": "DEBATE",
    "Temafest": "NIGHTLIFE",
    "Bokstavelig talt": "DEBATE",
    "Quiz": "OTHER",
    "DJ": "MUSIC",
    "Teater": "PERFORMANCES",
    "Annet": "OTHER",
    "Kurs": "PRESENTATIONS",
    "Omvising": "PRESENTATIONS",
    "Samfunn": "DEBATE",
    "Festival": "PERFORMANCES",
    "Sport": "SPORT",
    "Forestilling": "PERFORMANCES",
    "Utstilling" : "EXHIBITIONS",
    "Festmøte" : "DEBATE"
};
<|endoftext|>


<commit_before>/*
 * The competition store keeps track of competitions that are in progress.
 * The store's purpose is to minimise DB I/O if the open competitions need
 * to be queried often.
 */
import { db, io } from './main';
import { loadCompetitionResults } from './api/competition';
import { snakeToCamel } from './util';

export const competitions = {}; // Competition store, map from id to competition
const clients = {};      // Client sockets by socket ID (i.e. socket.id -> socket map)

const competitionDurationHours = 24;

// Send list of competitions to all connected sockets.
// Results need to be camelCased for correct object property names
// when restoring competitions from database upon startup.
function broadcastCompetitions() {
  io.sockets.emit('competitionListUpdate', snakeToCamel(competitions));
}

// Send list of competition result to all connected clients
function broadcastCompetitionResults(competitionId) {
  io.sockets.emit('competitionResultsUpdate', {
    competition: competitionId,
    results: competitions[competitionId].results,
  });
}

// Adds typing test object to the competition store
export function addCompetition(competition) {
  competition.duration = competitionDurationHours;
  competitions[competition.id] = competition;
  competitions[competition.id].results = {};

  broadcastCompetitions();
  // Keep competition open for 24 hours
  setTimeout(closeCompetition, competitionDurationHours * 60 * 60 * 1000, competition.id);
}

// Adds a result to competition. Result is expected to be an
// object containing necessary fields to describe the result.
export function addResult(competitionId, result) {
  const userCurrentResult = competitions[competitionId].results[result.user.id];
  if (!userCurrentResult || result.wpm > userCurrentResult.wpm) {
    competitions[competitionId].results[result.user.id] = result;
    broadcastCompetitionResults(competitionId);
  }
}

export function getCompetitionContent(competitionId) {
  return competitions[competitionId].content;
}

// Closes a competition:
//  - set status to finished
//  - create a competition 'finished' event
//  - create notification for all participants about competition begin finished
function closeCompetition(competitionId) {
  let eventId;

  db.query('SELECT close_competition($1)', [competitionId])
    .then(result => {
      eventId = result.rows[0].close_competition;
      return getParticipants(competitionId);
    })
    .then(users => {
      // Remove the competition from store and send updated store to clients
      delete(competitions[competitionId]);
      broadcastCompetitions();

      // Create notifications about finished competition
      const notifyTasks = users.map(userId =>
        db.query('INSERT INTO notifications(usr, event) VALUES($1, $2)',
          [userId, eventId]));

      return Promise.all(notifyTasks);
    })
    .catch(err => {
      console.log('Warning: failed to close competition.\n' +
        'competition id: ' + competitionId + '\n' + err.message + '\n');
    });
}

// Get competition participants.
// Returns an array of user ids.
function getParticipants(competitionId) {
  return new Promise((resolve, reject) =>
    db.query('SELECT usr FROM results WHERE competition=$1', [competitionId])
      .then(result => resolve(result.rows.map(row => row.usr)))
      .catch(err => reject(err)));
}

// Helper to restore in-progress competitions from db when starting the server
// --- NOTE: if a competition would have been finished while the server was not running,
// and should thus have been closed but was not because the server indeed was not running,
// then such a competition will, in fact, enjoy eternal life.
// It's a bug, yes, but this restore functionality exists solely on making the developing of the
// application more pleasant and therefore this the bug doesn't bother us too much at this point.
// It could be fixed, but I'd rather take the time to write this comment than think about
// timestamps and setTimeouts.
export function restoreCompetitions() {
  db.query('SELECT id, created_at, created_by, finished, content, language, duration FROM competitions WHERE finished=false')
    .then(result => {
      result.rows.forEach(competition => {
        competitions[competition.id] = competition;
        competition.results = {};
        loadCompetitionResults(competition.id).then(results => {
          results.forEach(result => {
            addResult(competition.id, result);
          });
        });
      });
    })
    .catch(err => {
      console.log("Warning: can't restore competitions from db");
    });
}

// newClient(): stores client socket to client pool when they connect.
// On disconnect, remove clients from the pool.
export function newClient(clientSocket) {
  clients[clientSocket.id] = clientSocket;
  clientSocket.on('disconnect', () => delete (clients[clientSocket.id]));
  broadcastCompetitions();
}

export function getRunningCompetitions() {
  return Object.keys(competitions).map(key => {
    const { id, language, createdAt, createdBy, duration, finished, content }  = competitions[key];
    return {
      id, language, createdAt, createdBy, duration, finished, content,
    };
  });
}<commit_msg>Fix typo in comment<commit_after>/*
 * The competition store keeps track of competitions that are in progress.
 * The store's purpose is to minimise DB I/O if the open competitions need
 * to be queried often.
 */
import { db, io } from './main';
import { loadCompetitionResults } from './api/competition';
import { snakeToCamel } from './util';

export const competitions = {}; // Competition store, map from id to competition
const clients = {};      // Client sockets by socket ID (i.e. socket.id -> socket map)

const competitionDurationHours = 24;

// Send list of competitions to all connected sockets.
// Results need to be camelCased for correct object property names
// when restoring competitions from database upon startup.
function broadcastCompetitions() {
  io.sockets.emit('competitionListUpdate', snakeToCamel(competitions));
}

// Send list of competition result to all connected clients
function broadcastCompetitionResults(competitionId) {
  io.sockets.emit('competitionResultsUpdate', {
    competition: competitionId,
    results: competitions[competitionId].results,
  });
}

// Adds typing test object to the competition store
export function addCompetition(competition) {
  competition.duration = competitionDurationHours;
  competitions[competition.id] = competition;
  competitions[competition.id].results = {};

  broadcastCompetitions();
  // Keep competition open for 24 hours
  setTimeout(closeCompetition, competitionDurationHours * 60 * 60 * 1000, competition.id);
}

// Adds a result to competition. Result is expected to be an
// object containing necessary fields to describe the result.
export function addResult(competitionId, result) {
  const userCurrentResult = competitions[competitionId].results[result.user.id];
  if (!userCurrentResult || result.wpm > userCurrentResult.wpm) {
    competitions[competitionId].results[result.user.id] = result;
    broadcastCompetitionResults(competitionId);
  }
}

export function getCompetitionContent(competitionId) {
  return competitions[competitionId].content;
}

// Closes a competition:
//  - set status to finished
//  - create a competition 'finished' event
//  - create notification for all participants about competition being finished
function closeCompetition(competitionId) {
  let eventId;

  db.query('SELECT close_competition($1)', [competitionId])
    .then(result => {
      eventId = result.rows[0].close_competition;
      return getParticipants(competitionId);
    })
    .then(users => {
      // Remove the competition from store and send updated store to clients
      delete(competitions[competitionId]);
      broadcastCompetitions();

      // Create notifications about finished competition
      const notifyTasks = users.map(userId =>
        db.query('INSERT INTO notifications(usr, event) VALUES($1, $2)',
          [userId, eventId]));

      return Promise.all(notifyTasks);
    })
    .catch(err => {
      console.log('Warning: failed to close competition.\n' +
        'competition id: ' + competitionId + '\n' + err.message + '\n');
    });
}

// Get competition participants.
// Returns an array of user ids.
function getParticipants(competitionId) {
  return new Promise((resolve, reject) =>
    db.query('SELECT usr FROM results WHERE competition=$1', [competitionId])
      .then(result => resolve(result.rows.map(row => row.usr)))
      .catch(err => reject(err)));
}

// Helper to restore in-progress competitions from db when starting the server
// --- NOTE: if a competition would have been finished while the server was not running,
// and should thus have been closed but was not because the server indeed was not running,
// then such a competition will, in fact, enjoy eternal life.
// It's a bug, yes, but this restore functionality exists solely on making the developing of the
// application more pleasant and therefore this the bug doesn't bother us too much at this point.
// It could be fixed, but I'd rather take the time to write this comment than think about
// timestamps and setTimeouts.
export function restoreCompetitions() {
  db.query('SELECT id, created_at, created_by, finished, content, language, duration FROM competitions WHERE finished=false')
    .then(result => {
      result.rows.forEach(competition => {
        competitions[competition.id] = competition;
        competition.results = {};
        loadCompetitionResults(competition.id).then(results => {
          results.forEach(result => {
            addResult(competition.id, result);
          });
        });
      });
    })
    .catch(err => {
      console.log("Warning: can't restore competitions from db");
    });
}

// newClient(): stores client socket to client pool when they connect.
// On disconnect, remove clients from the pool.
export function newClient(clientSocket) {
  clients[clientSocket.id] = clientSocket;
  clientSocket.on('disconnect', () => delete (clients[clientSocket.id]));
  broadcastCompetitions();
}

export function getRunningCompetitions() {
  return Object.keys(competitions).map(key => {
    const { id, language, createdAt, createdBy, duration, finished, content }  = competitions[key];
    return {
      id, language, createdAt, createdBy, duration, finished, content,
    };
  });
}<|endoftext|>


<commit_before>'use strict'

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

var DLModels = require('dl-models');
var map = DLModels.map;
var WindingProductionOutput = DLModels.production.spinning.winding.WindingProductionOutput;
var ProductManager = require('../../../master/product-manager');
var MachineManager = require('../../../master/machine-manager');
var UnitManager = require('../../../master/unit-manager');
var ThreadSpecificationManager = require('../../../master/thread-specification-manager');
var LotMachineManager = require('../../../master/lot-machine-manager');
var BaseManager = require('../../../base-manager');
var i18n = require('dl-i18n');
var DailySpinningProductionReportManager = require('../daily-spinning-production-report-manager');

module.exports = class WindingProductionOutputManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.collection(map.production.spinning.winding.collection.WindingProductionOutput);
        this.productManager = new ProductManager(db, user);
        this.machineManager = new MachineManager(db, user);
        this.unitManager = new UnitManager(db, user);
        this.lotmachineManager = new LotMachineManager(db, user);
        this.threadSpecificationManager = new ThreadSpecificationManager(db, user);
        this.dailySpinningProductionReportManager = new DailySpinningProductionReportManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterSpinning = {
                'unit.name': {
                    '$regex': regex
                }
            };
            var filterMachineCode = {
                "machine.code": {
                    '$regex': regex
                }
            };
            var filterMachineName = {
                'machine.name': {
                    '$regex': regex
                }
            };
            var filterThreadCode = {
                "product.code": {
                    '$regex': regex
                }
            };
            var filterThreadName = {
                "product.name": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterSpinning, filterMachineCode, filterMachineName, filterThreadCode, filterThreadName]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }

    _validate(windingProductionOutput) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = windingProductionOutput;
            // 1. begin: Declare promises.
            var getWindingProductionOutputPromise = this.collection.singleOrDefault({
                    "$and" : [{
                        _id : {
                            "$ne" : new ObjectId(valid._id)
                    }
                    },{
                        _deleted : false
                    },{
                        date : valid.date
                    },{
                        productId : valid.productId && ObjectId.isValid(valid.productId) ? (new ObjectId(valid.productId)) : ''
                    },{
                        machineId : valid.machine && ObjectId.isValid(valid.machine._id) ? (new ObjectId(valid.machine._id)) : ''
                    },{
                        shift : valid.shift
                    },{
                        unitId : valid.unitId && ObjectId.isValid(valid.unitId) ? (new ObjectId(valid.unitId)) : ''
                }]
            });

            var getProduct = valid.productId && ObjectId.isValid(valid.productId) ? this.productManager.getSingleByIdOrDefault(valid.productId) : Promise.resolve(null);
            var getMachine = valid.machineId && ObjectId.isValid(valid.machineId) ? this.machineManager.getSingleByIdOrDefault(valid.machineId) : Promise.resolve(null);
            var getUnit = valid.unitId && ObjectId.isValid(valid.unitId) ? this.unitManager.getSingleByIdOrDefault(valid.unitId) : Promise.resolve(null);
            var queryProduct=
            {
                filter : {
                        productId : ObjectId.isValid(valid.productId) ? new ObjectId(valid.productId) : ''
                }
            };
            var getLotMachine = valid.productId && ObjectId.isValid(valid.productId) ? this.lotmachineManager.read(queryProduct) : Promise.resolve(null);
            var getThreadSpecification = valid.productId && ObjectId.isValid(valid.productId) ? this.threadSpecificationManager.read(queryProduct) : Promise.resolve(null);
            Promise.all([getWindingProductionOutputPromise, getProduct, getMachine, getLotMachine, getThreadSpecification, getUnit])
             .then(results =>{
                var _module = results[0];
                var _product = results[1];
                var _machine = results[2];
                var _lotmachine = results[3];
                var _threadSpecification = results[4];
                var _unit= results[5];
                var _Lm=null;
                var _Ts=null;
                var now = new Date();
                valid.product=_product;
                valid.unitId=new ObjectId(_unit._id);
                valid.machineId=new ObjectId(_machine._id);
                valid.productId=new ObjectId(_product._id);
                if(_lotmachine)
                {
                    if(_lotmachine.data.length > 0){
                        for(var a of _lotmachine.data)
                        {
                            if(a.productId==valid.productId && a.machineId==valid.machineId) {
                            // if(a._id.toString() == valid.lotMachineId.toString()) {
                                _Lm = a;
                                break;
                            }
                        }
                    }
                }

                if(_threadSpecification)
                {
                    if(_threadSpecification.data.length > 0){
                        for(var b of _threadSpecification.data)
                        {
                            if(b.productId==valid.productId) {
                            // if(b._id.toString() == valid.threadSpecificationId.toString()) {
                                _Ts = b;
                                break;
                            }
                        }
                    }
                }

                if(_module){
                    errors["shift"] = i18n.__(`WindingProductionOutput.shift.isRequired:%s with same Product, Machine, Spinning and Date is already exists`, i18n.__("WindingQualitySampling.shift._:Shift")); //"Spinning dengan produk, mesin dan tanggal,shift,dan mesin yang sama tidak boleh";
                }

                if (!valid.shift || valid.shift == '')
                    errors["shift"] = i18n.__("WindingProductionOutput.shift.isRequired:%s is required", i18n.__("WindingProductionOutput.shift._:Shift"));

                if (!_unit)
                    errors["unit"] = i18n.__("WindingProductionOutput.unit.isRequired:%s is not exists", i18n.__("WindingProductionOutput.unit._:Unit"));

                else if (!valid.unitId)
                    errors["unit"] = i18n.__("WindingProductionOutput.unit.isRequired:%s is required", i18n.__("WindingProductionOutput.unit._:Unit"));
                else if (valid.unit) {
                    if (!valid.unit._id)
                        errors["unit"] = i18n.__("WindingProductionOutput.unit.isRequired:%s is required", i18n.__("WindingProductionOutput.unit._:Unit"));

                }

                if (!valid.date || valid.date == '')
                        errors["date"] = i18n.__("WindingProductionOutput.date.isRequired:%s is required", i18n.__("WindingProductionOutput.date._:Date"));

                if (!valid.threadWeight || valid.threadWeight == 0)
                        errors["threadWeight"] = i18n.__("WindingProductionOutput.threadWeight.isRequired:%s is required", i18n.__("WindingProductionOutput.threadWeight._:ThreadWeight"));

                if (!valid.goodCone || valid.goodCone == 0)
                        errors["goodCone"] = i18n.__("WindingProductionOutput.goodCone.isRequired:%s is required", i18n.__("WindingProductionOutput.goodCone._:GoodCone"));

                if (!valid.drum || valid.drum == 0)
                        errors["drum"] = i18n.__("WindingProductionOutput.drum.isRequired:%s is required", i18n.__("WindingProductionOutput.drum._:Drum"));

                if (!_product)
                    errors["product"] = i18n.__("WindingProductionOutput.product.isRequired:%s is not exists", i18n.__("WindingProductionOutput.product._:Product"));
                else if (!valid.productId)
                    errors["product"] = i18n.__("WindingProductionOutput.product.isRequired:%s is required", i18n.__("WindingProductionOutput.product._:Product"));
                else if (valid.product) {
                    if (!valid.product._id)
                        errors["product"] = i18n.__("WindingProductionOutput.product.isRequired:%s is required", i18n.__("WindingProductionOutput.product._:Product"));

                }

                if (!_machine)
                    errors["machine"] = i18n.__("WindingProductionOutput.machine.isRequired:%s is not exists", i18n.__("WindingProductionOutput.machine._:Machine"));
                else if (!valid.productId)
                    errors["machine"] = i18n.__("WindingProductionOutput.machine.isRequired:%s is required", i18n.__("WindingProductionOutput.machine._:Machine"));
                else if (valid.machine) {
                    if (!valid.machine._id)
                        errors["machine"] = i18n.__("WindingProductionOutput.machine.isRequired:%s is required", i18n.__("WindingProductionOutput.machine._:Machine"));
                }

                if(_Lm)
                {
                    valid.lotMachine=_Lm;
                    valid.lotMachineId=new ObjectId(_Lm._id);
                }
                if(_Ts)
                {
                    valid.threadSpecification=_Ts;
                    valid.threadSpecificationId=new ObjectId(_Ts._id);
                }

                if (!_Lm)
                    errors["lotMachine"] = i18n.__("WindingProductionOutput.lotMachine.isRequired:%s is not exists", i18n.__("WindingProductionOutput.lotMachine._:LotMachine"));
                else if (!valid.lotMachineId)
                    errors["lotMachine"] = i18n.__("WindingProductionOutput.lotMachine.isRequired:%s is required", i18n.__("WindingProductionOutput.lotMachine._:LotMachine"));
                else if (valid.lotMachine) {
                    if (!valid.lotMachine._id)
                        errors["lotMachine"] = i18n.__("WindingProductionOutput.lotMachine.isRequired:%s is required", i18n.__("WindingProductionOutput.lotMachine._:LotMachine"));
                }

                if (!_Ts)
                    errors["product"] = i18n.__("WindingProductionOutput.threadSpecification.isRequired:%s is not exists", i18n.__("WindingProductionOutput.threadSpecification._:ThreadSpecification"));
                else if (!valid.threadSpecificationId)
                    errors["product"] = i18n.__("WindingProductionOutput.threadSpecification.isRequired:%s is required", i18n.__("WindingProductionOutput.threadSpecification._:ThreadSpecification"));
                else if (valid.threadSpecification) {
                    if (!valid.threadSpecification._id)
                        errors["product"] = i18n.__("WindingProductionOutput.threadSpecification.isRequired:%s is required", i18n.__("WindingProductionOutput.threadSpecification._:ThreadSpecification"));
                }

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('../../../../validation-error');
                    reject(new ValidationError('data does not pass validation', errors));
                }

                valid = new WindingProductionOutput(windingProductionOutput);
                valid.stamp(this.user.username, 'manager');
                resolve(valid);
             })
             .catch(e => {
                    reject(e);
                })
        });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingProductionOutput}__updatedDate`,

            key: {
                _updatedDate: -1
            }
        }

        var codeIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingProductionOutput}_unitId_date_shift_machineId_productId`,
            key: {
                unitId: 1,
                date: 1,
                shift:1,
                machineId: 1,
                productId: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }

    create(data) {
        var _outputId;
        return new Promise((resolve, reject) => {
            super.create(data)
            .then(id => {
                _outputId = id;
                this.dailySpinningProductionReportManager.addOutput(data)
                    .then(result => {
                        resolve(id);
                    })
                    .catch(e => {
                        reject(e);
                    })
            })
            .catch(e => {
                var p = [];
                if (_outputId)
                    p.push(this._delete(_outputId));

                    Promise.all(p)
                        .then(results => {
                            reject(e);
                        })
                        .catch(e => {
                            reject(e);
                        });
            })
        });
    }
}<commit_msg>fixing validation<commit_after>'use strict'

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

var DLModels = require('dl-models');
var map = DLModels.map;
var WindingProductionOutput = DLModels.production.spinning.winding.WindingProductionOutput;
var ProductManager = require('../../../master/product-manager');
var MachineManager = require('../../../master/machine-manager');
var UnitManager = require('../../../master/unit-manager');
var ThreadSpecificationManager = require('../../../master/thread-specification-manager');
var LotMachineManager = require('../../../master/lot-machine-manager');
var BaseManager = require('../../../base-manager');
var i18n = require('dl-i18n');
var DailySpinningProductionReportManager = require('../daily-spinning-production-report-manager');

module.exports = class WindingProductionOutputManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.collection(map.production.spinning.winding.collection.WindingProductionOutput);
        this.productManager = new ProductManager(db, user);
        this.machineManager = new MachineManager(db, user);
        this.unitManager = new UnitManager(db, user);
        this.lotmachineManager = new LotMachineManager(db, user);
        this.threadSpecificationManager = new ThreadSpecificationManager(db, user);
        this.dailySpinningProductionReportManager = new DailySpinningProductionReportManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterSpinning = {
                'unit.name': {
                    '$regex': regex
                }
            };
            var filterMachineCode = {
                "machine.code": {
                    '$regex': regex
                }
            };
            var filterMachineName = {
                'machine.name': {
                    '$regex': regex
                }
            };
            var filterThreadCode = {
                "product.code": {
                    '$regex': regex
                }
            };
            var filterThreadName = {
                "product.name": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterSpinning, filterMachineCode, filterMachineName, filterThreadCode, filterThreadName]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }

    _validate(windingProductionOutput) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = windingProductionOutput;
            // 1. begin: Declare promises.
            var getWindingProductionOutputPromise = this.collection.singleOrDefault({
                    "$and" : [{
                        _id : {
                            "$ne" : new ObjectId(valid._id)
                    }
                    },{
                        _deleted : false
                    },{
                        date : valid.date
                    },{
                        productId : valid.productId && ObjectId.isValid(valid.productId) ? (new ObjectId(valid.productId)) : ''
                    },{
                        machineId : valid.machine && ObjectId.isValid(valid.machine._id) ? (new ObjectId(valid.machine._id)) : ''
                    },{
                        shift : valid.shift
                    },{
                        unitId : valid.unitId && ObjectId.isValid(valid.unitId) ? (new ObjectId(valid.unitId)) : ''
                }]
            });

            var getProduct = valid.productId && ObjectId.isValid(valid.productId) ? this.productManager.getSingleByIdOrDefault(valid.productId) : Promise.resolve(null);
            var getMachine = valid.machineId && ObjectId.isValid(valid.machineId) ? this.machineManager.getSingleByIdOrDefault(valid.machineId) : Promise.resolve(null);
            var getUnit = valid.unitId && ObjectId.isValid(valid.unitId) ? this.unitManager.getSingleByIdOrDefault(valid.unitId) : Promise.resolve(null);
            var queryProduct=
            {
                filter : {
                        productId : ObjectId.isValid(valid.productId) ? new ObjectId(valid.productId) : ''
                }
            };
            var getLotMachine = valid.productId && ObjectId.isValid(valid.productId) ? this.lotmachineManager.read(queryProduct) : Promise.resolve(null);
            var getThreadSpecification = valid.productId && ObjectId.isValid(valid.productId) ? this.threadSpecificationManager.read(queryProduct) : Promise.resolve(null);
            Promise.all([getWindingProductionOutputPromise, getProduct, getMachine, getLotMachine, getThreadSpecification, getUnit])
             .then(results =>{
                var _module = results[0];
                var _product = results[1];
                var _machine = results[2];
                var _lotmachine = results[3];
                var _threadSpecification = results[4];
                var _unit= results[5];
                var _Lm=null;
                var _Ts=null;
                var now = new Date();
                valid.product=_product;
                if(_lotmachine)
                {
                    if(_lotmachine.data.length > 0){
                        for(var a of _lotmachine.data)
                        {
                            if(a.productId==valid.productId && a.machineId==valid.machineId) {
                            // if(a._id.toString() == valid.lotMachineId.toString()) {
                                _Lm = a;
                            }
                        }
                    }
                }

                if(_threadSpecification)
                {
                    if(_threadSpecification.data.length > 0){
                        for(var b of _threadSpecification.data)
                        {
                            if(b.productId=valid.productId) {
                            // if(b._id.toString() == valid.threadSpecificationId.toString()) {
                                _Ts = b;
                            }
                        }
                    }
                }

                if(_module){
                    errors["shift"] = i18n.__(`WindingProductionOutput.shift.isRequired:%s with same Product, Machine, Spinning and Date is already exists`, i18n.__("WindingQualitySampling.shift._:Shift")); //"Spinning dengan produk, mesin dan tanggal,shift,dan mesin yang sama tidak boleh";
                }

                if (!valid.shift || valid.shift == '')
                    errors["shift"] = i18n.__("WindingProductionOutput.shift.isRequired:%s is required", i18n.__("WindingProductionOutput.shift._:Shift"));

                if (!_unit)
                    errors["unit"] = i18n.__("WindingProductionOutput.unit.isRequired:%s is not exists", i18n.__("WindingProductionOutput.unit._:Unit"));

                else if (!valid.unitId)
                    errors["unit"] = i18n.__("WindingProductionOutput.unit.isRequired:%s is required", i18n.__("WindingProductionOutput.unit._:Unit"));
                else if (valid.unit) {
                    if (!valid.unit._id)
                        errors["unit"] = i18n.__("WindingProductionOutput.unit.isRequired:%s is required", i18n.__("WindingProductionOutput.unit._:Unit"));

                }

                if (!valid.date || valid.date == '')
                        errors["date"] = i18n.__("WindingProductionOutput.date.isRequired:%s is required", i18n.__("WindingProductionOutput.date._:Date"));

                if (!valid.threadWeight || valid.threadWeight == 0)
                        errors["threadWeight"] = i18n.__("WindingProductionOutput.threadWeight.isRequired:%s is required", i18n.__("WindingProductionOutput.threadWeight._:ThreadWeight"));

                if (!valid.goodCone || valid.goodCone == 0)
                        errors["goodCone"] = i18n.__("WindingProductionOutput.goodCone.isRequired:%s is required", i18n.__("WindingProductionOutput.goodCone._:GoodCone"));

                if (!valid.drum || valid.drum == 0)
                        errors["drum"] = i18n.__("WindingProductionOutput.drum.isRequired:%s is required", i18n.__("WindingProductionOutput.drum._:Drum"));

                if (!_product)
                    errors["product"] = i18n.__("WindingProductionOutput.product.isRequired:%s is not exists", i18n.__("WindingProductionOutput.product._:Product"));
                else if (!valid.productId)
                    errors["product"] = i18n.__("WindingProductionOutput.product.isRequired:%s is required", i18n.__("WindingProductionOutput.product._:Product"));
                else if (valid.product) {
                    if (!valid.product._id)
                        errors["product"] = i18n.__("WindingProductionOutput.product.isRequired:%s is required", i18n.__("WindingProductionOutput.product._:Product"));

                }

                if (!_machine)
                    errors["machine"] = i18n.__("WindingProductionOutput.machine.isRequired:%s is not exists", i18n.__("WindingProductionOutput.machine._:Machine"));
                else if (!valid.productId)
                    errors["machine"] = i18n.__("WindingProductionOutput.machine.isRequired:%s is required", i18n.__("WindingProductionOutput.machine._:Machine"));
                else if (valid.machine) {
                    if (!valid.machine._id)
                        errors["machine"] = i18n.__("WindingProductionOutput.machine.isRequired:%s is required", i18n.__("WindingProductionOutput.machine._:Machine"));
                }

                if(_Lm)
                {
                    valid.lotMachine=_Lm;
                    valid.lotMachineId=new ObjectId(_Lm._id);
                }
                if(_Ts)
                {
                    valid.threadSpecification=_Ts;
                    valid.threadSpecificationId=new ObjectId(_Ts._id);
                }

                if (!_Lm)
                    errors["lotMachine"] = i18n.__("WindingProductionOutput.lotMachine.isRequired:%s is not exists", i18n.__("WindingProductionOutput.lotMachine._:LotMachine"));
                else if (!valid.lotMachineId)
                    errors["lotMachine"] = i18n.__("WindingProductionOutput.lotMachine.isRequired:%s is required", i18n.__("WindingProductionOutput.lotMachine._:LotMachine"));
                else if (valid.lotMachine) {
                    if (!valid.lotMachine._id)
                        errors["lotMachine"] = i18n.__("WindingProductionOutput.lotMachine.isRequired:%s is required", i18n.__("WindingProductionOutput.lotMachine._:LotMachine"));
                }

                if (!_Ts)
                    errors["product"] = i18n.__("WindingProductionOutput.threadSpecification.isRequired:%s is not exists", i18n.__("WindingProductionOutput.threadSpecification._:ThreadSpecification"));
                else if (!valid.threadSpecificationId)
                    errors["product"] = i18n.__("WindingProductionOutput.threadSpecification.isRequired:%s is required", i18n.__("WindingProductionOutput.threadSpecification._:ThreadSpecification"));
                else if (valid.threadSpecification) {
                    if (!valid.threadSpecification._id)
                        errors["product"] = i18n.__("WindingProductionOutput.threadSpecification.isRequired:%s is required", i18n.__("WindingProductionOutput.threadSpecification._:ThreadSpecification"));
                }

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('../../../../validation-error');
                    reject(new ValidationError('data does not pass validation', errors));
                }
                valid.unitId=new ObjectId(_unit._id);
                valid.machineId=new ObjectId(_machine._id);
                valid.productId=new ObjectId(_product._id);

                valid = new WindingProductionOutput(windingProductionOutput);
                valid.stamp(this.user.username, 'manager');
                resolve(valid);
             })
             .catch(e => {
                    reject(e);
                })
        });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingProductionOutput}__updatedDate`,

            key: {
                _updatedDate: -1
            }
        }

        var codeIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingProductionOutput}_unitId_date_shift_machineId_productId`,
            key: {
                unitId: 1,
                date: 1,
                shift:1,
                machineId: 1,
                productId: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }

    create(data) {
        var _outputId;
        return new Promise((resolve, reject) => {
            super.create(data)
            .then(id => {
                _outputId = id;
                this.dailySpinningProductionReportManager.addOutput(data)
                    .then(result => {
                        resolve(id);
                    })
                    .catch(e => {
                        reject(e);
                    })
            })
            .catch(e => {
                var p = [];
                if (_outputId)
                    p.push(this._delete(_outputId));

                    Promise.all(p)
                        .then(results => {
                            reject(e);
                        })
                        .catch(e => {
                            reject(e);
                        });
            })
        });
    }
}<|endoftext|>


<commit_before>module.exports = function (gulp, plugins) {
    var del = require('del');
    return {
        compass: function (srcFiles, outputFilename, config) {
            if (!config.compassSassFolder) {
                throw "The environment variable `compassSassFolder` must be defined";
            }

            // Filtro i CSS perchè non devono essere parsati da compass. Verrà
            // rimosso quando manderemo a cagare compass
            const filter = plugins.filter(['**', '!**/*.css'], {restore: true});
            // TODO: remove gulp-compass ASAP and use gulp-sass instead
            var promise = gulp.src(srcFiles)
                .pipe(plugins.plumber())
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
                .pipe(plugins.debug())
                .pipe(filter)
                .pipe(plugins.compass({
                    require: ['sass-globbing'],
                    sass: config.compassSassFolder
                }))
                .pipe(filter.restore)
                .pipe(plugins.concat(config.cssPath + outputFilename))
                .pipe(config.production ? plugins.minifyCss() : plugins.util.noop());

            if (config.revManifest) {
                promise.pipe(plugins.rev());
            }

            promise
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
                .pipe(gulp.dest(config.publicPath))
                .on('end', function () {
                    // Necessario fino a quando non togliamo compass
                    del.sync('css')
                });

            if (config.revManifest) {
                // Write the rev-manifest.json file for gulp-rev
                promise.pipe(plugins.rev.manifest(config.revManifestPath, {
                    merge: true
                }));
            }

            promise.pipe(gulp.dest('.'));

            return promise;
        },
        style: function (src, outputFilename, config) {
            var promise = gulp.src(src)
                .pipe(plugins.plumber())
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
                .pipe(plugins.sassGlob())
                .pipe(plugins.sass())
                .pipe(plugins.autoprefixer())
                .pipe(plugins.concat(config.cssPath + outputFilename))
                .pipe(config.production ? plugins.minifyCss() : plugins.util.noop());

            if (config.revManifest) {
                promise.pipe(plugins.rev());
            }

            promise
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
                .pipe(gulp.dest(config.publicPath));

            if (config.revManifest) {
                promise.pipe(plugins.rev.manifest(config.revManifestPath, {
                    merge: true
                }));
            }

            promise.pipe(gulp.dest('.'));

            return promise;
        },
        script: function (src, outputFilename, config) {
            var promise = gulp.src(src)
                .pipe(plugins.plumber())
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
                .pipe(plugins.concat(config.jsPath + outputFilename))
                .pipe(config.production ? plugins.uglify() : plugins.util.noop());

            if (config.revManifest) {
                promise.pipe(plugins.rev());
            }

            promise
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
                .pipe(gulp.dest(config.publicPath));

            if (config.revManifest) {
                // Write the rev-manifest.json file for gulp-rev
                promise.pipe(plugins.rev.manifest(config.revManifestPath, {
                    merge: true
                }));
            }
            promise.pipe(gulp.dest('.'));

            return promise;
        },
        copy: function (srcFiles, outputDir, config) {
            return gulp.src(srcFiles)
                .pipe(gulp.dest(outputDir));
        }
    };
};<commit_msg>Fix option revision code<commit_after>module.exports = function (gulp, plugins) {
    var del = require('del');
    return {
        compass: function (srcFiles, outputFilename, config) {
            if (!config.compassSassFolder) {
                throw "The environment variable `compassSassFolder` must be defined";
            }

            // Filtro i CSS perchè non devono essere parsati da compass. Verrà
            // rimosso quando manderemo a cagare compass
            const filter = plugins.filter(['**', '!**/*.css'], {restore: true});
            // TODO: remove gulp-compass ASAP and use gulp-sass instead
            var promise = gulp.src(srcFiles)
                .pipe(plugins.plumber())
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
                .pipe(plugins.debug())
                .pipe(filter)
                .pipe(plugins.compass({
                    require: ['sass-globbing'],
                    sass: config.compassSassFolder
                }))
                .pipe(filter.restore)
                .pipe(plugins.concat(config.cssPath + outputFilename))
                .pipe(config.production ? plugins.minifyCss() : plugins.util.noop());

            if (config.revManifest) {
                promise = promise.pipe(plugins.rev());
            }

            promise = promise
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
                .pipe(gulp.dest(config.publicPath))
                .on('end', function () {
                    // Necessario fino a quando non togliamo compass
                    del.sync('css')
                });

            if (config.revManifest) {
                // Write the rev-manifest.json file for gulp-rev
                promise = promise.pipe(plugins.rev.manifest(config.revManifestPath, {
                    merge: true
                }));
            }

            promise = promise.pipe(gulp.dest('.'));

            return promise;
        },
        style: function (src, outputFilename, config) {
            var promise = gulp.src(src)
                .pipe(plugins.plumber())
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
                .pipe(plugins.sassGlob())
                .pipe(plugins.sass())
                .pipe(plugins.autoprefixer())
                .pipe(plugins.concat(config.cssPath + outputFilename))
                .pipe(config.production ? plugins.minifyCss() : plugins.util.noop());

            if (config.revManifest) {
                promise = promise.pipe(plugins.rev());
            }

            promise = promise
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
                .pipe(gulp.dest(config.publicPath));

            if (config.revManifest) {
                promise = promise.pipe(plugins.rev.manifest(config.revManifestPath, {
                    merge: true
                }));
            }

            promise = promise.pipe(gulp.dest('.'));

            return promise;
        },
        script: function (src, outputFilename, config) {
            var promise = gulp.src(src)
                .pipe(plugins.plumber())
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
                .pipe(plugins.concat(config.jsPath + outputFilename))
                .pipe(config.production ? plugins.uglify() : plugins.util.noop());

            if (config.revManifest) {
                promise = promise.pipe(plugins.rev());
            }

            promise = promise
                .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
                .pipe(gulp.dest(config.publicPath));

            if (config.revManifest) {
                // Write the rev-manifest.json file for gulp-rev
                promise = promise.pipe(plugins.rev.manifest(config.revManifestPath, {
                    merge: true
                }));
            }
            promise = promise.pipe(gulp.dest('.'));

            return promise;
        },
        copy: function (srcFiles, outputDir, config) {
            return gulp.src(srcFiles)
                .pipe(gulp.dest(outputDir));
        }
    };
};<|endoftext|>


<commit_before>/*global module*/
module.exports = function (grunt) {
    "use strict";

    grunt.initConfig({
        jslint: {
            files: ["src/main/javascript/**/*.js",
                    "src/test/javascript/**/*.js",
                    "Gruntfile.js"],
            exclude: ["src/main/javascript/lib/*.js"],
            directives: {
                plusplus: true,
                vars: true,
                nomen: true,
                todo: true,
                predef: ["define"]
            },
            options: {
                jslintXml: "target/jslint.xml",
                junit: "target/jslint-junit.xml",
                checkstyle: "target/jslint-checkstyle.xml"
            }
        },
        requirejs: {
            compile: {
                options: {
                    // Insert Almond AMD loader into output, so that we do not need to include the RequireJS script.
                    almond: true,
                    baseUrl: "src/main/javascript",
                    mainConfigFile: "src/main/javascript/config.js",
                    // Path to main.js, relative to the base URL
                    name: "main",
                    // Place output file here, Maven will handle the rest.
                    out: "target/resources/main.min.js",
                    logLevel: 1,
                    optimize: "uglify2",
                    // Must be turned off for source maps to work.
                    preserveLicenseComments: false,
                    generateSourceMaps: true
                }
            }
        },
        cssmin: {
            compress: {
                files: {
                    "target/resources/css/main.css": ["src/main/css/**/*.css"]
                },
                options: {
                    report: "min"
                }
            }
        },
        karma: {
            options: {
                configFile: "karma.conf.js"
            },
            unit: {
            },
            ci: {
                singleRun: true,
                reporters: ["progress", "coverage", "junit"],
                browsers: ["PhantomJS"],
                coverageReporter: {
                    type: "cobertura",
                    dir: "target/coverage/"
                },
                junitReporter: {
                    outputFile: "target/karma-junit.xml"
                }
            }
        }
    });

    // TODO consider using grunt-combine to generate index.html from dev.html

    grunt.loadNpmTasks("grunt-jslint");
    grunt.loadNpmTasks("grunt-requirejs");
    grunt.loadNpmTasks("grunt-contrib-cssmin");
    grunt.loadNpmTasks("grunt-karma");

    grunt.registerTask("default", ["jslint", "cssmin"]);

    // Maven will run these tasks in the named phase.
    grunt.registerTask("maven-compile", ["requirejs", "cssmin"]);
    // The PHANTOMJS_BIN environment variable must be set, Maven takes care of this.
    grunt.registerTask("maven-test", ["jslint", "karma:ci"]);
};<commit_msg>Teamcity experiment.<commit_after>/*global module*/
module.exports = function (grunt) {
    "use strict";

    grunt.initConfig({
        jslint: {
            files: ["src/main/javascript/**/*.js",
                    "src/test/javascript/**/*.js",
                    "Gruntfile.js"],
            exclude: ["src/main/javascript/lib/*.js"],
            directives: {
                plusplus: true,
                vars: true,
                nomen: true,
                todo: true,
                predef: ["define"]
            },
            options: {
                jslintXml: "target/jslint.xml",
                junit: "target/jslint-junit.xml",
                checkstyle: "target/jslint-checkstyle.xml"
            }
        },
        requirejs: {
            compile: {
                options: {
                    // Insert Almond AMD loader into output, so that we do not need to include the RequireJS script.
                    almond: true,
                    baseUrl: "src/main/javascript",
                    mainConfigFile: "src/main/javascript/config.js",
                    // Path to main.js, relative to the base URL
                    name: "main",
                    // Place output file here, Maven will handle the rest.
                    out: "target/resources/main.min.js",
                    logLevel: 1,
                    optimize: "uglify2",
                    // Must be turned off for source maps to work.
                    preserveLicenseComments: false,
                    generateSourceMaps: true
                }
            }
        },
        cssmin: {
            compress: {
                files: {
                    "target/resources/css/main.css": ["src/main/css/**/*.css"]
                },
                options: {
                    report: "min"
                }
            }
        },
        karma: {
            options: {
                configFile: "karma.conf.js"
            },
            unit: {
            },
            ci: {
                singleRun: true,
                reporters: ["progress", "coverage", "junit", "teamcity"],
                browsers: ["PhantomJS"],
                coverageReporter: {
                    type: "cobertura",
                    dir: "target/coverage/"
                },
                junitReporter: {
                    outputFile: "target/karma-junit.xml"
                }
            }
        }
    });

    // TODO consider using grunt-combine to generate index.html from dev.html

    grunt.loadNpmTasks("grunt-jslint");
    grunt.loadNpmTasks("grunt-requirejs");
    grunt.loadNpmTasks("grunt-contrib-cssmin");
    grunt.loadNpmTasks("grunt-karma");

    grunt.registerTask("default", ["jslint", "cssmin"]);

    // Maven will run these tasks in the named phase.
    grunt.registerTask("maven-compile", ["requirejs", "cssmin"]);
    // The PHANTOMJS_BIN environment variable must be set, Maven takes care of this.
    grunt.registerTask("maven-test", ["jslint", "karma:ci"]);
};<|endoftext|>