d55030397c64aaf88820932c1d8b7ca7b1437d24
[motion.git] / server / api / fax_account / fax_account.controller.js
1 'use strict';
2
3 var _ = require('lodash');
4 var util = require('util');
5 var async = require('async');
6
7 var Trunk = require('../../models').Trunk;
8 var FaxAccount = require('../../models').FaxAccount;
9 var FaxApplication = require('../../models').FaxApplication;
10 var VoiceExtension = require('../../models').VoiceExtension;
11 var sequelize = require('../../models').sequelize;
12
13 // Get list of agents
14 exports.index = function(req, res, next) {
15
16   var attributes = ['description', 'name', 'phone'];
17   var per_page = req.query.per_page ? parseInt(req.query.per_page, 10) : 100;
18   var page = req.query.page ? parseInt(req.query.page, 10) : 0;
19
20   var query = {
21     where: {},
22     limit: per_page,
23     offset: page * per_page
24   };
25
26   _.forIn(req.query, function(value, key) {
27     switch (key) {
28       case 'per_page':
29       case 'page':
30         break;
31       case 'sort_by':
32         query.order = util.format('%s %s', req.query.sort_by, req.query.sort_order || 'ASC') || null;
33         break;
34       case 'sort_order':
35         break;
36       case '$':
37         query.where.$or = [];
38         attributes.forEach(function(attribute) {
39           var tmp = {};
40           tmp[attribute] = {
41             $like: '%' + value + '%'
42           };
43
44           query.where.$or.push(tmp);
45         });
46         break;
47       default:
48         query.where[key] = {
49           $like: {}
50         };
51         query.where[key].$like = '%' + value + '%';
52     }
53   });
54
55   FaxAccount
56     .findAndCountAll(query)
57     .then(function(result) {
58
59       var total_pages = Math.ceil(result.count / per_page);
60       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;
61       var previous_page = page > 0 ? util.format('%s://%s%s?page=%d', req.protocol, req.headers.host, req.baseUrl, page - 1) : null;
62
63       res.status(200).send({
64         count: result.count,
65         rows: result.rows,
66         next_page: next_page,
67         previous_page: previous_page,
68         total_pages: total_pages
69       });
70
71     })
72     .catch(function(err) {
73       res.status(500).send({
74         error: 'Something blew up!'
75       });
76     });
77 };
78
79 // Get a single faxAccount
80 exports.show = function(req, res, next) {
81   FaxAccount
82     .findById(req.params.id)
83     .then(function(faxAccount) {
84       if (!faxAccount) {
85         return res.sendStatus(404);
86       }
87       return res.send(faxAccount);
88     })
89     .catch(function(err) {
90       return next(err);
91     });
92 };
93
94 // Creates a new faxAccount in the DB.
95 exports.create = function(req, res, next) {
96   // console.log(req.body);
97   return sequelize
98     .transaction()
99     .then(function(t) {
100       async.waterfall([
101         function(callback) {
102           return FaxAccount
103             .create(req.body, {
104               transaction: t
105             })
106             .then(function(faxAccount) {
107               callback(null, faxAccount);
108             })
109             .catch(function(err) {
110               callback(err);
111             });
112         },
113         function(faxAccount, callback) {
114           return Trunk
115             .findById(req.body.TrunkId, {
116               transaction: t
117             })
118             .then(function(faxTrunk) {
119               callback(null, faxAccount, faxTrunk);
120             })
121             .catch(function(err) {
122               callback(err);
123             });
124         },
125         function(faxAccount, faxTrunk, callback) {
126           return VoiceExtension
127             .create({
128               context: faxTrunk.context,
129               exten: req.body.phone,
130               priority: 1,
131               app: 'Goto',
132               appdata: 'inbound-fax,s,1',
133               type: 'inbound-fax',
134               TrunkId: faxTrunk.id
135             }, {
136               transaction: t
137             })
138             .then(function(voiceExtension) {
139               callback(null, faxAccount);
140             })
141             .catch(function(err) {
142               callback(err);
143             });
144         }
145       ], function(err, faxAccount) {
146         if (err) {
147           console.log(err);
148           t.rollback();
149           return res.status(404).send(err);
150         } else {
151           console.log('ok');
152           t.commit();
153           return res.status(201).send(faxAccount);
154         }
155       })
156     });
157 };
158
159 // Updates an existing faxAccount in the DB.
160 exports.update = function(req, res, next) {
161   // console.log(req.body);
162   // console.log(req.params);
163
164   if (req.body.id) {
165     delete req.body.id;
166   }
167
168   return sequelize
169     .transaction()
170     .then(function(t) {
171       async.waterfall([
172         function(callback) {
173           return FaxAccount
174             .findOne({
175               where: {
176                 id: req.params.id
177               },
178               include: [{
179                 model: Trunk
180               }]
181             }, {
182               transaction: t
183             })
184             .then(function(faxAccount) {
185               callback(null, faxAccount);
186             })
187             .catch(function(err) {
188               callback(err);
189             });
190         },
191         function(faxAccount, callback) {
192           return Trunk
193             .findById(req.body.TrunkId, {
194               transaction: t
195             })
196             .then(function(trunk) {
197               return faxAccount
198                 .updateAttributes({
199                   TrunkId: trunk.id
200                 }, {
201                   transaction: t
202                 })
203                 .then(function(data) {
204                   callback(null, faxAccount, trunk);
205                 })
206                 .catch(function(err) {
207                   callback(err);
208                 });
209             })
210             .catch(function(err) {
211               callback(err);
212             });
213         },
214         function(faxAccount, trunk, callback) {
215           return VoiceExtension
216             .findOne({
217               where: {
218                 priority: 1,
219                 exten: faxAccount.phone,
220                 context: faxAccount.Trunk.context
221               }
222             }, {
223               transaction: t
224             })
225             .then(function(voiceExtension) {
226               if (!voiceExtension) {
227                 callback(null, faxAccount);
228               }
229               return voiceExtension
230                 .updateAttributes({
231                   exten: req.body.phone,
232                   context: trunk.context,
233                   TrunkId: req.body.UserId
234                 }, {
235                   transaction: t
236                 })
237                 .then(function() {
238                   console.log('voiceExtension edited');
239                   callback(null, faxAccount);
240                 })
241                 .catch(function(err) {
242                   callback(err);
243                 });
244             })
245             .catch(function(err) {
246               callback(err);
247             });
248         },
249         function(faxAccount, callback) {
250           var updated = _.merge(faxAccount, req.body);
251           return updated.save({
252               transaction: t
253             })
254             .then(function() {
255               console.log('faxAccount saved');
256               callback(null, faxAccount);
257             })
258             .catch(function(err) {
259               callback(err);
260             });
261         }
262       ], function(err, faxAccount) {
263         if (err) {
264           console.log(err);
265           t.rollback();
266           return res.status(404).send(err);
267         } else {
268           console.log('ok');
269           t.commit();
270           return res.status(201).send(faxAccount);
271         }
272       })
273     });
274 };
275
276 // Deletes a faxAccount from the DB.
277 exports.destroy = function(req, res, next) {
278   FaxAccount
279     .find({
280       where: {
281         id: req.params.id
282       }
283     })
284     .then(function(faxAccount) {
285       if (!faxAccount) {
286         return res.sendStatus(404);
287       }
288       faxAccount.destroy()
289         .then(function() {
290           return res.sendStatus(204);
291         })
292         .catch(function(err) {
293           next(err);
294         });
295     })
296     .catch(function(err) {
297       next(err);
298     });
299 };
300
301 exports.addApplications = function(req, res, next) {
302
303   FaxApplication
304     .findAll({
305       where: {
306         id: req.body.applications
307       }
308     })
309     .then(function(faxApplications) {
310       var tmpFaxApplications = faxApplications;
311
312       return sequelize.transaction(function(t) {
313         return FaxApplication.destroy({
314           where: {
315             id: req.body.applications
316           }
317         }, {
318           transaction: t
319         }).then(function() {
320
321           var sortedApplications = [];
322
323           for (var i = 0; i < req.body.applications.length; i++) {
324
325             var tmpFaxApplication = _.find(tmpFaxApplications, {
326               'id': req.body.applications[i]
327             });
328
329             if (tmpFaxApplication) {
330               tmpFaxApplication.priority = i + 1;
331               sortedApplications.push(tmpFaxApplication.dataValues);
332             }
333           }
334
335           return FaxApplication.bulkCreate(sortedApplications, {
336             transaction: t
337           }).then(function(data) {
338             return data;
339           });
340         });
341       }).then(function(result) {
342         return res.status(200).send(result);
343         // Transaction has been committed
344         // result is whatever the result of the promise chain returned to the transaction callback
345       }).catch(function(err) {
346         return handleError(res, err);
347         // Transaction has been rolled back
348         // err is whatever rejected the promise chain returned to the transaction callback
349       });
350     })
351     .catch(function(err) {
352       return next(err);
353     });
354 };
355
356 exports.bulkDestroy = function(req, res) {
357   FaxAccount
358     .destroy({
359       where: {
360         id: req.query.id
361       },
362       individualHooks: true
363     })
364     .then(function() {
365       return res.sendStatus(204);
366     })
367     .catch(function(err) {
368       return handleError(res, err);
369     });
370 };
371
372 function handleError(res, err) {
373   return res.status(500).send(err);
374 }