Built motion from commit 4143fce.|0.0.15
[motion.git] / server / api / freshdesk_account / freshdesk_account.controller.js
1 /**
2  * Using Rails-like standard naming convention for endpoints.
3  * GET     /api/freshdesk/accounts              ->  index
4  * POST    /api/freshdesk/accounts              ->  create
5  * GET     /api/freshdesk/accounts/:id          ->  show
6  * PUT     /api/freshdesk/accounts/:id          ->  update
7  * DELETE  /api/freshdesk/accounts/:id          ->  destroy
8  */
9
10 'use strict';
11
12
13 var _ = require('lodash');
14 var util = require('util');
15 var _fd = require('freshdesk');
16
17 var FreshdeskAccount = require('../../models').FreshdeskAccount;
18
19
20 function handleError(res, statusCode) {
21   statusCode = statusCode || 500;
22   return function(err) {
23     res.status(statusCode).send(err);
24   };
25 }
26
27 function responseWithResult(res, statusCode) {
28   statusCode = statusCode || 200;
29   return function(entity) {
30     if (entity) {
31       res.status(statusCode).json(entity);
32     }
33   };
34 }
35
36 function handleEntityNotFound(res) {
37   return function(entity) {
38     if (!entity) {
39       res.status(404).end();
40       return null;
41     }
42     return entity;
43   };
44 }
45
46 function saveUpdates(updates) {
47   return function(entity) {
48     return entity.updateAttributes(updates)
49       .then(function(updated) {
50         return updated;
51       });
52   };
53 }
54
55 function removeEntity(res) {
56   return function(entity) {
57     if (entity) {
58       return entity.destroy()
59         .then(function() {
60           res.status(204).end();
61         });
62     }
63   };
64 }
65
66 // Gets a list of FreshdeskAccounts
67 exports.index = function(req, res) {
68   var attributes = ['description', 'name', 'username', 'remoteUri'];
69   var per_page = req.query.per_page ? parseInt(req.query.per_page, 10) : 100;
70   var page = req.query.page ? parseInt(req.query.page, 10) : 0;
71
72   var query = {
73     where: {},
74     limit: per_page,
75     offset: page * per_page
76   };
77
78   _.forIn(req.query, function(value, key) {
79     switch (key) {
80       case 'per_page':
81       case 'page':
82         break;
83       case 'sort_by':
84         query.order = util.format('%s %s', req.query.sort_by, req.query.sort_order || 'ASC') || null;
85         break;
86       case 'sort_order':
87         break;
88       case '$':
89         query.where.$or = [];
90         attributes.forEach(function(attribute) {
91           var tmp = {};
92           tmp[attribute] = {
93             $like: '%' + value + '%'
94           };
95
96           query.where.$or.push(tmp);
97         });
98         break;
99       default:
100         query.where[key] = {
101           $like: {}
102         };
103         query.where[key].$like = '%' + value + '%';
104     }
105   });
106
107   FreshdeskAccount
108     .findAndCountAll(query)
109     .then(function(result) {
110
111       var total_pages = Math.ceil(result.count / per_page);
112       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;
113       var previous_page = page > 0 ? util.format('%s://%s%s?page=%d', req.protocol, req.headers.host, req.baseUrl, page - 1) : null;
114
115       return res.status(200).send({
116         count: result.count,
117         rows: result.rows,
118         next_page: next_page,
119         previous_page: previous_page,
120         total_pages: total_pages
121       });
122
123     })
124     .catch(function(err) {
125       return res.status(500).send({
126         error: 'Something blew up!'
127       });
128     });
129 }
130
131 // Gets a single FreshdeskAccount from the DB
132 exports.show = function(req, res) {
133   FreshdeskAccount.findById(req.params.id)
134     .then(handleEntityNotFound(res))
135     .then(responseWithResult(res))
136     .catch(handleError(res));
137 }
138
139 // Creates a new FreshdeskAccount in the DB
140 exports.create = function(req, res) {
141   FreshdeskAccount.create(req.body)
142     .then(responseWithResult(res, 201))
143     .catch(handleError(res));
144 }
145
146 // Updates an existing FreshdeskAccount in the DB
147 exports.update = function(req, res) {
148   if (req.body.id) {
149     delete req.body.id;
150   }
151   FreshdeskAccount.findById(req.params.id)
152     .then(handleEntityNotFound(res))
153     .then(saveUpdates(req.body))
154     .then(responseWithResult(res))
155     .catch(handleError(res));
156 }
157
158 // Deletes a FreshdeskAccount from the DB
159 exports.destroy = function(req, res) {
160   FreshdeskAccount.findById(req.params.id)
161     .then(handleEntityNotFound(res))
162     .then(removeEntity(res))
163     .catch(handleError(res));
164 }
165
166 exports.bulkDestroy = function(req, res) {
167   FreshdeskAccount
168     .destroy({
169       where: {
170         id: req.query.id
171       },
172       individualHooks: true
173     })
174     .then(function() {
175       return res.sendStatus(204);
176     })
177     .catch(function(err) {
178       return handleError(res, err);
179     });
180 };
181
182 exports.checkAccount = function(req, res) {
183   FreshdeskAccount.findById(req.params.id)
184     .then(handleEntityNotFound(res))
185     .then(function(account) {
186       var freshdesk = new _fd(account.remoteUri, account.apiKey);
187       freshdesk.listTickets(function(err, response, body) {
188         if (err) {
189           return res.sendStatus(400);
190         }
191         body = JSON.parse(body);
192         if (body.require_login) {
193           return res.sendStatus(400);
194         }
195         return res.sendStatus(200);
196       })
197     })
198     .catch(handleError(res));
199 }
200
201 exports.accountValidation = function(req, res) {
202   var where = {};
203   where[req.params.field] = req.body.value;
204   FreshdeskAccount
205     .findAndCountAll({
206       where: where
207     })
208     .then(function(result) {
209       if (result.count) {
210         return res.status(200).send({
211           isValid: false,
212           value: req.body.value
213         });
214       }
215       return res.status(200).send({
216         isValid: true,
217         value: req.body.value
218       });
219     })
220     .catch(function(err) {
221       return handleError(res, err);
222     });
223 };
224
225 exports.getFields = function(req, res, next) {
226   FreshdeskAccount.findById(req.params.id)
227     .then(handleEntityNotFound(res))
228     .then(function(account) {
229       var Freshdesk = new _fd(account.remoteUri, account.apiKey);
230       Freshdesk.get('/ticket_fields.json', function(err, response, body) {
231         if (err) {
232           return next(err);
233         }
234         body = JSON.parse(body);
235         return res.status(200).send(body);
236       });
237     })
238     .catch(handleError(res));
239 };