Switch to side-by-side view

--- a/backend/notificationManager.js
+++ b/backend/notificationManager.js
@@ -13,6 +13,7 @@
 	logger.info("backend.controllers.notificationHandler with payload: "+JSON.stringify(body) + ";" +JSON.stringify(destinations) + ";" + JSON.stringify(appToken));
 	//prepare the http response
 	var response = [];
+	var jobsdone = 0;
 
 	//grab the app rules list
 	mysql.getRulesListByToken(appToken, function(success, rules){
@@ -23,7 +24,7 @@
 			//iterate the body
 			body.forEach(function(eachBody, bodyIndex){
 				//prepare the response with some structure
-				response.push({subject: eachBody.subject, subjectValue: eachBody.subjectValue, results:[]});
+				response.push({subject: eachBody.subject, subjectValue: eachBody.subjectValue, total: 0, results:[]});
 				//iterate the rules list
 				rules.forEach(function(eachRule, ruleIndex){
 					applyRule(destinations, eachBody, eachRule, appToken, function(ruleApplied, reason){
@@ -31,38 +32,70 @@
 							if(!reason){
 								//rule applied
 								logger.debug({subject: eachBody.subject, value: eachBody.subjectValue, ruleid: eachRule.rulesID, success: true, comment:"Rule applied"})
-								response.forEach(function(eachResponse){
-									if(eachResponse.subject == eachBody.subject && eachResponse.subjectValue == eachBody.subjectValue){
-										eachResponse.results.push({ruleid: eachRule.rulesID, success: true, comment:"Rule applied"})
-									}
-								})
+								
+								concatenateResponse(response, eachBody, eachRule, true, "Rule applied", function(concat){
+									
+									response = concat;
+									logger.debug("bodyIndex",bodyIndex,"ruleIndex",ruleIndex);
+									jobsdone++;
+									logger.debug("jobsdone",jobsdone,body.length*rules.length);
+									if(jobsdone == (body.length*rules.length)){
+										logger.debug("Finished! bodyIndex",bodyIndex,"ruleIndex",ruleIndex, "jobsdone",jobsdone);
+										cb(true, response)
+									}
+								});
 							}else{
 								//rule not applied because of threshold was not exceed
 								logger.debug({subject: eachBody.subject, value: eachBody.subjectValue, ruleid: eachRule.rulesID, success: false, comment:"Rule's threshold not exceed"});
-								response.forEach(function(eachResponse){
-									if(eachResponse.subject == eachBody.subject && eachResponse.subjectValue == eachBody.subjectValue){
-										eachResponse.results.push({ruleid: eachRule.rulesID, success: false, comment:"Rule's threshold not exceed"})
+								
+								concatenateResponse(response, eachBody, eachRule, false, "Subject's value under Rule's threshold", function(concat){
+									
+									response = concat;
+									logger.debug("bodyIndex",bodyIndex,"ruleIndex",ruleIndex);
+									jobsdone++;
+									logger.debug("jobsdone",jobsdone,body.length*rules.length);
+									if(jobsdone == (body.length*rules.length)){
+										logger.debug("Finished! bodyIndex",bodyIndex,"ruleIndex",ruleIndex, "jobsdone",jobsdone);
+										cb(true, response)
 									}
 								})
 							}
 						}else{
 							//rule not applied
 							logger.debug({subject: eachBody.subject, value: eachBody.subjectValue, ruleid: eachRule.rulesID, success: false, comment:"Rule not applied"})
-							response.forEach(function(eachResponse){
-								if(eachResponse.subject == eachBody.subject && eachResponse.subjectValue == eachBody.subjectValue){
-									eachResponse.results.push({ruleid: eachRule.rulesID, success: false, comment:"Rule not applied"})
+							
+							concatenateResponse(response, eachBody, eachRule, false, "Rule not applied",function(concat){
+								
+								response = concat;
+								logger.debug("bodyIndex",bodyIndex,"ruleIndex",ruleIndex);
+								jobsdone++;
+								logger.debug("jobsdone",jobsdone,body.length*rules.length);
+								if(jobsdone == (body.length*rules.length)){
+									logger.debug("Finished! bodyIndex",bodyIndex,"ruleIndex",ruleIndex, "jobsdone",jobsdone);
+									cb(true, response)
 								}
 							})
-						}
-						//check the loop end
-						logger.debug("bodyIndex",bodyIndex,"body length",body.length,"ruleIndex",ruleIndex,"rules length",rules.length);
-						if(bodyIndex == body.length-1 && ruleIndex == rules.length-1){
-							logger.debug("Finished!");
-							cb(true, response)
 						}
 					})
 				})
 			})
+		}
+	})
+}
+/*
+routine to concatenate the notificationHandler response
+input: response, request body, internal rule applied, success type (boolean), the comment for the rule agains the resquested body
+output: response concatenated
+ */
+function concatenateResponse (response, body, rule, success, comment, cb){
+	response.forEach(function(eachResponse){
+		if(eachResponse.subject == body.subject && eachResponse.subjectValue == body.subjectValue){
+			eachResponse.results.push({ruleid: rule.rulesID, success: success, comment: comment, notType: rule.notificationType})
+			//increment the total
+			if(success){
+				eachResponse.total++;
+			}
+			cb(response);
 		}
 	})
 }
@@ -76,7 +109,6 @@
 //	true, reason 	- rule not applied because values are lower/higher then controlValue defined
 function applyRule(destinations, source, rule, token, cb){
 	var handler = "applyRule";
-	logger.debug(handler,"is starting...");
 	var ruleApplied = false;
 	//check the rule parameter: if not exists, discard
 	if(source.subject == rule.parameter){
@@ -86,7 +118,8 @@
 			subject: source.subject,
 			subjectValue: parseFloat(source.subjectValue),
 			rulesID: rule.rulesID,
-			token: token
+			token: token,
+			ntype: rule.notificationType
 		}
 		switch (rule.conditionValue){
 			case ">":
@@ -110,20 +143,11 @@
 
 			mysql.insertNotification(notificationInput, function(notificationCreated, err){
 				if(notificationCreated){
-					logger.info(handler, "Notification created successfully");
+					logger.info(handler, "Notification created successfully with", JSON.stringify(err.insertId));
 					statsDispatcher(true,source,rule, function(statsCreated, err){
 						if(statsCreated){
 							logger.info(handler, "Stats created successfully");
-							cronDispatcher(rule.notificationType, destinations, source.subject + " = " + source.subjectValue, function(cronCreated, err){
-								if(cronCreated){
-									logger.info(handler, "Cron created successfully");
-									cb(true);		
-								}else{
-									logger.error(handler,err);
-									cb(false, err);
-								}
-							})
-							
+							cb(true);
 						}else{
 							logger.error(handler, err);
 							cb(false, err);
@@ -148,7 +172,7 @@
 			});
 		}
 	}else{
-		cb(false,"Parameter does not match")
+		cb(false, "Parameter does not match")
 	}
 }
 //ruleApplied: TRUE if it was applied properly, FALSE if source is out of value scope
@@ -164,9 +188,10 @@
 	})	
 }
 //self explainatory 
-//TODO THIS CRON IS WRONG!
-function cronDispatcher(schedule, emailTo, subject, cb){
+//function cronDispatcher(appToken, input, schedule, emailTo, subject, cb){
+module.exports.cronDispatcher = function(emailTo, reason){
 	var handler = "cronDispatcher";
+
 	var today = new Date();
 	var endoftwoweeks = new Date();
 	var endofweek = new Date();
@@ -176,41 +201,64 @@
 	endoftwoweeks.setDate(endoftwoweeks.getDate() + 14);
 	endofweek.setDate(endofweek.getDate() + 7);
 	endofthreedays.setDate(endofthreedays.getDate() + 3);
-
-	var toCron = "";
-
-	switch (schedule){
-		case '1':
-			toCron = lastDayOfMonth.getDate();
-			break;
-		case '2':
-			toCron = endoftwoweeks.getDate();
-			break;
-		case '3':
-			toCron = endofweek.getDate();
-			break;
-		case '4':
-			toCron = endofthreedays.getDate();
-			break;
-		default:
-			//trigger immediately
-			toCron = today.getDate();
-	}
-	logger.debug(handler,"email feature is not active");
-	//TODO uncomment this
-	/*
-	var crontab = require('node-crontab');
-	var jobId = crontab.scheduleJob("* * * "+toCron+" * *", function(){
-		
-		for(var i = 0; i < emailTo.length; i++){
-			email.sendEmail(emailTo[i], subject);
+	
+	var thiscron = [
+		{
+			type: 1,
+			list:[],
+			schedule: lastDayOfMonth.getDate(),
+		},{
+			type: 2,
+			list:[],
+			schedule: endoftwoweeks.getDate(),
+		},{
+			type: 3,
+			list:[],
+			schedule: endofweek.getDate(),
+		},{
+			type: 4,
+			list:[],
+			schedule: endofthreedays.getDate(),
+		},{
+			type: 5,
+			list:[],
+			schedule: today.getDate()
 		}
-
-	}, null, null, false);
-	*/
-	cb(true)
+	];
+
+
+	
+	reason.forEach(function(eachElem, reasonidx){
+		eachElem.results.forEach(function(eachResult, resultidx){
+			if(eachResult.success){
+				thiscron[eachResult.notType-1].proceed = true;
+				thiscron[eachResult.notType-1].list.push({subject: eachElem.subject, value: eachElem.subjectValue,rule:eachResult.ruleid})
+			}
+			//detect end loop
+			if(reason.length-1 == reasonidx && eachElem.results.length-1 == resultidx){
+
+				if(process.env.EMAILON){
+					logger.info(handler,"Email feature is activated");
+					var crontab = require('node-crontab');
+					
+					thiscron.forEach(function(eachCron){
+						if(eachCron.proceed){
+							logger.info(handler,"Creating scheduled job for notification type",eachCron.type,"Destination list",emailTo,"Email Content",eachCron.list,"Scheduled for day",eachCron.schedule);
+							var jobid=crontab.scheduleJob("* * * "+eachCron.schedule+" * *", function(){
+								email.sendEmail(emailTo, JSON.stringify(eachCron.list));
+							},null,null,false);
+							logger.info(handler,"Scheduled job created with id",jobid);
+						}
+						
+					})
+				}else{
+					logger.info(handler, "Email feature is NOT activated");
+				}
+			}
+		})
+	})
 }
-
+/* TODO: DELETE THIS FUNCTION - NOT NEEDED ANYMORE */
 module.exports.notificationsCheck= function(body, emailTo, token, callback) {
 
 	var handler = "backend.controllers.notificationManager";
@@ -899,7 +947,7 @@
 		}
 	});
 }
-
+/* TODO: DELETE THIS FUNCTION - NOT NEEDED ANYMORE */
 function cronjob(emailTo, subject, day){
 	var crontab = require('node-crontab');
 	var jobId = crontab.scheduleJob("* * * "+day+" * *", function(){
@@ -908,7 +956,7 @@
 		}
 	}, null, null, false);
 }
-
+/* TODO: DELETE THIS FUNCTION - NOT NEEDED ANYMORE */
 function checkOut(j, length, flag){
 	if(j == length - 1){
 		if(flag == true){