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