0.0.11 | Built motion from commit e8dda05.
[motion.git] / server / api / contact_manager / contact_manager.controller.js
1 'use strict';
2
3 var _ = require('lodash');
4 var Contact = require('../../models').Contact;
5 var ContactPhone = require('../../models').ContactPhone;
6 var ContactEmail = require('../../models').ContactEmail;
7 var ReportCall = require('../../models').ReportCall;
8 var ReportCallHistory = require('../../models').history.ReportCallHistory;
9 var ReportMailSession = require('../../models').ReportMailSession;
10 var ReportMailSessionHistory = require('../../models').history.ReportMailSessionHistory;
11 var Tag = require('../../models').Tag;
12 var stream = require('stream');
13 var sequelize = require('../../models').sequelize;
14 var util = require('util');
15
16 // Get list of contacts
17 exports.index = function(req, res) {
18
19   var attributes = ['name', 'surname', 'description'];
20   var per_page = req.query.per_page ? parseInt(req.query.per_page, 10) : 100;
21   var page = req.query.page ? parseInt(req.query.page, 10) : 0;
22
23   var query = {
24     where: {},
25     limit: per_page,
26     offset: page * per_page
27   };
28
29   _.forIn(req.query, function(value, key) {
30     switch (key) {
31       case 'per_page':
32       case 'page':
33         break;
34       case 'sort_by':
35         query.order = util.format('%s %s', req.query.sort_by, req.query.sort_order || 'ASC') || null;
36         break;
37       case 'sort_order':
38         break;
39       case '$':
40         query.where.$or = [];
41         attributes.forEach(function(attribute) {
42           var tmp = {};
43           tmp[attribute] = {
44             $like: '%' + value + '%'
45           };
46
47           query.where.$or.push(tmp);
48         });
49         break;
50       default:
51         query.where[key] = {
52           $like: {}
53         };
54         query.where[key].$like = '%' + value + '%';
55     }
56   });
57
58
59   Contact
60     .findAndCountAll(query)
61     .then(function(managed_contacts) {
62       return res.status(200).send(managed_contacts);
63     })
64     .catch(function(err) {
65       return handleError(res, err);
66     });
67 };
68
69 // Get a single managed_contact
70 exports.show = function(req, res) {
71   Contact
72     .findById(req.params.id, {
73       include: [{
74         model: ContactPhone,
75         as: 'Phones',
76         include: [{
77           model: ReportCall,
78           as: 'Inbounds',
79           include: [{
80             all: true
81           }]
82         }, {
83           model: ReportCall,
84           as: 'Outbounds',
85           include: [{
86             all: true
87           }]
88         }, {
89           model: ReportCallHistory,
90           as: 'HistoryInbounds',
91           include: [{
92             all: true
93           }]
94         }, {
95           model: ReportCallHistory,
96           as: 'HistoryOutbounds',
97           include: [{
98             all: true
99           }]
100         }]
101       }, {
102         model: ContactEmail,
103         as: 'Emails',
104         include: [{
105           model: ReportMailSession,
106           as: 'InboundMessages',
107           include: [{
108             all: true
109           }]
110         }, {
111           model: ReportMailSession,
112           as: 'OutboundMessages',
113           include: [{
114             all: true
115           }]
116         }, {
117           model: ReportMailSessionHistory,
118           as: 'HistoryInboundMessages',
119           include: [{
120             all: true
121           }]
122         }, {
123           model: ReportMailSessionHistory,
124           as: 'HistoryOutboundMessages',
125           include: [{
126             all: true
127           }]
128         }]
129       }]
130     })
131     .then(function(managed_contact) {
132       if (!managed_contact) {
133         return res.sendStatus(404);
134       }
135       return res.send(managed_contact);
136     })
137     .catch(function(err) {
138       console.log(err);
139       return handleError(res, err);
140     });
141 };
142
143 exports.getHistory = function(req, res) {
144
145 };
146
147 // validate contact uniqueness
148 exports.contactValidation = function(req, res) {
149   Contact.findAll({
150       where: {
151         $or: {
152           '$Phones.phone$': req.body.phones,
153           '$Emails.email$': req.body.emails
154         }
155       },
156       include: [{
157         all: true
158       }]
159     })
160     .then(function(contacts) {
161       console.log(contacts);
162       return res.status(200).send(contacts);
163     })
164     .catch(function(err) {
165       console.log(err);
166       return handleError(res, err);
167     });
168 };
169 // Creates a new managed_contact in the DB.
170 exports.create = function(req, res, next) {
171   var newPhones = [],
172     newEmails = [];
173   Tag.findAll()
174     .then(function(tags) {
175       var newTags = [];
176       var tagList = _.pluck(_.pluck(tags, 'dataValues'), 'name');
177       if (req.body.tags) {
178         var contactTags = req.body.tags.split(',');
179         contactTags.forEach(function(elem) {
180           if (!_.includes(tags, elem)) {
181             newTags.push({
182               name: elem
183             });
184           }
185         });
186         if (newTags.length) {
187           Tag.bulkCreate(newTags, {
188             individualHooks: true
189           });
190         }
191       }
192       req.body.UserId = req.user.id;
193       console.log('body', req.body);
194       var phones = _.uniq(_.pluck(req.body.Phones, 'phone'));
195       console.log(phones);
196       var emails = _.uniq(_.pluck(req.body.Emails, 'email'));
197       console.log(emails);
198       var contactPhones = [];
199       req.body.Phones.forEach(function(elem) {
200         console.log('elem', elem);
201         contactPhones.push(ContactPhone.findOrCreate({
202           where: {
203             phone: elem.phone
204           },
205           defaults: {
206             phone: elem.phone
207           }
208         }));
209       });
210       console.log('return cP');
211       return contactPhones;
212     })
213     .all()
214     .then(function(res) {
215       newPhones = _.map(res, function(elem) {
216         return elem[0];
217       });
218
219       var contactEmails = [];
220       req.body.Emails.forEach(function(elem) {
221         console.log('elem', elem);
222         contactEmails.push(ContactEmail.findOrCreate({
223           where: {
224             email: elem.email
225           },
226           defaults: {
227             email: elem.email
228           }
229         }));
230       });
231
232       return contactEmails;
233     })
234     .all()
235     .then(function(res) {
236       newEmails = _.map(res, function(elem) {
237         return elem[0];
238       });
239       delete req.body.Phones;
240       delete req.body.Emails;
241
242       return Contact.create(req.body);
243     })
244     .then(function(contact) {
245       return [contact, contact.setPhones(newPhones)];
246     })
247     .spread(function(contact) {
248       return [contact, contact.setEmails(newEmails)];
249     })
250     .spread(function(contact) {
251       return res.status(201).send(contact);
252     })
253     .catch(function(err) {
254       console.log(err);
255       return next(err);
256     });
257 };
258
259 // Updates an existing managed_contact in the DB.
260 exports.update = function(req, res, next) {
261   req.body.Phones = _.uniq(_.pluck(req.body.Phones, 'phone'));
262   req.body.Emails = _.uniq(_.pluck(req.body.Emails, 'email'));
263   console.log(req.body.Phones);
264   console.log(req.body.Emails);
265   Contact.findAll({
266       where: {
267         $or: {
268           '$Phones.phone$': req.body.Phones,
269           '$Emails.email$': req.body.Emails
270         },
271         id: {
272           $ne: req.params.id
273         }
274       },
275       include: [{
276         all: true
277       }]
278     })
279     .then(function(contacts) {
280       console.log(contacts);
281       if (!contacts) {
282         return res.sendStatus(404);
283       }
284       if (contacts.length > 0) {
285         return res.status(500).send({
286           message: 'MESSAGE_EXIST_PHONE_OR_EMAIL'
287         });
288       }
289       Tag.findAll()
290         .then(function(tags) {
291           var newTags = [];
292           var tagList = _.pluck(_.pluck(tags, 'dataValues'), 'name');
293           if (req.body.tags) {
294             var contactTags = req.body.tags.split(',');
295             contactTags.forEach(function(elem) {
296               if (!_.includes(tags, elem)) {
297                 newTags.push({
298                   name: elem
299                 });
300               }
301             });
302             if (newTags.length) {
303               Tag.bulkCreate(newTags, {
304                 individualHooks: true
305               });
306             }
307           }
308           delete req.body.id;
309           var phones = _.map(req.body.Phones, function(elem) {
310             return {
311               phone: elem,
312               ContactId: req.params.id
313             };
314           });
315           var emails = _.map(req.body.Emails, function(elem) {
316             return {
317               email: elem,
318               ContactId: req.params.id
319             };
320           });
321           delete req.body.Phones;
322           delete req.body.Emails;
323           return sequelize.transaction(function(t) {
324               return Contact.update(req.body, {
325                   where: {
326                     id: req.params.id
327                   }
328                 }, {
329                   transaction: t,
330                   include: [{
331                     all: true
332                   }]
333                 })
334                 .then(function() {
335                   return ContactPhone
336                     .destroy({
337                       where: {
338                         ContactId: req.params.id
339                       }
340                     }, {
341                       transaction: t
342                     })
343                     .then(function() {
344                       return ContactPhone
345                         .bulkCreate(phones, {
346                           transaction: t
347                         })
348                         .then(function() {
349                           return ContactEmail
350                             .destroy({
351                               where: {
352                                 ContactId: req.params.id
353                               }
354                             }, {
355                               transaction: t
356                             })
357                             .then(function() {
358                               return ContactEmail
359                                 .bulkCreate(emails, {
360                                   transaction: t
361                                 })
362                                 .then(function() {
363                                   return res.sendStatus(201);
364                                 })
365                             })
366                         })
367                     })
368                 })
369             })
370             .catch(function(err) {
371               return handleError(res, err);
372             });
373         })
374         .catch(function(err) {
375           return handleError(res, err);
376         });
377
378     })
379     .catch(function(err) {
380       console.log(err);
381       return handleError(res, err);
382     });
383 };
384
385 // Join contacts info in the DB.
386 exports.joinContacts = function(req, res, next) {
387   if (req.body.tags) {
388     Tag.findAll()
389       .then(function(tags) {
390         var newTags = [];
391         var tagList = _.pluck(_.pluck(tags, 'dataValues'), 'name');
392         var contactTags = req.body.tags.split(',');
393         contactTags.forEach(function(elem) {
394           if (!_.includes(tags, elem)) {
395             newTags.push({
396               name: elem
397             });
398           }
399         });
400         if (newTags.length) {
401           Tag.bulkCreate(newTags, {
402             individualHooks: true
403           });
404         }
405       })
406       .catch(function(err) {
407         return handleError(res, err);
408       });
409   }
410   var updateId = req.body.id;
411   delete req.body.id;
412   var phones = _.map(req.body.Phones, function(elem) {
413     return {
414       phone: elem.phone,
415       ContactId: updateId
416     };
417   });
418   var emails = _.map(req.body.Emails, function(elem) {
419     return {
420       email: elem.email,
421       ContactId: updateId
422     };
423   });
424   delete req.body.Phones;
425   delete req.body.Emails;
426   return sequelize.transaction(function(t) {
427       return Contact.update(req.body, {
428           where: {
429             id: updateId
430           }
431         }, {
432           transaction: t,
433           include: [{
434             all: true
435           }]
436         })
437         .then(function(contact) {
438           return ContactPhone
439             .bulkCreate(phones, {
440               transaction: t
441             })
442             .then(function() {
443               return ContactEmail
444                 .bulkCreate(emails, {
445                   transaction: t
446                 })
447                 .then(function() {
448                   return Contact.findById(updateId, {
449                       transaction: t
450                     })
451                     .then(function(contact) {
452                       return res.status(201).send(contact);
453                     })
454                 })
455             })
456         })
457     })
458     .catch(function(err) {
459       console.log(err);
460       return next(err);
461     });
462 };
463
464 // Deletes a managed_contact from the DB.
465 exports.destroy = function(req, res) {
466   Contact
467     .findById(req.params.id)
468     .then(function(managed_contact) {
469       if (!managed_contact) {
470         return res.sendStatus(404);
471       }
472       managed_contact.destroy()
473         .then(function() {
474           return res.sendStatus(204);
475         })
476         .catch(function(err) {
477           return handleError(res, err);
478         });
479     })
480     .catch(function(err) {
481       return handleError(res, err);
482     });
483 };
484
485 // Deletes a managed_contact from the DB.
486 exports.bulkDestroy = function(req, res) {
487   Contact
488     .destroy({
489       where: {
490         id: req.query.id
491       },
492       individualHooks: true
493     })
494     .then(function() {
495       return res.sendStatus(204);
496     })
497     .catch(function(err) {
498       return handleError(res, err);
499     });
500 };
501
502 function handleError(res, err) {
503   return res.status(500).send(err);
504 }