Skip to content

Commit

Permalink
Plan Routing Added
Browse files Browse the repository at this point in the history
  • Loading branch information
AnnasSalman committed Oct 26, 2020
1 parent 4f204f5 commit d5d4391
Show file tree
Hide file tree
Showing 7 changed files with 431 additions and 19 deletions.
8 changes: 8 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,17 @@ var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var hotelRouter = require('./routes/hotels')
var bookingRouter = require('./routes/bookings')
var toursRouter = require('./routes/tours')
var passport = require('passport');
var config = require('./config');
var cors = require('cors');
var authenticate = require('./middlewares/authenticate');

if (process.env.NODE_ENV !== 'production') {
require('dotenv').config({path: path.resolve( __dirname,'secrets.env')});
console.log('loaded')
}

const connection = mongoose.connect('mongodb://localhost:27017/travelry-api', { useNewUrlParser: true, useUnifiedTopology: true });
var app = express();
connection.then((db) => {
Expand All @@ -32,6 +39,7 @@ app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/hotels', hotelRouter);
app.use('/bookings', bookingRouter)
app.use('/tours', toursRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
Expand Down
177 changes: 177 additions & 0 deletions classes/Plan.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
const Hotel = require('../models/hotel')

class Plan{
get days() {
return this._days;
}

set days(value) {
this._days = value;
}

get budget() {
return this._budget;
}

set budget(value) {
this._budget = value;
}

get route() {
return this._route;
}

set route(value) {
this._route = value;
}

get hotelDistanceSmallWeight() {
return this._hotelDistanceSmallWeight;
}

set hotelDistanceSmallWeight(value) {
this._hotelDistanceSmallWeight = value;
}

get hotelDistanceMediumWeight() {
return this._hotelDistanceMediumWeight;
}

set hotelDistanceMediumWeight(value) {
this._hotelDistanceMediumWeight = value;
}

get hotelDistanceLargeWeight() {
return this._hotelDistanceLargeWeight;
}

set hotelDistanceLargeWeight(value) {
this._hotelDistanceLargeWeight = value;
}

get hotelDistanceSmall() {
return this._hotelDistanceSmall;
}

set hotelDistanceSmall(value) {
this._hotelDistanceSmall = value;
}

get hotelDistanceMedium() {
return this._hotelDistanceMedium;
}

set hotelDistanceMedium(value) {
this._hotelDistanceMedium = value;
}

get hotelDistanceLarge() {
return this._hotelDistanceLarge;
}

set hotelDistanceLarge(value) {
this._hotelDistanceLarge = value;
}
//Budget in Rupees
constructor(days, budget, route) {
this._days = days;
this._budget = budget;
this._route = route;
this._hotelDistanceSmallWeight = 60;
this._hotelDistanceMediumWeight = 30;
this._hotelDistanceLargeWeight = 10;
this._hotelDistanceSmall = 1500;
this._hotelDistanceMedium = 2500;
this._hotelDistanceLarge = 4000;
}

async calculatePlaceStaysProbability (lat, lng) {
try{
const hotelsClose = await Hotel.find().getNearbyHotels(lat, lng, this._hotelDistanceSmall)
const length1 = hotelsClose.length
const hotelsMedium = await Hotel.find().getNearbyHotels(lat, lng, this._hotelDistanceMedium)
const length2 = hotelsMedium.length
const hotelsFar = await Hotel.find().getNearbyHotels(lat, lng, this._hotelDistanceLarge)
const length3 = hotelsFar.length
return (length1*(this.hotelDistanceSmallWeight/100))+(length2*(this.hotelDistanceMediumWeight/100))+(length3*(this.hotelDistanceLargeWeight/100))
}
catch(e){
return e
}
}

calculateStaysAndStops (ratios) {
let totalTravelTime = 0
const totalTourTime = this._days*24*60*60
this._route.forEach((location)=>{
totalTravelTime += location.duration.value
})
const tourTimeWithOutTravel = totalTourTime - totalTravelTime
const stays = ratios.map((ratio)=>(
Math.floor((tourTimeWithOutTravel*ratio)/(24*60*60))
))
let stayTime = 0
stays.forEach((stay)=>{
stayTime += stay*24*60*60
})
const totalDaysArray = []
stays.forEach((stay, index)=>{
if(index === 0){
totalDaysArray.push(stay)
}
else{
totalDaysArray.push(stay + totalDaysArray[index-1])
}
})
const tourDays = totalDaysArray.map((day, index)=>{
if(day === 0){
return [1]
}
else{
const temp = []
for(let i = totalDaysArray[index-1]+1; i<=totalDaysArray[index]+1; i++){
if (i !== 0){
temp.push(i)
}
}
return temp
}
})
const surplusTime = totalTourTime - (totalTravelTime + stayTime)
return ({
route: this._route.map((location, index)=>{
return(
{...location,
stayDuration: stays[index],
tourDays: tourDays[index]
}
)
})
})
}

async generateTour () {
try{
const weights = [0]
const ratios = []
let sum = 0

for(let i=1; i<this._route.length; i++){
const weight = await this.calculatePlaceStaysProbability(this.route[i].geometry.coordinates.lat,this.route[i].geometry.coordinates.lng)
sum+=weight
weights.push(weight)
}
weights.forEach((weight)=>{
ratios.push(weight/sum)
})
return this.calculateStaysAndStops(ratios)
}
catch(e){
return e
}
}


}

module.exports = Plan
86 changes: 86 additions & 0 deletions classes/Route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
const axios = require('axios')

class Route{

//set of string coordinates separated by |
//33.693852,73.065305|33.591368,73.053589|33.916725,73.396740|34.072142,73.386269
//First one are the source coordinates
constructor(coordinates) {
this._coordinates = coordinates
console.log(coordinates)
}

async calculateShortestTrip(){
try{
const distances = await axios.request({
url:'https://maps.googleapis.com/maps/api/distancematrix/json',
method: 'get',
params: {
origins: this._coordinates,
destinations: this._coordinates,
key: process.env.mapsKey
}
})

const selectedIndexes = [0]
let currentIndex = 0
for(let i = 0; i<distances.data.rows.length-1; i++){
let lowest = 10000000
distances.data.rows[currentIndex].elements.forEach((element, index)=>{
if (element.distance.value<lowest && element.distance.value!=0 && !selectedIndexes.includes(index)){
lowest = element.distance.value
currentIndex = index
}
})
selectedIndexes.push(currentIndex)
}
const tour = []
const coordinateArray = this._coordinates.split('|')
console.log(selectedIndexes)
selectedIndexes.forEach((ind,index)=>{
if(ind===0){
tour.push({
name: distances.data.destination_addresses[0],
type: 'origin',
distance: {
text: "0 km",
value: 0
},
duration: {
text: "0 mins",
value: 0
},
geometry: {
coordinates: {
lat: coordinateArray[0].split(',')[0],
lng: coordinateArray[0].split(',')[1]
}
}
})
}
else{
console.log(index-1+'-'+ind)
const previous = index - 1
tour.push({
name: distances.data.destination_addresses[ind],
type: 'destination',
distance: distances.data.rows[selectedIndexes[previous]].elements[ind].distance,
duration: distances.data.rows[selectedIndexes[previous]].elements[ind].duration,
geometry: {
coordinates: {
lat: coordinateArray[ind].split(',')[0],
lng: coordinateArray[ind].split(',')[1]
}
}
})
}
})
return tour
}
catch(e){
return e
}
}
}

module.exports = Route
15 changes: 15 additions & 0 deletions models/hotel.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,21 @@ var Hotel = new Schema({
facilityInfo: {},
policies: {},
roomInfo: [],
geometry: {
coordinates: { type: [Number], index: '2dsphere'}
}
});

Hotel.query.getNearbyHotels = function(lat, lng, distance){
return this.find({'geometry.coordinates': {
$near: {
$geometry: {
type: "Point",
coordinates: [lng, lat]
},
$maxDistance: distance
}
}})
}

module.exports = mongoose.model('Hotel', Hotel);
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
"start": "node ./bin/www"
},
"dependencies": {
"axios": "^0.20.0",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"dotenv": "^8.2.0",
"expo-secure-store": "^9.0.1",
"express": "~4.16.1",
"fs-extra": "^9.0.1",
Expand All @@ -19,6 +21,7 @@
"mongoose": "^5.9.7",
"morgan": "~1.9.1",
"multer": "^1.4.2",
"node-dijkstra": "^2.5.0",
"nodemon": "^2.0.3",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
Expand Down
48 changes: 29 additions & 19 deletions routes/bookings.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,31 +163,41 @@ router.get('/hotel/checkroomsavailability',async(req, res)=>{
})

router.post('/rooms/book', async(req, res)=>{

let rooms = []
for(const roomSpecificId of req.body.roomSpecificIds){
const rooms = []
const room = await Booking.find({
_id: roomSpecificId,
bookings:{
$not:{
$elemMatch: {from: {$lt: req.body.to.substring(0,10)}, to: {$gt: req.body.from.substring(0,10)}}
try{
const room = await Booking.find({
_id: roomSpecificId,
bookings:{
$not:{
$elemMatch: {from: {$lt: req.body.to.substring(0,10)}, to: {$gt: req.body.from.substring(0,10)}}
}
}
}
})
rooms.push(room)
})
rooms.push(...room)
}
catch(e){
res.send(e)
}
}
if(req.body.roomSpecificIds.length==rooms.length){
const bookings = []
for(const roomSpecificId of req.body.roomSpecificIds){
const booking = Booking.findByIdAndUpdate(roomSpecificID, {
$push: {"bookings": {from: req.body.from, to: req.body.to}}
}, {
safe: true,
new: true
})
bookings.push(booking)
try{
for(const roomSpecificId of req.body.roomSpecificIds){
const booking = await Booking.findByIdAndUpdate(roomSpecificId, {
$push: {"bookings": {from: req.body.from, to: req.body.to}}
}, {
safe: true,
new: true
})
console.log()
bookings.push(booking)
}
res.send(bookings)
}
catch(e){
res.status(400).send(e)
}
res.send(bookings)
}
else{
res.status(400).send()
Expand Down
Loading

0 comments on commit d5d4391

Please sign in to comment.