Built motion from commit 06df96e on branch develop.
[motion.git] / server / api / agent / agent.controller.js
1 'use strict';
2
3 var _ = require('lodash');
4 var util = require('util');
5 var Agent = require('../../models').User;
6 var Team = require('../../models').Team;
7
8 // Get list of agents
9 exports.index = function(req, res, next) {
10
11   var attributes = ['fullname', 'name', 'email'];
12   var per_page = req.query.per_page ? parseInt(req.query.per_page, 10) : 100;
13   var page = req.query.page ? parseInt(req.query.page, 10) : 0;
14
15   var query = {
16     where: {
17       role: 'agent'
18     },
19     limit: per_page,
20     offset: page * per_page
21   };
22
23   _.forIn(req.query, function(value, key) {
24     switch (key) {
25       case 'per_page':
26       case 'page':
27         break;
28       case 'sort_by':
29         query.order = util.format('%s %s', req.query.sort_by, req.query.sort_order || 'ASC') || null;
30         break;
31       case 'sort_order':
32         break;
33       case '$':
34         query.where.$or = [];
35         attributes.forEach(function(attribute) {
36           var tmp = {};
37           tmp[attribute] = {
38             $like: '%' + value + '%'
39           };
40
41           query.where.$or.push(tmp);
42         });
43         break;
44       default:
45         query.where[key] = {
46           $like: {}
47         };
48         query.where[key].$like = '%' + value + '%';
49     }
50   });
51
52   Agent
53     .findAndCountAll(query)
54     .then(function(result) {
55
56       var total_pages = Math.ceil(result.count / per_page);
57       var next_page = total_pages > (query.offset + 1) ? util.format('%s://%s%s?page=%d', req.protocol, req.headers.host, req.baseUrl, page + 1) : null;
58       var previous_page = page > 0 ? util.format('%s://%s%s?page=%d', req.protocol, req.headers.host, req.baseUrl, page - 1) : null;
59
60       res.status(200).send({
61         count: result.count,
62         rows: result.rows,
63         next_page: next_page,
64         previous_page: previous_page,
65         total_pages: total_pages
66       });
67
68     })
69     .catch(function(err) {
70       res.status(500).send({
71         error: 'Something blew up!'
72       });
73     });
74 };
75
76 // Get a single agent
77 exports.show = function(req, res) {
78   Agent
79     .findById(req.params.id)
80     .then(function(agent) {
81       if (!agent) {
82         return res.sendStatus(404);
83       }
84       return res.send(agent);
85     })
86     .catch(function(err) {
87       return handleError(res, err);
88     });
89 };
90
91 // Validate the existence of an internal number
92 exports.internalValidation = function(req, res) {
93   Agent
94     .findAll({
95       where: {
96         internal: req.body.internal
97       }
98     })
99     .then(function(internals) {
100       if (!internals) {
101         return res.sendStatus(404);
102       }
103       return res.send(internals);
104     })
105     .catch(function(err) {
106       return handleError(res, err);
107     });
108 };
109
110 // Creates a new agent in the DB.
111 exports.create = function(req, res) {
112   Agent
113     .create(req.body)
114     .then(function(agent) {
115       Team
116         .findOne({
117           where: {
118             defaultEntry: true
119           }
120         })
121         .then(function(team) {
122           team
123             .addUser(agent.id)
124             .then(function() {
125               return res.status(201).send(agent);
126             })
127             .catch(function(err) {
128               console.log(err);
129               return handleError(res, err);
130             });
131         })
132         .catch(function(err) {
133           console.log(err);
134           return handleError(res, err);
135         });
136     })
137     .catch(function(err) {
138       console.log(err);
139       return handleError(res, err);
140     });
141 };
142
143 // Updates an existing agent in the DB.
144 exports.update = function(req, res) {
145   if (req.body.id) {
146     delete req.body.id;
147   }
148   Agent
149     .findById(req.params.id)
150     .then(function(agent) {
151       if (!agent) {
152         return res.sendStatus(404);
153       }
154       var updated = _.merge(agent, req.body);
155       updated
156         .save()
157         .then(function() {
158           return res.status(200).send(agent);
159         })
160         .catch(function(err) {
161           return handleError(res, err);
162         });
163     })
164     .catch(function(err) {
165       return handleError(res, err);
166     });
167 };
168
169 // Deletes a agent from the DB.
170 exports.destroy = function(req, res) {
171   Agent
172     .findById(req.params.id)
173     .then(function(agent) {
174       if (!agent) {
175         return res.sendStatus(404);
176       }
177       agent.destroy()
178         .then(function() {
179           return res.sendStatus(204);
180         })
181         .catch(function(err) {
182           return handleError(res, err);
183         });
184     })
185     .catch(function(err) {
186       return handleError(res, err);
187     });
188 };
189
190 // Deletes a agent from the DB.
191 exports.bulkDestroy = function(req, res) {
192   Agent
193     .destroy({
194       where: {
195         id: req.query.id
196       },
197       individualHooks: true
198     })
199     .then(function() {
200       return res.sendStatus(204);
201     })
202     .catch(function(err) {
203       return handleError(res, err);
204     });
205 };
206
207 /**
208  * Change an agent password
209  */
210 exports.changePassword = function(req, res, next) {
211   console.log(req.body);
212   var agentId = req.user.id;
213   var oldPass = String(req.body.oldPassword);
214   var newPass = String(req.body.newPassword);
215   Agent
216     .findById(agentId)
217     .then(function(agent) {
218       if (agent.authenticate(oldPass)) {
219         agent.password = newPass;
220         agent.save()
221           .then(function() {
222             res.status(200).send(agent);
223           })
224           .catch(function(err) {
225             return next(err);
226           });
227       } else {
228         res.sendStatus(403);
229       }
230     });
231 };
232
233 /**
234  * Change an agent password by admin
235  */
236 exports.resetPassword = function(req, res, next) {
237   var newPass = String(req.body.newPassword);
238   Agent
239     .findById(req.params.id)
240     .then(function(user) {
241       user.password = newPass;
242       user.save()
243         .then(function() {
244           res.status(200).send(user);
245         })
246         .catch(function(err) {
247           return handleError(res, err);
248         });
249     });
250 };
251
252 exports.agentValidation = function(req, res) {
253   var where = {};
254   where[req.params.field] = req.body.value;
255   Agent
256     .findAndCountAll({
257       where: where
258     })
259     .then(function(result) {
260       if (result.count) {
261         return res.status(200).send({
262           isValid: false,
263           value: req.body.value
264         });
265       }
266       return res.status(200).send({
267         isValid: true,
268         value: req.body.value
269       });
270     })
271     .catch(function(err) {
272       return handleError(res, err);
273     });
274
275 };
276
277 function handleError(res, err) {
278   return res.status(500).send(err);
279 }