-
Notifications
You must be signed in to change notification settings - Fork 16
/
departments.js
489 lines (399 loc) · 13.3 KB
/
departments.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
"use strict";
const { sorter } = require('../util');
const express = require('express'),
router = express.Router(),
validator = require('validator'),
Promise = require('bluebird'),
_ = require('underscore');
// Make sure that current user is authorized to deal with settings
router.all(/.*/, require('../middleware/ensure_user_is_admin'));
function generate_all_department_allowances() {
var allowance_options = [{ value : 0, caption : 'None'}],
allowance = 0.5;
while (allowance <= 50) {
allowance_options.push({ value : allowance, caption : allowance });
allowance += 0.5;
}
return allowance_options;
}
function get_and_validate_department(args) {
var req = args.req,
index = args.suffix,
company = args.company,
// If no_suffix is set then parameter names are considered without "indexes"
no_suffix = args.no_suffix,
department_name = args.department_name;
// Get user parameters
let
name = validator.trim(req.body[no_suffix ? 'name' : 'name__'+index]),
allowance = validator.trim(req.body[no_suffix ? 'allowance' : 'allowance__'+index]),
boss_id = validator.trim(req.body[no_suffix ? 'boss_id' : 'boss_id__'+index]),
include_public_holidays = validator.toBoolean(
req.body[no_suffix ? 'include_public_holidays' : 'include_public_holidays__'+index]
),
is_accrued_allowance = validator.toBoolean(
req.body[no_suffix ? 'is_accrued_allowance' : 'is_accrued_allowance__'+index]
);
// Validate provided parameters
//
// New allowance should be from range of (0;50]
if (!validator.isFloat(allowance)) {
req.session.flash_error(
'New allowance for '+department_name+' should be numeric'
);
} else if (!((0 <= allowance) && (allowance <= 50))) {
req.session.flash_error(
'New allowance for '+department_name+' should be between 0.5 and 50 days'
);
}
// New manager ID should be numeric and from within
// current company
if (!validator.isNumeric( boss_id ) ) {
req.session.flash_error(
'New boss reference for '+department_name+' should be numeric'
);
} else if ( ! _.contains(
_.map( company.users, function(user){ return String(user.id) }),
String(boss_id)
)) {
req.session.flash_error(
'New boss for '+department_name+' is unknown'
);
}
return {
allowance : allowance,
bossId : boss_id,
include_public_holidays : include_public_holidays,
is_accrued_allowance : is_accrued_allowance,
name : name,
};
}
router.get('/departments/', function(req, res){
// Add JS that is specific only to current page
res.locals.custom_java_script.push('/js/departments.js');
var company_for_template,
model = req.app.get('db_model');
req.user.getCompany({
scope : ['with_active_users', 'order_by_active_users'],
})
.then(function(company){
company_for_template = company;
return company.getDepartments({
scope : ['with_simple_users', 'with_boss'],
});
})
.then(function(departments){
res.render('departments_overview', {
title : 'Departments settings',
departments : departments.sort((a, b) => sorter(a.name, b.name)),
allowance_options : generate_all_department_allowances(),
company : company_for_template,
});
});
});
router.post('/departments/', function(req, res){
const
model = req.app.get('db_model');
req.user.getCompany({
scope : ['with_active_users'],
})
.then(company => {
let attributes = get_and_validate_department({
req : req,
suffix : 'new',
company : company,
department_name : 'New department'
});
if ( req.session.flash_has_errors() ) {
return Promise.resolve(1);
}
attributes.companyId = company.id;
return model.Department.create(attributes);
})
.then(() => {
if ( ! req.session.flash_has_errors() ) {
req.session.flash_message('Changes to departments were saved');
}
return res.redirect_with_session('/settings/departments/');
})
.catch(error => {
console.error(
'An error occurred when trying to add department by user '+req.user.id
+ ' : ' + error
);
req.session.flash_error(
'Failed to add new department, please contact customer service'
);
return res.redirect_with_session('/settings/departments/');
});
});
router.post('/departments/delete/:department_id/', function(req, res){
var department_id = req.params['department_id'],
department_to_remove;
if (!validator.isInt(department_id)) {
console.error(
'User '+req.user.id+' submited non-int department ID '+department_id
);
req.session.flash_error('Cannot remove department: wronge parameters');
return res.redirect_with_session('/settings/departments/');
}
req.user.getCompany()
.then(function(company){
return company.getDepartments({
scope : ['with_simple_users'],
where : {
id : department_id,
}
});
})
.then(function(departments){
department_to_remove = departments[ 0 ];
// Check if user specify valid department number
if (! department_to_remove) {
req.session.flash_error('Cannot remove department: wronge parameters');
throw new Error(
'User '+req.user.id+' tried to remove non-existing department ID'+department_id
);
}
if (department_to_remove.users.length > 0){
req.session.flash_error(
'Cannot remove department '+department_to_remove.name
+' as it still has '
+department_to_remove.users.length+' users.'
);
throw new Error('Department still has users');
}
// TODO VPP remove corresponding records in supervisors linking table
return department_to_remove.destroy();
})
.then(function(){
req.session.flash_message('Department was successfully removed');
return res.redirect_with_session('/settings/departments/');
})
.catch(function(error){
console.error(
'An error occurred when trying to edit departments by user '+req.user.id+' : '+error
);
return res.redirect_with_session( department_to_remove
? '/settings/departments/edit/'+department_to_remove.get('id')+'/'
: '/settings/departments/'
);
});
});
function promise_to_extract_company_and_department(req, only_active = true) {
var department_id = req.params['department_id'],
company;
return Promise.try(function(){
if ( ! validator.isInt(department_id)) {
throw new Error('User '+req.user.id+' tried to open department refered by non-int ID '+department_id);
}
if (only_active) {
return req.user.getCompany({
scope : ['with_active_users', 'order_by_active_users'],
});
} else {
return req.user.getCompany({
scope : ['with_all_users'],
});
}
})
.then(function(c){
company = c;
if ( ! company ) {
throw new Error('Cannot determin company!');
}
return company.getDepartments({
scope : ['with_simple_users', 'with_boss', 'with_supervisors'],
where : {
id : department_id,
}
});
})
.then(function(departments){
var department = departments[0];
// Ensure we have database record for given department ID
if ( ! department ) {
throw new Error('Non existing department ID provided');
}
return Promise.resolve({
company : company,
department : department,
});
});
}
router.get('/departments/edit/:department_id/', function(req, res){
var department_id = req.params['department_id'];
Promise.try(function(){
return promise_to_extract_company_and_department(req);
})
.then(function(result){
var department = result.department,
company = result.company;
res.render('department_details', {
title : 'Department details',
department : department,
company : company,
allowance_options : generate_all_department_allowances(),
});
})
.catch(function(error){
console.error(
'An error occurred when trying to edit department '+department_id
+' for user '+req.user.id + ' : ' + error
);
req.session.flash_error(
'Failed to fetch details for given department'
);
return res.redirect_with_session('/settings/departments/');
});
});
router.post('/departments/edit/:department_id/', function(req, res){
var department_id = req.params['department_id'],
company,
department;
// to remove supervisor we need to get all users, not only active ones
var only_active = !req.body.remove_supervisor_id
Promise.try(function(){
return promise_to_extract_company_and_department(req, only_active);
})
.then(function(result){
company = result.company;
department = result.department;
return Promise.resolve(1);
})
.then(function(){
if (req.body.remove_supervisor_id) {
return promise_to_remove_supervisor({
supervisor_id : req.body.remove_supervisor_id,
company : company,
department : department,
})
.then(function(){
req.session.flash_message('Supervisor was removed from ' + department.name);
return Promise.resolve(1);
});
} else if ( req.body.do_add_supervisors ) {
return promise_to_update_supervisors({
req : req,
company : company,
department : department,
})
.then(function(){
req.session.flash_message('Supervisors were added to department ' + department.name);
return Promise.resolve(1);
});
}
return promise_to_update_department({
req : req,
company : company,
department : department,
})
.then(function(){
req.session.flash_message('Department ' + department.name + ' was updated');
return Promise.resolve(1);
});
})
.then(function(){
return res.redirect_with_session('.');
})
.catch(function(error){
console.error(
'An error occurred when trying to update secondary superwisors for depertment '+department_id
+' by user '+req.user.id + ' : ' + error
);
req.session.flash_error(
"Failed to update department's details"
);
return res.redirect_with_session('../../');
});
});
function promise_to_remove_supervisor(args) {
var
supervisor_id = args.supervisor_id,
company = args.company,
department = args.department;
// Make sure that provided supervisor ID belongs to user from current company
if (company.users.map(function(u){return String(u.id)}).indexOf( String(supervisor_id) ) === -1){
return Promise.resolve(1);
}
return department.Model.sequelize.models.DepartmentSupervisor.destroy({
where : {
department_id : department.id,
user_id : supervisor_id,
},
});
}
function promise_to_update_supervisors(args) {
var
req = args.req,
company = args.company,
department = args.department;
var supervisor_ids = req.body.supervisor_id || [];
// Take list of all users as a base of intersaction,
// so we use submitted data only as criteria and do not save it in database
supervisor_ids = company.users
.map(function(user){ return user.id})
.filter(function(id){ return supervisor_ids.indexOf(String(id)) !== -1});
var link_model = department.Model.sequelize.models.DepartmentSupervisor;
return link_model.destroy({
where : {
department_id : department.id,
}
})
.then(function(){
return link_model.bulkCreate(
supervisor_ids.map(function(id){ return { user_id : id, department_id : department.id } })
);
});
}
function promise_to_update_department(args) {
var
req = args.req,
company = args.company,
department = args.department;
var attributes = get_and_validate_department({
company : company,
department_name : department.name,
no_suffix : true,
req : req,
});
// If there were any validation errors: do not update department
if ( req.session.flash_has_errors() ) {
throw new Error("Invalid parameters submitted while while attempt to update department details");
}
return department.updateAttributes(attributes);
}
router.get('/departments/available-supervisors/:department_id/', function(req, res){
var department_id = req.params['department_id'],
department,
company;
Promise.try(function(){
return promise_to_extract_company_and_department(req);
})
.then(function(result){
department = result.department;
company = result.company;
return department.promise_me_with_supervisors();
})
.then(function(department_with_supervisors){
var supervisor_map = {};
department_with_supervisors.supervisors.forEach(function(user){
supervisor_map[user.id] = true;
});
res.render('department/available_supervisors', {
layout : false,
users : _.map(
_.filter(company.users, function(user){ return user.id !== department.bossId }),
function(user){ user._marked = supervisor_map[user.id]; return user }
),
});
})
.catch(function(error){
console.error(
'An error occurred when trying to get all availabele superviers for department '+department_id
+' for user '+req.user.id + ' : ' + error
);
res.send('REQUEST FAILED');
});
});
module.exports = router;