Skip to content

Commit

Permalink
finished routes and tests for new apartment feature #335
Browse files Browse the repository at this point in the history
  • Loading branch information
chananbental committed Jun 18, 2018
1 parent d6c4518 commit 0c13a92
Show file tree
Hide file tree
Showing 4 changed files with 330 additions and 2 deletions.
115 changes: 115 additions & 0 deletions server/models/search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@

const mongoose = require('mongoose');
const _ = require('lodash');


const {Apartment} = require('../../server/models/apartment');
const {EARTH_RADIUS_IN_KM} = require('../constants');
const geoLocation = require('../services/geoLocation/geoLocation');
const {removeFalsyProps} = require('../helpers/removeFalsyProps');
const {getIndexOfValue, getIndexOfFirstElementMatchKey} = require('../helpers/arrayFunctions');
const {ObjectID} = require('mongodb');

const SearchSchema = new mongoose.Schema({
createdBy: {
type: mongoose.Schema.Types.ObjectId,
required: true
},
createdAt: {
type: Number,
required: true
},
price: [{
type: Number,
min: 0,
}],
entranceDate: {
type: Number,
required: true
},
address: {
type: String,
minlength: 2,
maxlength: 100,
lowercase: true,
trim: true,
},
geolocation: {
type: [Number],
index: '2dsphere',
default: [0, 0]
},
radius:{
type: Number
},
floor: [{
type: Number,
}],
tags: [{
type: Number,
}],
roommates: [{
type: Number,
}]
});

/**
* @author Chanan Ben-Tal
*
* main function of this model
* go through all new apartments and check if any new searchs would have found them
* then notify the users who made the searchs
*/
SearchSchema.methods.checkNewApartments = async function() {
const day = 1000*60*60*24 //1000 ms * 60 secs * 60 min * 24 hours
const query = {};
query.createdAt = {
$gte: (Date.now()-day)
};

const newApartments = await Apartment.find(query);
const toBeNotified = [];

const searchs = await Search.find({});

var result;

searchs.forEach(element => { //get rid of old searchs, old == over 2 days
if(Date.now() - element.createdAt>(2*day)){
Search.findByIdAndRemove(element._id);
}
});
await searchs.forEach(async (search) => {
if(Date.now() - search.createdAt>(2*day)){
return;
}
newApartments.forEach(apartment => {

if(search.price[0]<=apartment.price && search.price[1]>=apartment.price){
if(search.roommates[0]<=apartment.totalRoommates && search.roommates[1]>=apartment.totalRoommates){
if(search.floor[0]<=apartment.floor && search.floor[1]>=apartment.floor){ //floor
if(search.entranceDate <= apartment.entranceDate){ //
toBeNotified.forEach(id => {

if(id.equals(search.createdBy)){
result++;
}
})
if(!result){
toBeNotified.push(search.createdBy);
}
result = 0;
}
}
}
}
});
});
return toBeNotified;
};

const Search = mongoose.model('Search', SearchSchema);

module.exports = {
Search
};
66 changes: 66 additions & 0 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ const {
const {
User
} = require('./models/user');
const {
Search
} = require('./models/search');

const {
XAUTH
} = require('./constants');
Expand Down Expand Up @@ -65,6 +69,7 @@ const userVerificator = require('./services/user-verification/user-verificator')
const passwordReset = require('./services/password-reset/password-reset');
const errors = require('./errors');
const imageService = require('./services/image-service/image-service');
const mail = require('./services/mail/mail');

const app = express();

Expand Down Expand Up @@ -1498,6 +1503,67 @@ app.patch('/apartments/:id/groups/sign', authenticate, async (req, res) => {
}
});



app.post('/searchs', async (req, res) => {
try {
const query = _.pick(req.body, [
'createdBy', // String of a legal ObjectID
'entranceDate', // A value which can be converted into Date
'address', // String of the full address
'radius', // Number, which indicates the range from the address or geolocation
'price', // Array of 2 Numbers, which indicates the price range
'roommates', // Array of 2 Numbers, which indicates the roommates range
'floor', // Array of 2 Numbers, which indicates the floor range
'tags', // Array of the tags Numbers (ids)
'geolocation' // Array of 2 numbers: ['longitude','latitude']
]);
query.createdAt = Date.now();
const search = await new Search(query).save();
return res.send({
search
});
} catch (err) {
res.status(BAD_REQUEST).send(err.message);
}
});

app.get('/searchs/toNotify', async (req, res) => {
try {
const search = new Search;
const toBeNotified = await search.checkNewApartments();
await User.find({}).then( res => {
res.forEach( user => {
toBeNotified.forEach(async id => {
if(user._id.equals(id)){
const msg = {
to: user.email,
from: 'newApartmentsForYou@roommatesyearlyproject.com',
subject: '[Roommates] New apartments you might like!',
html: `<h1>Come back to Roommates!</h1>
<p>apartments matching your latest searchs have been added</p>`,
};
mail.sendMail(msg);
}
});
})
});


// console.log("got users to notify");
return res.send({
toBeNotified
});
} catch (err) {
return res.status(BAD_REQUEST).send(err);
}
});






/**
* @author: Alon Talmor
* @date: 28/3/18
Expand Down
78 changes: 77 additions & 1 deletion tests/seed/seed.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const {
FORGOT_SECRET
} = require('../../server/constants');
const visit = require('../../server/models/visit');
const { Search } = require('../../server/models/search');

const user1Id = new ObjectID();
const user2Id = new ObjectID();
Expand All @@ -51,6 +52,9 @@ const apartment1User2VisitId = new ObjectID();

const user1Notification1Id = new ObjectID();

const newSearchID = new ObjectID;
const oldSearchID = new ObjectID;

const apartment1 = new Apartment({
_id: apartment1Id,
_createdBy: new ObjectID(),
Expand Down Expand Up @@ -608,6 +612,58 @@ const notPublishedReview2 = {
// status: 2, //accepted
// };



const unsearchedSearch = {
createdBy:user1Id,
address: null,
geolocation: [35.020568, 32.776515],
price: [0, 10000],
radius: 10,
roommates: [1, 3],
floor: [1, 20],
entranceDate: new Date('2018-05-05').getTime(),
tags: []
};


const newSearch = {
_id: newSearchID,
createdBy:user1Id,
createdAt: Date.now(),
address: null,
geolocation: [35.2340603, 31.7765232],
price: [0, 9000],
radius: 20,
roommates: [1, 7],
floor: [1, 10],
entranceDate: new Date('2018-05-06').getTime(),
tags: []
};

const oldSearch = {
_id: oldSearchID,
createdBy:user1Id,
createdAt: (Date.now() - (1000*60*60*24*3)),
address: null,
geolocation: [35.2340603, 31.7765232],
price: [0, 9000],
radius: 20,
roommates: [1, 7],
floor: [1, 10],
entranceDate: new Date('2018-05-06').getTime(),
tags: []
};


const searchs = [
unsearchedSearch,
newSearch,
oldSearch
];



const apartments = [
apartment1,
apartment2,
Expand Down Expand Up @@ -690,6 +746,22 @@ const populateReviews = (done) => {
.catch(done);
};


const populateSearchs = (done) => {
Search.remove({})
.then(() =>
Promise.all([
new Search(searchs[1]).save(),
new Search(searchs[2]).save(),
]))
.then(() => done())
.catch(done);
};





// const populateGroups = (done) => {
// Group.remove({})
// .then(() =>
Expand Down Expand Up @@ -725,5 +797,9 @@ module.exports = {
user2VerificationToken,
getForgotPasswordToken,
review1Id,
review2Id
review2Id,
populateSearchs,
unsearchedSearch,
newSearch,
oldSearch
};
Loading

0 comments on commit 0c13a92

Please sign in to comment.