Example #1
0
        it('should return 404 if no genre with given id exists', async () => {
            const id = mongoose.Types.ObjectId();
            const res = await request(server).get('/api/genres/' + id);

            expect(res.status).toBe(404);
        });
Example #2
0
    it("should not create app with not existing user", function*() {
        var userResponse = yield dbHelper.createUser()
        var response = yield dbHelper.createApp(Mongoose.Types.ObjectId())

        response.statusCode.should.equal(STATUS_CODES.BAD_REQUEST)
    });
    entityConfig,
    loggedInUser,
    requiredStaffAccess,
    callback
  ) {
    if (callback == null) {
      callback = function(error, entity) {}
    }
    const query = buildEntityQuery(entityId, entityConfig)
    if (
      !loggedInUser.isAdmin &&
      !(loggedInUser.staffAccess != null
        ? loggedInUser.staffAccess[requiredStaffAccess]
        : undefined)
    ) {
      query[entityConfig.fields.access] = ObjectId(loggedInUser._id)
    }
    return EntityModels[entityConfig.modelName].findOne(query, callback)
  },

  getEntityWithoutAuthorizationCheck(entityId, entityConfig, callback) {
    if (callback == null) {
      callback = function(error, entity) {}
    }
    const query = buildEntityQuery(entityId, entityConfig)
    return EntityModels[entityConfig.modelName].findOne(query, callback)
  },

  createEntity(entityId, entityConfig, callback) {
    if (callback == null) {
      callback = function(error, entity) {}
describe("Cache Route Tests", function() {

  var sandbox;
  before(function(done) {
    sandbox = sinon.sandbox.create();
    var mongodbConfig = config.server.mongodb;

    var mongoUri = "mongodb://" + mongodbConfig.host + "/" + mongodbConfig.db;
    mongoose.connect(mongoUri, {server: {poolSize: mongodbConfig.poolSize}}, function(err) {
      if (err) {
        console.log('Error connecting to mongo database, please make sure mongodb is running...');
        throw err;
      }
      done();
    });
    mongoose.set('debug', true);
  });

  after(function(done) {
    mongoose.disconnect(function() {
      done();
    });
  });

  var userId = mongoose.Types.ObjectId();

  before(function() {
    var token = {
      _id: '1',
      token: '12345',
      userId: {
        populate: function(field, callback) {
          callback(null, {
            _id: userId,
            username: 'test',
            roleId: {
              permissions: ['CREATE_CACHE', 'READ_CACHE', 'DELETE_CACHE', 'EXPORT_CACHE']
            }
          });
        }
      }
    };

    sandbox.mock(TokenModel)
      .expects('findOne')
      .atLeast(0)
      .withArgs({token: "12345"})
      .chain('populate')
      .atLeast(0)
      .chain('exec')
      .atLeast(0)
      .yields(null, token);
  });

  after(function() {
    sandbox.restore();
  });

  describe("cache create tests", function() {

    var cacheId;

    var mapId;
    var map;

    beforeEach(function(done) {
      request(app)
        .post('/api/maps')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect('Content-Type', /json/)
        .send({
          dataSources: [{
            zOrder: 0,
            url: 'http://osm.geointservices.io/osm_tiles',
            format: 'xyz',
            valid: true,
            name: 'http://osm.geointservices.io/osm_tiles'
          }],
          name: 'OSM' }
        )
        .expect(function(res) {
          map = res.body;
          mapId = map.id;
        })
        .end(done);
    });

    afterEach(function(done) {
      if (!mapId) return done();
      Map.getById(mapId, function(err, map) {
        var m = new Map(map);
        m.delete(function() {
          if (!cacheId) return done();
          Cache.getById(cacheId, function(err, cache) {
            var c = new Cache(cache);
            c.delete(done);
          });
        });
      });
    });

    it("api should fail to create a cache because geometry is not specified", function(done) {
      startTest("api should fail to create a cache because geometry is not specified");
      request(app)
        .post('/api/caches')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer 12345')
        .expect(400)
        .send({
          sourceId: mapId,
          minZoom: 0,
          maxZoom: 3,
          name: 'Cache'
        })
        .expect(function(res) {
        })
        .end(done);
    });

    it("api should create a cache", function(done) {
      startTest("api should create a cache");
      request(app)
        .post('/api/caches')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect('Content-Type', /json/)
        .send({
          sourceId: mapId,
          minZoom: 0,
          maxZoom: 1,
          name: 'Cache',
          geometry: turf.bboxPolygon([-180, -85, 180, 85]).geometry
        })
        .expect(function(res) {
          var cache = res.body;
          cacheId = cache.id;
          cache.should.have.property('id');
          cache.should.have.property('userId', userId.toString());
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 1);
          cache.should.have.property('status');
        })
        .end(done);
    });

    it("api should create a cache and generate a format", function(done) {
      startTest("api should create a cache and generate a format");
      this.timeout(10000);
      request(app)
        .post('/api/caches')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect('Content-Type', /json/)
        .send({
          sourceId: mapId,
          minZoom: 0,
          maxZoom: 1,
          name: 'Cache',
          create: ['xyz'],
          geometry: turf.bboxPolygon([-180, -85, 180, 85]).geometry
        })
        .expect(function(res) {
          var cache = res.body;
          cacheId = cache.id;
          cache.should.have.property('id');
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 1);
          cache.should.have.property('status');
        })
        .end(function() {
          var finishedGenerating = false;
          console.log('until');
          async.until(
            function() { return finishedGenerating; },
            function(callback) {
              request(app)
                .get('/api/caches/'+cacheId)
                .set('Authorization', 'Bearer 12345')
                .expect(200)
                .expect(function(res) {
                  var cache = res.body;
                  if (!cache.status.complete) return;
                  cache.formats.should.have.property('xyz');
                  if (cache.formats.xyz.complete) {
                    cache.formats.xyz.should.have.property('generatedTiles', 5);
                    finishedGenerating = true;
                  }
                }).end(function() {
                  setTimeout(callback, 500);
                });
            },
            function() {
              done();
            }
          );
        });
    });
});

  describe("tests on existing cache", function() {
    var mapId;
    var map;
    var cacheId;

    before(function(done) {
      request(app)
        .post('/api/maps')
        .set('Accept', 'application/json')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect('Content-Type', /json/)
        .send({
          dataSources: [{
            zOrder: 0,
            url: 'http://osm.geointservices.io/osm_tiles',
            format: 'xyz',
            valid: true,
            name: 'http://osm.geointservices.io/osm_tiles'
          }],
          name: 'OSM' }
        )
        .expect(function(res) {
          map = res.body;
          mapId = map.id;
        })
        .end(function() {
          request(app)
            .post('/api/caches')
            .set('Accept', 'application/json')
            .set('Authorization', 'Bearer 12345')
            .expect(200)
            .expect('Content-Type', /json/)
            .send({
              sourceId: mapId,
              minZoom: 0,
              maxZoom: 1,
              name: 'Cache',
              geometry: turf.bboxPolygon([-180, -85, 180, 85]).geometry
            })
            .expect(function(res) {
              var cache = res.body;
              cacheId = cache.id;
              cache.should.have.property('id');
              cache.should.have.property('name', 'Cache');
              cache.should.have.property('minZoom', 0);
              cache.should.have.property('maxZoom', 1);
              cache.should.have.property('status');
            })
            .end(done);
        });
    });

    after(function(done) {
      if (!mapId) return done();
      Map.getById(mapId, function(err, map) {
        var m = new Map(map);
        m.delete(function() {
          if (!cacheId) return done();
          Cache.getById(cacheId, function(err, cache) {
            var c = new Cache(cache);
            c.delete(done);
          });
        });
      });
    });

    it ('should get all caches for the map', function(done) {
      startTest('should get all caches for the map');
      request(app)
        .get('/api/maps/'+mapId+'/caches')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect(function(res) {
          console.log('res', res.body);
          var caches = res.body;
          console.log("caches", caches);
          caches.length.should.be.equal(1);
          var cache = caches[0];
          cache.should.have.property('id', cacheId);
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 1);
          cache.should.have.property('status');
        })
        .end(done);
    });

    it ('should pull the cache', function(done) {
      startTest('should pull the cache');
      request(app)
        .get('/api/caches/'+cacheId)
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect(function(res) {
          console.log('res', res.body);
          var cache = res.body;
          cacheId = cache.id;
          cache.should.have.property('id', cacheId);
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 1);
          cache.should.have.property('status');
        })
        .end(done);
    });

    it ('should pull the 0/0/0 tile for the cache', function(done) {
      startTest('should pull the 0/0/0 tile for the cache');
      var file = fs.createWriteStream('/tmp/cache_test.png');
      file.on('close', done);
      request(app)
        .get('/api/caches/'+cacheId+'/0/0/0.png')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect(function(res) {
          console.log('response body is', res);
        })
        .pipe(file);
    });

    it ('should generate an xyz cache', function(done) {
      startTest('should generate an xyz cache');
      this.timeout(10000);
      request(app)
        .get('/api/caches/'+cacheId + '/generate')
        .set('Authorization', 'Bearer 12345')
        .query({format: 'xyz'})
        .expect(202)
        .expect(function(res) {
          var cache = res.body;
          cache.should.have.property('id', cacheId);
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 1);
          cache.should.have.property('status');
          cache.status.should.have.property('xyz');
        }).end(function() {
          var finishedGenerating = false;
          console.log('until');
          async.until(
            function() { return finishedGenerating; },
            function(callback) {
              request(app)
                .get('/api/caches/'+cacheId)
                .set('Authorization', 'Bearer 12345')
                .expect(200)
                .expect(function(res) {
                  var cache = res.body;
                  cache.formats.should.have.property('xyz');
                  if (cache.formats.xyz.complete) {
                    cache.formats.xyz.should.have.property('generatedTiles', 5);
                    finishedGenerating = true;
                  }
                }).end(function() {
                  setTimeout(callback, 500);
                });
            },
            function() {
              done();
            }
          );
        });
    });

    it ('should generate a geopackage cache', function(done) {
      startTest('should generate a geopackage cache');
      this.timeout(10000);
      request(app)
        .get('/api/caches/'+cacheId + '/generate')
        .set('Authorization', 'Bearer 12345')
        .query({format: 'geopackage'})
        .expect(202)
        .expect(function(res) {
          var cache = res.body;
          cache.should.have.property('id', cacheId);
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 1);
          cache.should.have.property('status');
          cache.formats.should.have.property('xyz');
        }).end(function() {
          var finishedGenerating = false;
          console.log('until');
          async.until(
            function() { return finishedGenerating; },
            function(callback) {
              request(app)
                .get('/api/caches/'+cacheId)
                .set('Authorization', 'Bearer 12345')
                .expect(200)
                .expect(function(res) {
                  var cache = res.body;
                  cache.formats.should.have.property('geopackage');
                  console.log('GeoPackage', cache.formats.geopackage.percentComplete);
                  if (cache.formats.geopackage.complete) {
                    cache.formats.geopackage.should.have.property('complete');
                    finishedGenerating = true;
                  }
                }).end(function() {
                  setTimeout(callback, 500);
                });
            },
            function() {
              done();
            }
          );
        });
    });

    it('should pull the overview tile', function(done) {
      startTest('should pull the overview tile');
      var file = fs.createWriteStream('/tmp/cache_overview_tile_test.png');
      file.on('close', done);
      request(app)
        .get('/api/caches/'+cacheId+'/overviewTile')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect(function(res) {
        })
        .pipe(file);
    });

    it('should pull the 0/0/0 tile', function(done) {
      startTest('should pull the 0/0/0 tile');
      var file = fs.createWriteStream('/tmp/cache_zero_tile_test.png');
      file.on('close', done);
      request(app)
        .get('/api/caches/'+cacheId+'/0/0/0.png')
        .set('Authorization', 'Bearer 12345')
        .expect(200)
        .expect(function(res) {
        })
        .pipe(file);
    });

    it('should generate an xyz cache and download it', function(done) {
      startTest('should generate an xyz cache and download it');
      this.timeout(15000);
      request(app)
        .get('/api/caches/'+cacheId + '/xyz')
        .set('Authorization', 'Bearer 12345')
        .expect(202)
        .expect(function(res) {
          var cache = res.body;
          cache.should.have.property('id', cacheId);
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 3);
          cache.should.have.property('status');
          cache.status.should.have.property('xyz');
        }).end(function() {
          var finishedGenerating = false;
          console.log('until');
          async.until(
            function() { return finishedGenerating; },
            function(callback) {
              request(app)
                .get('/api/caches/'+cacheId)
                .set('Authorization', 'Bearer 12345')
                .expect(200)
                .expect(function(res) {
                  var cache = res.body;
                  cache.formats.should.have.property('xyz');
                  if (cache.formats.xyz.complete) {
                    cache.formats.xyz.should.have.property('generatedTiles', 5);
                    finishedGenerating = true;
                  }
                }).end(function() {
                  setTimeout(callback, 500);
                });
            },
            function() {
              var file = fs.createWriteStream('/tmp/xyz_cache.zip');
              file.on('close', done);
              console.log('going to get xyz cache for %s', cacheId);
              request(app)
                .get('/api/caches/'+cacheId+'/xyz')
                .set('Authorization', 'Bearer 12345')
                .expect(200)
                .pipe(file);
            }
          );
        });
    });

    it('should delete the cache xyz format', function(done) {
      startTest('should delete the cache xyz format');
      request(app)
        .get('/api/caches/'+cacheId + '/generate')
        .set('Authorization', 'Bearer 12345')
        .query({format: 'xyz'})
        .expect(202)
        .expect(function(res) {
          var cache = res.body;
          cache.should.have.property('id', cacheId);
          cache.should.have.property('name', 'Cache');
          cache.should.have.property('minZoom', 0);
          cache.should.have.property('maxZoom', 1);
          cache.should.have.property('status');
          cache.status.should.have.property('xyz');
        }).end(function() {
          request(app)
            .delete('/api/caches/'+cacheId+'/xyz')
            .set('Authorization', 'Bearer 12345')
            .expect(200)
            .expect(function(res) {
            })
            .end(done);
        });
    });
  });
});
Example #5
0
var mongoose = require('mongoose');

var page1Id = mongoose.Types.ObjectId(),
  page2Id = mongoose.Types.ObjectId();

function makeHistElement(pageId, count){
  var runDate = new Date(2016,6,1);
  var rtn = [];
  while (count--){
    runDate.setDate(runDate.getDate() + 1);
    rtn.push({
      page: pageId,
      fields: JSON.stringify({
        price:{
          index: 0,
          value: 'Our price $' + Math.round((Math.random() + 1) * 10)
       },
       reviews: {
         index: 1,
         value: Math.round((Math.random() * 4)+1).toString()
       }
      }),
      jobRunTS: runDate.getTime()
    });
  }
  return rtn;
}

module.exports = makeHistElement;
Example #6
0
exports.postVersion = function(req, res) {
  var dispersal_version  = req.body; 
  dispersal_version._id = mongoose.Types.ObjectId();
  dispersal_version.created=Date();
  dispersal_version.state="accepted";
  dispersal_version.element="dispersal";
  var eleValue = dispersal_version.dispersal;
  dispersal_version = new DispersalVersion(dispersal_version);

  console.log("distance: "+dispersal_version);
  console.log("keys: "+Object.keys(dispersal_version));
  console.log("doc: "+dispersal_version._doc);
  console.log("keys: "+Object.keys(dispersal_version._doc));
  console.log("doc: "+dispersal_version._doc.dispersal);
  console.log("doc req: "+Object.keys(req.body));
  console.log("doc req: "+Object.keys(req.body.dispersal));

  var id_v = dispersal_version._id;
  var id_rc = req.params.id_record;

  var ob_ids= new Array();
  ob_ids.push(id_v);

  if(typeof  id_rc!=="undefined" && id_rc!=""){
    if(typeof  eleValue!=="undefined" && eleValue!=""){
    add_objects.RecordVersion.count({ _id : id_rc }, function (err, count){ 
      if(typeof count!=="undefined"){
      if(count==0){
        res.json({message: "The Record (Ficha) with id: "+id_rc+" doesn't exist."});
      }else{
       add_objects.RecordVersion.findByIdAndUpdate( id_rc, { $push: { "dispersalVersion": id_v } },{safe: true, upsert: true},function(err, doc) {
          if (err){
              res.status(406);
              res.send(err);
          }else{
            dispersal_version.id_record=id_rc;
            dispersal_version.version=doc.dispersalVersion.length+1;
            var ver = dispersal_version.version;
            dispersal_version.save(function(err){
              if(err){
                res.status(406);
                res.send(err);
              }else{
                res.json({ message: 'Save DispersalVersion', element: 'dispersal', version : ver, _id: id_v, id_record : id_rc });
              }
            });
          }
        });
      }
      }else{
        res.json({message: "The Record (Ficha) with id: "+id_rc+" doesn't exist."});
      }
   });
   }else{
    res.status(406);
    res.json({message: "Empty data in version of the element"});
   } 
  }else{
    res.status(406);
    res.json({message: "The url doesn't have the id for the Record (Ficha)"});
  }
};
Example #7
0
/*jslint node: true */
/*global describe, it, before, beforeEach, after, afterEach */
'use strict';

var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId();
var mockgoose = require('mockgoose');
mockgoose(mongoose);

global.config = {};
global.config.root = '../../../';

var request = require('supertest');
var express = require('express');
var bodyParser = require('body-parser');
var should = require('should');
var rootUrls = require(global.config.root + '/config/rootUrls');
var postRoutes = require('../routes/postRoutes');

var FooForm = require('fooforms-forms');
var db = require('mongoose').connection;
var fooForm = new FooForm(db);


var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

var rootUrl = '/' + rootUrls.posts;
exports.getRoom = function (req, res) {
  if(req.query.minPrice)
    req.query.minPrice = parseInt(req.query.minPrice);
  if(req.query.maxPrice)
    req.query.maxPrice = parseInt(req.query.maxPrice);

  // if(req.query.isDash == "1")
  // {
  //   if(req.user._doc.role.type != "ghUser")
  //     return res.json(response(200,"success",constants.messages.errors.auth))
  //
  //     roomModelObj.aggregate([
  //       {
  //         // condition to match the logged in user
  //         $match: {
  //           guestHouse: mongoose.Types.ObjectId(req.user._doc._id),  //$region is the column name in collection
  //           isDelete:false,
  //         }
  //       },
  //       {
  //         // condition to group the room details
  //         "$group": {
  //           "_id": {
  //               "roomType": "$roomType",
  //               "bookingStatus": "$bookingStatus"
  //           },
  //           "count": { "$sum": 1 }
  //       }},
  //     ], function (err, result) {
  //       if (err) {
  //         return res.json(response(500,"error",constants.messages.success.getData,err));
  //       } else {
  //         return res.json(response(200,"success",constants.messages.success.getData,result));
  //       }
  //     });
  // }
  // if user selects a room to get the details of the room
  if (req.query._id) {

    var query = {
      "_id":mongoose.Types.ObjectId(req.query._id)
    }
    if(req.user._doc.role.type == "ghUser"){
          query.guestHouse = mongoose.Types.ObjectId(req.user._doc._id);
    }
    roomModelObj.find(query).deepPopulate("facility")
    .exec()
    .then(function(room) {
      return res.json(response(200,"success",constants.messages.success.getData,room));
    })
  }
  else {

    var match = {};
    var aggregrate = [];
    var filters = {};// sets the price filter flag
    var roomCount = {
      availableRooms : 0,
      bookedRooms : 0,
      checkedInRooms : 0,
    };
    // adding condition for the price
    if((req.query.minPrice == "" || req.query.minPrice == undefined) && utility.isDataExist(req.query.maxPrice,true) ){
      // if min price not mentioed and max price mentioed then make minPrice as ZERO
      req.query.minPrice = 0 ;
    }
    if((req.query.maxPrice == "" || req.query.maxPrice == undefined) && utility.isDataExist(req.query.minPrice,true) ){
      return res.json(response(202,"failed",constants.messages.errors.invalidPriceQuery));
    }
    if(parseInt(req.query.minPrice) > parseInt(req.query.maxPrice)){
      sendResponse(res,202,"failed",constants.messages.errors.invalidPriceQuery);
    }
    if(
      utility.isDataExist(req.query.minPrice)
      && utility.isDataExist(req.query.maxPrice)
      && req.query.maxPrice  >= req.query.minPrice ){
      filters.price = true; // sets the price filter
    }
    if(req.query.roomType){
      filters.roomType = true;
    }
    if(req.query.facilities){
      filters.facilities = true;
      req.query.facilities = req.query.facilities.split(",");
    }
    // req.query.checkInDate ? req.query.checkInDate = new Date(req.query.checkInDate) : new Date();
    match["$and"] = [
      {'roomsDetails.checkInDate':{'$lte':new Date(req.query.checkInDate)}},
      // {'roomsDetails.checkInDate':{'$lt': utility.getDateFormat({operation:"add",mode:"day",count:1,startDate:new Date(req.query.checkInDate)})}}
      {'roomsDetails.checkOutDate':{'$gte': new Date(req.query.checkInDate)}}
    ]

    // var query = {
    //   "isDelete" : false,
    // };
    // if(req.query._id){
    //   query._id = req.query._id;
    // }
    // // adding filter for the facility
    // if(req.query.facility && req.query.facility.split(",").length > 0 ){
    //     query.facility = {
    //       "$in":req.query.facility.split(",")
    //   }
    // }
    // // adding filter for the room type
    // if(req.query.roomType && req.query.roomType.split(",").length > 0 ){
    //     query.roomType = {
    //       "$in":req.query.roomType.split(",")
    //   }
    // }
    // validating data as per the user requested
    var select = {};

    // no condition as admin can access all
    if(req.user._doc.role.type == "ccare"){
      // select = "name  contactDetails establishDate rating MinPrice MaxPrice address";
    }
    else if(req.user._doc.role.type == "ghUser"){
      console.log("mongoose.Types.ObjectId(req.user._doc._id)  ",mongoose.Types.ObjectId(req.user._doc._id));
      match['guestHouse'] = mongoose.Types.ObjectId(req.user._doc._id);
      // select = "name  contactDetails rooms establishDate rating MinPrice MaxPrice address";
    }
    aggregrate.push({$match:match});
    console.log("aggregrate   ",utility.stringify(aggregrate));
    tranctionModelObj.aggregate(aggregrate)
    .exec()
    .then(function(trans) {
      // return res.json(response(200,"success",constants.messages.success.getData,trans));
      return tranctionModelObj.populate( trans,{ "path": "roomsDetails.room" });
    })
    .then(function(trans1) {
      var nonAvailbleRoomsId = [];
      var nonAvailableRooms = [];
      for(var i = 0 ; i < trans1.length ; i++){
        for(var j = 0 ; j < trans1[i].roomsDetails.length ; j++ ){
          // checking for the dashBoard info
          if(req.query.isDash == "1" && !req.query.status){
            switch (trans1[i].roomsDetails[j].bookingStatus) {
              // case "AVAILABLE":
              //   roomCount.availableRooms ++;
              //   break;
              case "CHECKED-IN":
                roomCount.checkedInRooms ++;
                break;
              case "BOOKED":
                roomCount.bookedRooms ++;
                break;
              default:

            }
            nonAvailbleRoomsId.push(trans1[i].roomsDetails[j].room._id);
            continue;
          }
          else if(req.query.isDash == "1" && req.query.status != "AVAILABLE"){ // skipping availableRooms
            // req.query.status can be availableRooms,bookedRooms,checkedInRooms only
            if(trans1[i].roomsDetails[j].bookingStatus == req.query.status){
              nonAvailableRooms.push(trans1[i].roomsDetails[j]);
              nonAvailbleRoomsId.push(trans1[i].roomsDetails[j].room._id);
            }
            continue;
          }
          if(trans1[i].roomsDetails[j]  && trans1[i].roomsDetails[j].bookingStatus == "AVAILABLE" )
          continue;
          // adding price filter
          if(
            filters.price
            && trans1[i].roomsDetails[j].price >= req.query.minPrice
            && trans1[i].roomsDetails[j].price <= req.query.maxPrice ){
              nonAvailbleRoomsId.push(trans1[i].roomsDetails[j].room._id);
              nonAvailableRooms.push(trans1[i].roomsDetails[j]);

          }
          if(filters.roomType && trans1[i].roomsDetails[j].room.roomType == req.query.roomType){
            nonAvailbleRoomsId.push(trans1[i].roomsDetails[j].room._id);
            nonAvailableRooms.push(trans1[i].roomsDetails[j]);
          }
          if(filters.facilities && underscore.intersection(req.query.facilities, trans1[i].roomsDetails[j].room.facility.toString().split(",")).length){
            nonAvailbleRoomsId.push(trans1[i].roomsDetails[j].room._id);
            nonAvailableRooms.push(trans1[i].roomsDetails[j]);

          }
          if(!filters.price && !filters.facilities  && !filters.roomType){
            nonAvailbleRoomsId.push(trans1[i].roomsDetails[j].room._id);
            nonAvailableRooms.push(trans1[i].roomsDetails[j]);
          }
        }
      }
      nonAvailbleRoomsId = unique(nonAvailbleRoomsId);
      nonAvailableRooms = unique(nonAvailableRooms);
      // getting availble rooms
      var query= {
         "_id": { "$nin": nonAvailbleRoomsId },
         "isDelete":false,
      }
      if(req.user._doc.role.type == "ghUser"){
        query['guestHouse'] = req.user._doc._id;
      }
      // adding price filter
      if(filters.price){
        query.price = {
            "$gte":parseInt(req.query.minPrice),
            "$lte":parseInt(req.query.maxPrice)
        }
      }
      // adding facilities filter
      if(filters.facilities){
        query.facility = {
            "$in":req.query.facilities
        }
      }
      // adding room type
      if(filters.roomType){
        query.roomType = req.query.roomType;
      }
      // checking for the dashBoard service or not
      if(req.query.isDash == "1" && !req.query.status){
        roomModelObj.count(query,function(err,count) {
          if(err)
            sendResponse(res,500,"error",constants.messages.errors.getData,err);
          else{
            roomCount.availableRooms = count;
            sendResponse(res,200,"success",constants.messages.success.getData,roomCount);
          }
        })
        // return res.json(response(200,"success",constants.messages.success.getData,data));
      }
      else if(req.query.isDash == "1" && req.query.status && req.query.status != "AVAILABLE"){
        var data = {
          nonAvailebleRooms :nonAvailableRooms,
          availableRooms :[],
        }
        sendResponse(res,200,"success",constants.messages.success.getData,data);
        // return res.json(response(200,"success",constants.messages.success.getData,data));
      }
      else if(req.query.isDash == "1" && req.query.status && req.query.status == "AVAILABLE"){
        roomModelObj.find(query,function(err,rooms) {
          if(err)
            sendResponse(res,500,"error",constants.messages.errors.getData,err);
          else{
            var data = {
              nonAvailebleRooms :[],
              availableRooms :rooms,
            }
            sendResponse(res,200,"success",constants.messages.success.getData,data);
          }
        })
        // return res.json(response(200,"success",constants.messages.success.getData,data));
      }
      else {
        roomModelObj.find(query)
        .lean()
        .exec(function(err,availableRooms) {
          var data = {
            nonAvailebleRooms :nonAvailableRooms,
            availableRooms :availableRooms,
          }
          return res.json(response(200,"success",constants.messages.success.getData,data));
        })
      }
    })
  }
}
Example #9
0
		svarray.forEach(function(s){
			console.log(s);
			sv.push(mongoose.Types.ObjectId(s));
		});
exports.delete = function(req, res) {
    Item.remove({'_id':mongoose.Types.ObjectId(req.param('id'))}, function (err, result) {
        if (err) return console.error(err);
        res.send({});
    });
};
 return PromiseAdapter.convertMongooseQuery(Task.model.findById(taskPlainObject.id)).then(function (task) {
     task.state = taskPlainObject.state;
     task.taskInfo = mongoose.Types.ObjectId(taskInfoId);
     return PromiseAdapter.convertMongooseDocumentSave(task);
 });
exports.update = function(req, res) {
    Item.findByIdAndUpdate(mongoose.Types.ObjectId(req.param('id')), {'item':req.param('item')}, function (err, result) {
        if (err) return console.error(err);
        res.send(result);
    });
};
exports.retrieveOne = function(req, res) {
    Item.find({'_id':mongoose.Types.ObjectId(req.param('id'))}, function (err, item) {
        if (err) return console.error(err);
        res.send(item);
    });
};
  exports.replyComment = function(req,res,next)
  {
  	 var newCommentId = mongoose.Types.ObjectId();
  	 var parentComment = req.body._id || null;

  	 	  if(parentComment!=null)
  	 	  {

  	 	  var comments;
  	 	  var comment = new Comment({

  	 	  	 _id:newCommentId,
  	 	  	 postId:req.body.postId,
  	 	  	 comment:config.validator.escape(req.body.comment),
  	 	  	 parentCommentID:req.body.parentCommentID,
           post_date:lib.getTimeString(),
  	 	  	 childComments:[],
  	 	  	 CommentUser:req.body.userId,
  	 	  	 userImage:req.body.userImage,
  	 	  	 userName:req.body.userName

  	 	  });	
 
 			/* Use where statement to find root level comment in the post
 			*/

  	 	  	   Comment.findOne()
  	 	  	   		  .where('postId',req.body.postId)
  	 	  	   		  .where('_id',req.body.parentCommentID).
  	 	  	   		  exec(function(err,oldComment){
  	 	  	   		 
  	 	  	   		 	  if(err)
  	 	  	   		 	  {
					  	       err = config.InsertClientErrMessage(err,config.ClientErrorMessages.FAIL_LOAD_DATA);
					  	 	     return next(err);
  	 	  	   		 	  }
 
  	 	  	   		 	  comments = pushRecusivley(oldComment,parentComment,comment);
  	 	  	   		 	  comments.save(function(err,coment){

      			  	 	  		if(err)
      			  	 	  		{
      					  	       err = config.InsertClientErrMessage(err,config.ClientErrorMessages.FAIL_LOAD_DATA);
      					  	 	     return next(err);
      			  	 	  		}
  	 	  	   		 	  	res.json(comment);
  	 	  	   		 	 
  	 	  	   		 	  })

  	 	  	   		  })
  	 	  }
  	 	else
  	 	  {

  	 	  // no parent id , means, this comment is root level comment  
 
  	 	  var comment = new Comment({

  	 	  	 _id:newCommentId,
  	 	  	 postId:req.body.postId,
           post_date:lib.getTimeString(),
  	 	  	 comment:config.validator.escape(req.body.comment),
  	 	  	 parentCommentID:newCommentId,
  	 	  	 childComments:[],
  	 	  	 CommentUser:req.body.userId

  	 	  });	  	 	  	

	  	 	  comment.save(function(err,comment){

	  	 	  		if(err)
	  	 	  		{
			  	       err = config.InsertClientErrMessage(err,config.ClientErrorMessages.FAIL_LOAD_DATA);
			  	 	   return next(err);
	  	 	  		}

	  	 	  		res.json(comment);

	  	 	  });
  	 	  }   



  }
Example #15
0
userSchema.statics.findById = function(id, cb){
	return this.findOne({_id: mongoose.Types.ObjectId(id)}, cb);
};
Example #16
0
			svarray.forEach(function(s){
				sv.push(mongoose.Types.ObjectId(s));
			});
Example #17
0
EditorChannelServer.prototype.handleConnection = function(socket) {
	var that = this
	var req = socket.upgradeReq
	var remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress

	function abortClient(err) {
		console.error('handleConnection.abortClient', err)

		if (socket.readyState === WebSocket.OPEN) {
			socket.send(JSON.stringify({ error: err.message, stack: err.stack }))
		}

		socket.close()
	}

	function parseCookie() {
		var header = req.headers.cookie

		if (!header)
			return

		var headerMatch = header.match(/(vs070=[^;\s]*)/)

		if (!headerMatch)
			return

		var sessionCookie = headerMatch[1].substring('vs070='.length)

		return sessions.util.decode({
			cookieName: 'vs070',
			cookie: {
				domain: process.env.FQDN,
			},
			secret: secrets.sessionSecret,
			duration: week,
			activeDuration: day
		}, sessionCookie)
	}

	var cookie = parseCookie()

	if (!cookie || !cookie.content)
		return abortClient('No cookie')

	var userId = cookie.content.userId
	if (cookie.content.passport && cookie.content.passport.user)
		userId = cookie.content.passport.user

	function setupClient(user) {
		var client = new EditorConnection(userId)
		client.socket = socket
		client.remoteAddress = remoteAddress
		client.channels = []
		client.username = user.username
		client.lastMessageReceivedAt = 0
		client.floodCounter = 0

		that.clients[client.id] = client

		socket.on('message', that.handleSocketMessage.bind(that, client))
		socket.on('close', that.onSocketClosed.bind(that, client))

		// relay messages to the user from other nodes
		that._redisSubscriber.subscribe(client.id)

		console.log('EditorChannelServer connected', remoteAddress, userId, client.username, client.id)

		that.send(client, {
			kind: 'READY',
			id: client.id,
			color: client.color
		})
	}

	User.findById(mongoose.Types.ObjectId(userId), function(err, user) {
		if (err)
			return abortClient(err.stack)

		if (!user)
			return setupClient({
				username: 'Guest '+
					userId.substring(0, 1).toUpperCase() +
					userId.substring(1, 2)
			})
		
		setupClient(user)
	})
}
Example #18
0
function sq(collection, company, callback) {
   mongoose.model('counters').findOneAndUpdate({ entity: collection, _company :  mongoose.Types.ObjectId(company)}, { $inc: { seq: 1 } }, callback);
}
Example #19
0
      name: 'Test User',
      email: 'test@test.com',
      password: 'test'
    }, {
      provider: 'local',
      role: 'admin',
      name: 'Admin',
      email: 'admin@admin.com',
      password: 'admin'
    }, function () {
      console.log('finished populating users');
    }
  );
});

var idBinu = mongoose.Types.ObjectId();
var idOnyx = mongoose.Types.ObjectId();
Hamster.find({}).remove(function () {
  Hamster.create({
    _id: idOnyx,
    name: 'Onyx',
    male: false,
    birthday: new Date,
    image: 'image.jpg'
  }, {
    _id: idBinu,
    name: 'Binu',
    male: true,
    birthday: new Date
  }, {
    name: 'Joe',
Example #20
0
module.exports.getObjId = function(idString) {
    var id = mongoose.Types.ObjectId(idString);
    return id;
}
Example #21
0
 *
 * @author   Denzel Wamburu {@link http://denzel.xyz}
 * @copyright Copyright (c) 2015,Denzel Wamburu
 * @license   The MIT License {@link http://opensource.org/licenses/MIT}
 */
'use strict';

/**
 * Module dependencies.
 */
var logger   = require('mm-node-logger')(module);
var mongoose = require('mongoose');
var User     = require('../user/user.model');
var Image    = require('../image/image.model');

var testUserId = mongoose.Types.ObjectId();

User.find({}).remove(function() {
    User.create({
            provider: 'local',
            name: 'Sabina Serabi',
            email: 'sabinabenerdette@gmail.com',
            password: 'password',
            avatar: 'https://raw.githubusercontent.com/denzelwamburu/pichalink/master/www/img/sabina.png?123456'
        }, {
            _id: testUserId,
            provider: 'local',
            name: 'Test',
            email: 'test@test.com',
            password: 'password'
        }, {
      DataPointModel.findById(req.params.id, function (err, datapoint) {
      if (!err && datapoint){

        datapoint.title = req.body.title;
        datapoint.description = req.body.description;
        datapoint.comment = req.body.comment;
        datapoint.soc = req.body.soc;
        datapoint.Location.title = req.body.location;
        datapoint.Location.latitude = req.body.latitude;
        datapoint.Location.longitude = req.body.longitude;
        datapoint.tags = req.body.tag_list;
        datapoint.stage= req.body.stage;
        datapoint.modified = date_now;
        datapoint.modifiedBy = user._id;
        datapoint.event_date = req.body.event_date;
        //to update/add/remove sources in a datapoint
        if (jquery.isArray(req.body.sourceurl)){
          var countSources=new Array();
          for (j=0;j<req.body.sourceurl.length;j++){
            var url = req.body.sourceurl[j];
            //add http if its not there since request library doesnt support URLs without it
            if (!/^(f|ht)tps?:\/\//i.test(url)) {
              url = "http://" + url;
            }
            var sourceType = req.body.sourcetype[j];
            var sourceId = req.body.sourceid[j];
            (function(url,sourceType,sourceId) {
              saveUrl(url,WebsiteModel,sourceId,function(websiteId){
                countSources.push('dummy');
                if (url!=='' && sourceType!==''){
                  if (sourceId!==''){
                    //update existing source
                    var id = mongoose.Types.ObjectId(sourceId);
                    var source = datapoint.sources.id(id);
                    source.url= url;
                    source.sourcetype= sourceType;
                  } else {
                      //create new source
                      if (websiteId!='-1'){
                        datapoint.sources.addToSet({url: url,sourcetype: sourceType, savedurl: websiteId});
                      } else {
                        datapoint.sources.addToSet({url: url,sourcetype: sourceType});
                      }
                  }
                } else if (url==='' && sourceId!==''){
                  //delete source
                  var id_to_delete = mongoose.Types.ObjectId(sourceId);
                  var source_to_delete = datapoint.sources.id(id_to_delete);
                  source_to_delete.remove();
                }
                if (countSources.length==req.body.sourceurl.length){
                  update_datapoint_db(datapoint);
                }
              });
            })(url,sourceType,sourceId);
          }
        } else if (req.body.sourceurl!=='' && req.body.sourcetype!==''){
          saveUrl(req.body.sourceurl,WebsiteModel,req.body.sourceid,function(websiteId){          
            if (req.body.sourceid!==''){
              //update source
              var id_to_update = mongoose.Types.ObjectId(req.body.sourceid);
              var source_to_update = datapoint.sources.id(id_to_update);
              source_to_update.url=req.body.sourceurl;
              source_to_update.sourcetype=req.body.sourcetype;
            } else {
                if (websiteId!='-1'){
                  datapoint.sources.addToSet({url: req.body.sourceurl,sourcetype: req.body.sourcetype,savedurl: websiteId});
                } else {
                  //create new source
                  datapoint.sources.addToSet({url: req.body.sourceurl,sourcetype: req.body.sourcetype});
                }
            }
            update_datapoint_db(datapoint);
          });
        } else if (req.body.sourceurl==='' && req.body.sourceid!=='') {
          //delete source
          var id_delete = mongoose.Types.ObjectId(req.body.sourceid);
          var source_delete = datapoint.sources.id(id_delete);
          source_delete.remove();
          update_datapoint_db(datapoint);
        } else {
          //no sources
          update_datapoint_db(datapoint);

        }

      } else {
        console.log('Cant find datapoint by ID '+err);
        return res.send(null);
      }
    });
Example #23
0
exports.askenroll = function(req,res){
  var key = mongoose.Types.ObjectId(req.session.passport.user);
    console.log(req.file);
    console.log(req.body);
    console.log(req.params);
    var newAsk            = new Ask();

    User.findOne({ '_id' : key }, function(err, user) {

      var name;
      var email;

      if(user.local.name)
        name=user.local.name;
      else if(user.facebook.name)
        name=user.facebook.name;
      else if(user.naver.name)
        name=user.naver.name;
      else if(user.google.name)
        name=user.google.name;

      if(user.local.email)
        email=user.local.email;
      else if(user.facebook.email)
        name=user.facebook.email;
      else if(user.naver.email)
        name=user.naver.email;
      else if(user.google.email)
        name=user.google.email;

      user.asks.push(newAsk._id);
      user.save(function(err){
        if(err)
          console.log(err);
      });
      newAsk.asker=key;
      newAsk.name =name ;
      newAsk.email =email;
      newAsk.status =0 ;
      newAsk.ask_img_dir = req.file.destination.substring(19)+'/'+req.file.filename;

      var comment=req.body.explantion;
      comment=comment.replace(/(\s+)/gi,' ').trim();
      newAsk.comment = comment;

      var tags=req.body.hashtag;
      tags=tags.replace(/(\s+)/gi,' ');
      tags=tags.replace(/(\#+)/gi,' #').trim();
      var tagsarray=tags.split(' ');
      for(var i=0; i<tagsarray.length; i++){
        if(tagsarray[i][0]!='#')
          tagsarray[i]='#'+tagsarray[i];
      }
      newAsk.tag = tagsarray;
      newAsk.reward =req.body.point ;
      newAsk.view = 0 ;
      newAsk.time= Date.now();
      newAsk.gender=req.body.sex;
      console.log("here");

      newAsk.clothes.size = req.body.size;
      newAsk.clothes.color = req.body.color;

      newAsk.save(function(err){
        if (err)
          throw err;
      });
    });


    User.findOneAndUpdate({ '_id' : key }, { 'asks': newAsk._id });



    res.redirect('/askUploaded');


};
Example #24
0
	router.get('/siteadmin/editsecgroup', function (req, res, next) {
		Secgroups.findOne({ _id: mongoose.Types.ObjectId(req.query.gid) }, function (err, secgroup) {
			res.render('admin/site_admin/edit_groups', { secgroup: secgroup });
		});
	});
Example #25
0
 var ids = req.body.ids.map(function(id){
   return mongoose.Types.ObjectId(id);
 });
Example #26
0
PImageSchema.statics.getImage = function(image_id, callback) {
    var grid = new mongoose.mongo.Grid(mongoose.connection.db, 'channel_images');
    return grid.get(mongoose.Types.ObjectId(image_id), callback);
};
Example #27
0
var crypto = require('crypto')
var mongoose = require('mongoose')
var Schema = mongoose.Schema

// User
var User = new Schema({
  _id: {
    type: Schema.Types.ObjectId,
    default: mongoose.Types.ObjectId()
  },

  // Données générales de l'utilisateur
  username: {
    type: String,
    unique: true,
    required: true
  },

  // Données liées à la sécurité
  hashedPassword: {
    type: String,
    required: true
  },
  salt: {
    type: String,
    required: true
  },
  created: {
    type: Date,
    default: Date.now
  },
Example #28
0
 getTypes: function ( x ) {
     return mongoose.Types.ObjectId(x);
 },
exports.removeUser = function(req, res) {
	var wg = req.body;

	var newPass = randomWord() + '-' + randomWord();

	Xtasklist.find({wg_id: mongoose.Types.ObjectId(wg._id)}, function(err, tasks){
		var task = tasks;
		task.forEach(function(elem){
			if(elem.users.hasOwnProperty(req.user._id)){
				var turnUser = elem.users[req.user._id].turn;
				var isNext = elem.users[req.user._id].isNext;
				var isCurrent = (elem.crtUser.toString() === req.user._id.toString());

				var changeNext = false;
				var newNextTurn = 0;
				var crtIsNext = false;
				var usersNext = [];

				for(var user in elem.users){
					usersNext.push({id: elem.users[user]._id, turn: elem.users[user].turn});
					if(elem.users[user].turn > turnUser) elem.users[user].turn = Math.max(1, elem.users[user].turn-1);
					if(elem.users[user].turn === turnUser) elem.users[user].isNext = isNext;
					if((turnUser-1) === 1) crtIsNext = true;
					if(isCurrent && elem.users[user].isNext){
						newNextTurn = elem.users[user].turn+1;
						changeNext = true;
						elem.crtUser = elem.users[user]._id;
					}
				}
				if(changeNext || crtIsNext){
					usersNext.forEach(function(u){
						if(crtIsNext){
							elem.users[u.id].isNext = true;
						}
						if(changeNext && u.isNext === newNextTurn){
							elem.users[u.id].isNext = true;
						}
					});
				}
				console.log('delete KEY');
				delete elem.users[req.user._id];

				Xtasklist.update({ _id: elem._id },{ $set: { users: elem.users }}, function(err){
					if(err) console.log('error while update task');
					console.log('update task success');
				});
			}
		});

		Wg.update({ _id: wg._id },{ $set: { users: wg.users, passphrase: newPass }}, function(error,wg){
			console.log('update wg.users');
			if(error){ console.log('error'); }
		});
	});

	User.update({ _id: req.user._id }, { $set: { wg_id: null, balance: 0 }}, function(error, user){
		if(error){ 
			console.log('error');
			return res.status(400).send({
			message: errorHandler.getErrorMessage(error)
			});
		}
		res.jsonp(user);
	});
};
 it('GET /admins/:id should respond with 301 Redirect', function() {
   return server.get(`/api/admins/${mongoose.Types.ObjectId()}`).expect(301).endAsync();
 });