Built motion from commit 5e31ea4.|0.0.32
[motion.git] / server / api / telephone / telephone.controller.js
1 /**
2  * Using Rails-like standard naming convention for endpoints.
3  * GET     /api/telephones              ->  index
4  * POST    /api/telephones              ->  create
5  * GET     /api/telephones/:id          ->  show
6  * PUT     /api/telephones/:id          ->  update
7  * DELETE  /api/telephones/:id          ->  destroy
8  */
9
10 'use strict';
11
12 var util = require('util');
13 var _ = require('lodash');
14
15 var Telephone = require('../../models').User;
16
17 function handleError(res, statusCode) {
18   statusCode = statusCode || 500;
19   return function (err) {
20     res.status(statusCode).send(err);
21   };
22 }
23
24 function responseWithResult(res, statusCode) {
25   statusCode = statusCode || 200;
26   return function (entity) {
27     if (entity) {
28       res.status(statusCode).json(entity);
29     }
30   };
31 }
32
33 function handleEntityNotFound(res) {
34   return function (entity) {
35     if (!entity) {
36       res.status(404).end();
37       return null;
38     }
39     return entity;
40   };
41 }
42
43 function saveUpdates(updates) {
44   return function (entity) {
45     return entity.updateAttributes(updates)
46       .then(function (updated) {
47         return updated;
48       });
49   };
50 }
51
52 function removeEntity(res) {
53   return function (entity) {
54     if (entity) {
55       return entity.destroy()
56         .then(function () {
57           res.status(204).end();
58         });
59     }
60   };
61 }
62
63 // Gets a list of Telephones
64 exports.index = function (req, res) {
65   // Telephone.findAll()
66   //   .then(responseWithResult(res))
67   //   .catch(handleError(res));
68   var attributes = ['fullname', 'name'];
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       role: 'telephone'
75     },
76     limit: per_page,
77     offset: page * per_page
78   };
79
80   _.forIn(req.query, function (value, key) {
81     switch (key) {
82     case 'per_page':
83     case 'page':
84       break;
85     case 'sort_by':
86       query.order = util.format('%s %s', req.query.sort_by, req.query.sort_order || 'ASC') || null;
87       break;
88     case 'sort_order':
89       break;
90     case '$':
91       query.where.$or = [];
92       attributes.forEach(function (attribute) {
93         var tmp = {};
94         tmp[attribute] = {
95           $like: '%' + value + '%'
96         };
97
98         query.where.$or.push(tmp);
99       });
100       break;
101     default:
102       query.where[key] = {
103         $like: {}
104       };
105       query.where[key].$like = '%' + value + '%';
106     }
107   });
108
109   Telephone
110     .findAndCountAll(query)
111     .then(function (result) {
112
113       var total_pages = Math.ceil(result.count / per_page);
114       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;
115       var previous_page = page > 0 ? util.format('%s://%s%s?page=%d', req.protocol, req.headers.host, req.baseUrl, page - 1) : null;
116
117       return res.status(200).send({
118         count: result.count,
119         rows: result.rows,
120         next_page: next_page,
121         previous_page: previous_page,
122         total_pages: total_pages
123       });
124
125     })
126     .catch(function (err) {
127       return res.status(500).send({
128         error: 'Something blew up!'
129       });
130     });
131
132 }
133
134 // Gets a single Telephone from the DB
135 exports.show = function (req, res) {
136   console.log('req.params', req.params);
137   Telephone.findById(req.params.id)
138     .then(handleEntityNotFound(res))
139     .then(responseWithResult(res))
140     .catch(handleError(res));
141 }
142
143 // Get list of settings
144 exports.getInternal = function (req, res) {
145
146   var _tinternal;
147
148   return Telephone
149     .max('internal')
150     .then(function (tinternal) {
151       _tinternal = tinternal ? tinternal : 0;
152
153       res.status(200).send({
154         internal: _tinternal + 1
155       });
156     })
157     .catch(function (err) {
158       return handleError(res, err);
159     });
160 };
161
162 // Validate the existence of an internal number
163 exports.getInternalValidation = function (req, res) {
164   console.log('req.params', req.params);
165   return Telephone
166     .findAll({
167       where: {
168         internal: req.body.internal
169       }
170     })
171     .then(function (internals) {
172       if (!internals) {
173         return res.sendStatus(404);
174       }
175       return res.send(internals);
176     })
177     .catch(function (err) {
178       return handleError(res, err);
179     });
180 };
181
182 // Creates a new Telephone in the DB
183 exports.create = function (req, res) {
184   req.body.role = 'telephone';
185   Telephone.create(req.body)
186     .then(responseWithResult(res, 201))
187     .catch(handleError(res));
188 }
189
190 // Updates an existing Telephone in the DB
191 exports.update = function (req, res) {
192   if (req.body.id) {
193     delete req.body.id;
194   }
195   Telephone.findById(req.params.id)
196     .then(handleEntityNotFound(res))
197     .then(saveUpdates(req.body))
198     .then(responseWithResult(res))
199     .catch(handleError(res));
200 }
201
202 // Deletes a Telephone from the DB
203 exports.destroy = function (req, res) {
204   Telephone.findById(req.params.id)
205     .then(handleEntityNotFound(res))
206     .then(removeEntity(res))
207     .catch(handleError(res));
208 }