Skip to content

Commit

Permalink
function 'sending email' is done && delete useless console.log in bac…
Browse files Browse the repository at this point in the history
…kEnd
  • Loading branch information
kaih1994 committed Jun 6, 2017
1 parent 91c2b59 commit 0453693
Show file tree
Hide file tree
Showing 8 changed files with 175 additions and 12 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@
"semantic-ui-css": "^2.2.10",
"semantic-ui-dropdown": "^2.2.10",
"semantic-ui-react": "^0.68",
"sendgrid": "^5.1.1",
"sendgrid-nodejs": "0.1.0-2",
"style-loader": "^0.13.1",
"url-loader": "^0.5.6",
"validator": "^7.0.0",
Expand Down
1 change: 1 addition & 0 deletions server/config/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ module.exports = {
'secret': 'asdawldjal',
databaseUrl: 'mongodb://teamdivider:[email protected]:37101/teamdivider',
authenticationMiddleware: passport.authenticate('jwt', { session: false }),
SENDGRID_API_KEY: "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",
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
const HttpStatus = require("http-status-codes");
const createErrorHandler = require("../../utils").createErrorHandler;
const ObjectIdIsValid = require("mongoose").Types.ObjectId.isValid;

const Activity = require("../../../models").Activity;

const sendgridAPIKey = require("../../../config/main").SENDGRID_API_KEY;
const sendgrid = require("sendgrid")(sendgridAPIKey);
const mailHelper = require('sendgrid').mail;


function groupParticipantsByGroupNumber (pars) {
let groupList = [];
pars.forEach(function (par) {
// iterate all the group in groupList, if there exits that group number, add par to it, and return
for (let i=0; i<groupList.length; i++){
const group = groupList[i];
if (group.groupNumber === par.groupNumber){
group.groupMembers.push(par);
return ;
}
}
// didn't find the group in groupList, create a group and add to groupList
groupList.push({
groupNumber: par.groupNumber,
groupMembers: [par],
});
});

return groupList;
}


function generateHTMLText (participant, group, activity) {
const participantName = participant.name;
let partnerNameList = [];
group.groupMembers.forEach(function (member) {
if (member._id !== participant._id) {
partnerNameList.push(member.name);
}
})
let text = "<b>Dear " + participantName + ",<br>"
+ 'Congratulations! You are now in the group number ' + participant.groupNumber + ".<br>";

if (partnerNameList.length === 0){
text += 'Currently, you are the only one in this group. We would add more people to your group!<br><br>';
}
else if (partnerNameList.length === 1){
text += 'Your partners is ' + partnerNameList[0] + "!<br><br>";
}
else{
text += 'Your partners are ';
for (let i = 0; i < partnerNameList.length - 1; i++) {
text += partnerNameList[i] + ", ";
}
text += partnerNameList[partnerNameList.length -1] + ".<br><br>";
}
return text + "Thank you for attending '" + activity.title + "'!</b>";
}


function validateInput(req) {
return validateParameters(req.params) ;
}

function validateParameters(prm) {
return prm.hasOwnProperty('activityId') && typeof prm.activityId === 'string'
&& ObjectIdIsValid(prm.activityId);
}


module.exports = function (req, res, next) {
if (!validateInput(req)) {
const errorMessage = 'please give the correct activityID in URL';
createErrorHandler(res, HttpStatus.BAD_REQUEST)(errorMessage);
return;
}

Activity.findOne({_id: req.params.activityId, _creator: req.user._id, isDeleted: false})
.populate({
path: 'participants',
select: 'name email groupNumber',
match: {isDeleted: false, groupNumber: {'$nin': [-1, -2] } },
})
.exec()
.then(function (activity) {
if (activity === null) {
const errorMessage = "Cannot find activity: " + req.params.activityId;
return createErrorHandler(res, HttpStatus.NOT_FOUND)(errorMessage);
}

const groupList = groupParticipantsByGroupNumber(activity.participants);

groupList.forEach(function (group) {
group.groupMembers.forEach(function (member) {

// send mail
const from_email = new mailHelper.Email('[email protected]');
const to_email = new mailHelper.Email(member.email);
const subject = 'Activity Notification: Group Information';
const content = new mailHelper.Content('text/html', generateHTMLText(member, group, activity));
const email = new mailHelper.Mail(from_email, subject, to_email, content);

const emailRequest = sendgrid.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: email.toJSON()
});

sendgrid.API(emailRequest, function (error, response) {
if (error !== null){
console.log(error);
return;
}
// console.log(response.statusCode)
// console.log(response.body)
// console.log(response.headers)
console.log("---success in sending email---");
})

})

});


return res.status(HttpStatus.OK).json({
groupList: groupList,
})
})
.catch(createErrorHandler(res, HttpStatus.INTERNAL_SERVER_ERROR));
};

// function generateEmailText (participant, group, activity) {
// const participantName = participant.name;
// let partnerNameList = [];
// group.groupMembers.forEach(function (member) {
// if (member._id !== participant._id) {
// partnerNameList.push(member.name);
// }
// })
// let text = "Dear " + participantName + ",\n"
// + 'Congratulations! You are now in the group number ' + participant.groupNumber + ".\n";
//
// if (partnerNameList.length === 0){
// text += 'Currently, you are the only one in this group. We would add more people to your group!\n\n';
// }
// else if (partnerNameList.length === 1){
// text += 'Your partners is ' + partnerNameList[0] + "!\n\n";
// }
// else{
// text += 'Your partners are ';
// for (let i = 0; i < partnerNameList.length - 1; i++) {
// text += partnerNameList[i] + ", ";
// }
// text += partnerNameList[partnerNameList.length -1] + ".\n\n";
// }
// return text + "Thank you for attending '" + activity.title + "'!";
// }

10 changes: 7 additions & 3 deletions server/routes/activities/controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const getOneActivityController = require("./getOneActivityController");
const deleteActivityController = require("./deleteActivityController");
const updateActivityController = require("./updateActivityController");
const lockGroupInCertainActivityController = require("./lockGroupInCertainActivityController");
const unlockGroupInCertainActivityController = require("./unlockGroupInCertainActivityController")
const unlockGroupInCertainActivityController = require("./unlockGroupInCertainActivityController");
const emailParticipantsForCertainActivityController = require("./emailParticipantsForCertainActivityController");

const activitiesControllers = {
// create an activity
Expand All @@ -24,14 +25,17 @@ const activitiesControllers = {
// delete one activity
deleteActivityController,

//update one activity
// update one activity
updateActivityController,

// lock an group
lockGroupInCertainActivityController,

// unlock an group
unlockGroupInCertainActivityController
unlockGroupInCertainActivityController,

// send email to participants
emailParticipantsForCertainActivityController,
};

module.exports = activitiesControllers;
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ module.exports = function (req, res, next) {
const activityId = req.params.activityId;
const groupNumber = req.body.groupNumber;

console.log(groupNumber);

Activity.findOneAndUpdate(
{
_id: activityId, _creator: userId, isDeleted: false},
Expand Down
3 changes: 3 additions & 0 deletions server/routes/activities/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ activitiesRouter.post('/:activityId/lockedGroup/', authenticationMiddleware,
activitiesRouter.delete('/:activityId/lockedGroup/:groupNumber', authenticationMiddleware,
activitiesControllers.unlockGroupInCertainActivityController);

activitiesRouter.post('/:activityId/sendEmail', authenticationMiddleware,
activitiesControllers.emailParticipantsForCertainActivityController);


activitiesRouter.use('/:activityId/participants', require('./participants'));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,14 @@ module.exports = function (req, res, next) {
createErrorHandler(res, HttpStatus.NOT_FOUND)(errorMessage);
return;
}
console.log("I am here");

// then we try to find the participant by activityID and other constraints
Participant.find({
// _activity: activityId, groupNumber: {'$nin': activity.lockedGroups}, isDeleted: false,
_activity: activityId, _creator: userId, isDeleted: false,
}).sort({ lastModifiedAt: 1 })
.exec()
.then(function (pars) {
console.log("I am here too " + pars);
let filteredPars = [];
let lockedPars = [];
let parsToShowUp = [];
Expand All @@ -74,15 +73,14 @@ console.log("I am here too " + pars);
lockedPars.push(par);
}
});
console.log("I am here too2");
// whatever the pars are empty or not, we go with algorithm, save and print the result
algorithmFcn(filteredPars, activity.groupCapacity, activity.lockedGroups);
console.log("I am here too3");

filteredPars.forEach(function (par) {
par.save().then(function (par) {
}).catch(createErrorHandler(res, HttpStatus.INTERNAL_SERVER_ERROR));
});
console.log("I am here too4");

// combine these two pars array to one since the pars should always be sorted by lastModified
lockedPars.forEach(function (par) {
parsToShowUp.push(par);
Expand Down
2 changes: 0 additions & 2 deletions server/routes/surveys/controllers/createSurveyController.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ module.exports = function (req, res, next) {
const userId = req.user._id;
const payload = req.body;

console.log(payload);

const newSurvey = new Survey({
_creator: userId,
title: payload.title,
Expand Down

0 comments on commit 0453693

Please sign in to comment.