socketioMEANseed/server/controllers/trainerController.js
server/controllers/trainerController.jsRaw
1var express = require('express');
2var app = express();
3var jwt = require('jsonwebtoken');
4var config = require('../config/config');
5var crypto = require('crypto');
6
7app.set('superSecret', config.secret);
8
9/*******MODELS*********/
10//var trainerModel = require('../models/trainerModel');
11var userModel = require('../models/userModel');
12var dietModel = require('../models/dietModel');
13var routineModel = require('../models/routineModel');
14
15/** GET '/trainers' **/
16exports.getTrainers = function (req, res) {
17 userModel.find({role: 'trainer'})
18 .limit(Number(req.query.pageSize))
19 .skip(Number(req.query.pageSize)*Number(req.query.page))
20 .exec(function (err, trainers) {
21 if (err) return res.send(500, err.message);
22 res.status(200).jsonp(trainers);
23 });
24};
25exports.getTrainersByDisciplinesArray = function (req, res) {
26 userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, user) {
27 if (err) return res.send(500, err.message);
28 if (!user) {
29 res.json({success: false, message: 'sending petition failed. user not found.'});
30 } else if (user) {
31 if(user.disciplines[0])
32 {
33 userModel.find({
34 role: 'trainer',
35 $and: [
36 {_id: { $nin: user._id}},
37 {_id: { $nin: user.trainers}}
38 ],
39 'disciplines.name': user.disciplines[0].name//per ara torna els trainers que tinguin la discipline[0] del user client
40 })
41 .limit(Number(req.query.pageSize))
42 .skip(Number(req.query.pageSize)*Number(req.query.page))
43 .exec(function (err, trainers) {
44 if (err) return res.send(500, err.message);
45 res.status(200).jsonp(trainers);
46 });
47 }else{
48 userModel.find({
49 role: 'trainer',
50 $and: [
51 {_id: { $nin: user._id}},
52 {_id: { $nin: user.trainers}}
53 ]
54 })
55 .limit(Number(req.query.pageSize))
56 .skip(Number(req.query.pageSize)*Number(req.query.page))
57 .exec(function (err, trainers) {
58 if (err) return res.send(500, err.message);
59 res.status(200).jsonp(trainers);
60 });
61 }
62
63 }
64 });
65};
66
67/** GET '/trainers/:trainerid' **/
68exports.getTrainerById = function (req, res) {
69 userModel.findOne({_id: req.params.trainerid, role: 'trainer'})
70 .lean()
71 .populate('routines', 'title description')
72 .populate('clients.client', 'name avatar points')
73 .populate('clientsPetitions.clientid', 'name avatar')
74 .exec(function (err, trainer) {
75 if (err) return res.send(500, err.message);
76 res.status(200).jsonp(trainer);
77 });
78};
79
80/** GET '/trainers/searchByDiscipline' **/
81exports.searchByDiscipline = function (req, res) {
82 userModel.find({'disciplines.name': req.params.discipline, role: 'trainer'})
83 .limit(Number(req.query.pageSize))
84 .skip(Number(req.query.pageSize)*Number(req.query.page))
85 .exec(function (err, trainers) {
86 if (err) return res.send(500, err.message);
87 res.status(200).jsonp(trainers);
88 });
89};
90
91/** POST '/trainers/register' **/
92exports.register = function (req, res) {
93 var trainer = new userModel({
94 name: req.body.name,
95 password: crypto.createHash('sha256').update(req.body.password).digest('base64'),
96 email: req.body.email,
97 avatar: 'img/user.png',
98 background: 'img/background.png',
99 role: req.body.role,
100 discipline: req.body.discipline,
101 points: {
102 total: 0
103 }
104 });
105 /* gamification */
106 var reward = {
107 concept: "account created",
108 date: Date(),
109 value: +1
110 };
111 trainer.points.history.push(reward);
112 trainer.points.total = trainer.points.total + 1;
113 /* end of gamification */
114 trainer.save(function (err, trainer) {
115 if (err) return res.send(500, err.message);
116 res.status(200).jsonp(trainer);
117 });
118};
119
120/** POST '/trainers/login' **/
121exports.login = function (req, res) {
122 userModel.findOne({
123 email: req.body.email, role: 'trainer'
124 })
125 .select('+password')
126 .exec(function (err, trainer) {
127 if (err) throw err;
128 if (!trainer) {
129 res.json({success: false, message: 'Authentication failed. trainer not found.'});
130 } else if (trainer) {
131 req.body.password = crypto.createHash('sha256').update(req.body.password).digest('base64');
132 if (trainer.password != req.body.password) {
133 res.json({success: false, message: 'Authentication failed. Wrong password.'});
134 } else {
135 var indexToken = -1;
136 for (var i = 0; i < trainer.tokens.length; i++) {
137 if (trainer.tokens[i].userAgent == req.body.userAgent) {
138 indexToken = JSON.parse(JSON.stringify(i));
139 }
140 }
141 console.log(indexToken);
142 if (indexToken == -1) {//userAgent no exist
143
144 var tokenGenerated = jwt.sign({foo: 'bar'}, app.get('superSecret'), {
145 // expiresIn: 86400 // expires in 24 hours
146 });
147 var newToken = {
148 userAgent: req.body.userAgent,
149 token: tokenGenerated,
150 os: req.body.os,
151 browser: req.body.browser,
152 device: req.body.device,
153 os_version: req.body.os_version,
154 browser_version: req.body.browser_version,
155 ip: req.body.ip,
156 lastLogin: Date()
157 };
158 trainer.tokens.push(newToken);
159 } else {//userAgent already exist
160 trainer.tokens[indexToken].token = "";
161
162 var tokenGenerated = jwt.sign({foo: 'bar'}, app.get('superSecret'), {
163 // expiresIn: 86400 // expires in 24 hours
164 });
165 trainer.tokens[indexToken].token = tokenGenerated;
166 trainer.tokens[indexToken].ip = req.body.ip;
167 trainer.tokens[indexToken].lastLogin = Date();
168 }
169 trainer.save(function (err, trainer) {
170 if (err) return res.send(500, err.message);
171
172 // return the information including token as JSON
173 trainer.password = "";
174 res.json({
175 user: trainer,
176 success: true,
177 message: 'Enjoy your token!',
178 token: tokenGenerated
179 });
180 });
181 }
182 }
183 });
184};
185
186/** POST '/trainers/acceptClientPetition' **/
187exports.acceptClientPetition = function (req, res) {
188 userModel.findOne({'tokens.token': req.headers['x-access-token'], role: 'trainer'}, function (err, trainer) {
189 if (err) return res.send(500, err.message);
190 if (!trainer) {
191 res.json({success: false, message: 'adding client to trainer failed. trainer not found.'});
192 } else if (trainer) {
193 console.log(trainer);//aquí potser caldria comprovar que la routine és la que han creat per l'trainer
194 //busquem la petition que estem processant
195 for (var i = 0; i < trainer.clientsPetitions.length; i++) //routine.days
196 {
197 if (trainer.clientsPetitions[i]._id.equals(req.body.petitionid)) {
198 var newClient = {
199 client: trainer.clientsPetitions[i].clientid,
200 petitionMessage: trainer.clientsPetitions[i].message,
201 date: Date()
202 };
203 trainer.clients.push(newClient);
204
205 //la petició la marco com a accepted
206 trainer.clientsPetitions[i].state = "accepted";
207 trainer.save(function (err) {
208 if (err) return res.send(500, err.message);
209
210 userModel.findOne({_id: trainer._id, role: 'trainer'})
211 .lean()
212 .populate('routines', 'title description')
213 .populate('clients.client', 'name avatar points')
214 .populate('clientsPetitions.clientid', 'name avatar')
215 .exec(function (err, trainer) {
216 if (err) return res.send(500, err.message);
217 res.status(200).jsonp(trainer);
218 });
219 });
220 //ara afegim el trainer al user.trainer
221 userModel.findOne({'_id': trainer.clientsPetitions[i].clientid}, function (err, user) {
222 if (err) console.log(err.message);
223 if (!user) {
224 console.log('adding client to trainer failed. user not found.');
225 } else if (user) {
226 user.trainers.push(trainer._id);
227
228 /* gamification */
229 var reward = {
230 concept: "new trainer",
231 date: Date(),
232 value: +5
233 };
234 user.points.history.push(reward);
235 user.points.total = user.points.total + 5;
236 /* end of gamification */
237
238 var notification = {
239 state: "pendent",
240 message: "trainer has accepted to train you",
241 link: "training",
242 icon: "newtrainer.png",
243 date: Date()
244 };
245 user.notifications.push(notification);
246 user.save(function (err) {
247 if (err) console.log(err.message);
248 console.log("trainer added to user");
249 });
250 }
251 });
252 }
253 }
254
255 }//end else if
256 });
257};
258
259/** PUT '/trainers/:trainerid' **/
260exports.updateTrainer = function (req, res) {
261 var trainer = req.body;
262 userModel.update({'tokens.token': req.headers['x-access-token']}, trainer,
263 function (err) {
264 if (err) return console.log(err);
265 console.log(trainer);
266 res.status(200).jsonp(trainer);
267 });
268};
269
270/** POST '/trainers/valorateTrainer/:trainerid' **/
271exports.valorateTrainer = function (req, res) {
272 userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, user) {
273 if (err) return res.send(500, err.message);
274 if (!user) {
275 res.json({success: false, message: 'sending valoration failed. user not found.'});
276 } else if (user) {
277 //ara busquem el trainer
278 userModel.findOne({_id: req.params.trainerid, role: 'trainer'}, function (err, trainer) {
279 if (err) return res.send(500, err.message);
280 if (!trainer) {
281 res.json({success: false, message: 'sending valoration failed. trainer not found.'});
282 } else if (trainer) {
283 //comprovem que el client no hagi valorat ja el trainer
284 var javalorat = false;
285 var indexValoration=-1;
286 for (var i = 0; i < trainer.valorations.length; i++) {
287
288 if (trainer.valorations[i].clientid.equals(user._id)) {
289 javalorat = true;
290 indexValoration=JSON.parse(JSON.stringify(i));
291 }
292 }
293
294 if (javalorat == false) {
295 var valoration = {
296 clientid: user._id,
297 date: Date(),
298 message: req.body.message,
299 value: req.body.value
300 };
301 if(!trainer.valoration)
302 {
303 trainer.valoration=0;
304 }
305 var actual = (+trainer.valoration) * trainer.valorations.length;
306 var valor = ((+actual) + (+valoration.value)) / (trainer.valorations.length + 1);
307 trainer.valoration = valor;
308 trainer.valorations.push(valoration);
309
310 var notification = {
311 state: "pendent",
312 message: "client has valorated you",
313 link: "dashboard",
314 icon: "newvaloration.png",
315 date: Date()
316 };
317 trainer.notifications.push(notification);
318
319 trainer.save(function (err) {
320 if (err) return res.send(500, err.message);
321
322 //aquí la gamificació de l'user que fa la valoració per primer cop
323 /* gamification */
324 var reward = {
325 concept: "valorating trainer",
326 date: Date(),
327 value: +1
328 };
329 user.points.history.push(reward);
330 user.points.total = user.points.total + 1;
331 /* end of gamification */
332 user.save(function (err) {
333 /*if (err) return res.send(500, err.message);
334
335 res.status(200).jsonp(routine);*/
336 console.log("points of gamification on trainer valorating added to user");
337 });
338
339 userModel.findOne({_id: trainer._id})
340 .lean()
341 .populate('diets', 'title description')
342 .populate('routines', 'title description')
343 .populate('trainers', 'name avatar description')
344 .populate('clients.client', 'name avatar')
345 .populate('publications')
346 .exec(function (err, trainer) {
347 if (err) return res.send(500, err.message);
348 res.status(200).jsonp(trainer);
349 });
350 });
351 } else {//end if javalorat==false
352 console.log("user already has valorated trainer, updating valoration and recalculating total");
353 var valoration = {
354 clientid: user._id,
355 date: Date(),
356 message: req.body.message,
357 value: req.body.value
358 };
359 var actual = ((+trainer.valoration) * (+trainer.valorations.length)) - (+trainer.valorations[indexValoration].value);//suma total valoracions sense la que estic canviant
360 var valor = ((+actual) + (+valoration.value)) / (trainer.valorations.length);
361 console.log(actual + ", " + valor);
362 trainer.valoration = valor;
363 trainer.valorations[indexValoration]=valoration;
364
365 var notification = {
366 state: "pendent",
367 message: "client has updated the valoration on you",
368 link: "dashboard",
369 icon: "newvaloration.png",
370 date: Date()
371 };
372 trainer.notifications.push(notification);
373
374 trainer.save(function (err) {
375 if (err) return res.send(500, err.message);
376
377 userModel.findOne({_id: trainer._id})
378 .lean()
379 .populate('diets', 'title description')
380 .populate('routines', 'title description')
381 .populate('trainers', 'name avatar description')
382 .populate('clients.client', 'name avatar')
383 .populate('publications')
384 .exec(function (err, trainer) {
385 if (err) return res.send(500, err.message);
386 res.status(200).jsonp(trainer);
387 });
388 });
389 }
390 }//end else if
391 });
392 }//end else if
393 });
394};
395
396/** GET '/trainers/:trainerid/getNotifications' **/
397exports.getNotifications = function (req, res) {
398 userModel.findOne({_id: req.params.trainerid, role: 'trainer'})
399 .exec(function (err, trainer) {
400 if (err) return res.send(500, err.message);
401 for (var i = 0; i < trainer.notifications.length; i++) {
402 if (trainer.notifications[i].state == "pendent") {
403 trainer.notifications[i].state = "viewed";
404 trainer.notifications[i].dateviewed = Date();
405 }
406 }
407 trainer.save(function (err) {
408 if (err) return res.send(500, err.message);
409
410 res.status(200).jsonp(trainer.notifications);
411 });
412 });
413};
414
415/** GET '/trainers/searchByName/:trainername' **/
416exports.searchByName = function (req, res) {
417 console.log("searchByName");
418 userModel.find({name: new RegExp(req.params.trainername, "i"), role: 'trainer'})
419 .limit(Number(req.query.pageSize))
420 .skip(Number(req.query.pageSize)*Number(req.query.page))
421 .exec(function (err, trainers) {
422 if (err) return res.send(500, err.message);
423 res.status(200).jsonp(trainers);
424 });
425};
426
427/** DELETE '/trainers/:trainerid' **/
428exports.removeTrainer = function (req, res) {/* AQUESTA FUNCIÖ CREC QUE ESTÂ MAL PLANTEJADA, DIRIA QUE NO FUNCIONA, si jo també ho diria no es pot trobar despres d'eliminar */
429 userModel.findByIdAndRemove({_id: req.params.trainerid}, function (err) {/**La he corregit, pero tenint en compte que tenim només un model ara potser es redundant no?**/
430 if (err) return res.send(500, err.message);
431 res.status(200).send("Trainer Deleted");
432 });
433};