/
ticket.js
1666 lines (1430 loc) · 45.3 KB
/
ticket.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* . .o8 oooo
* .o8 "888 `888
* .o888oo oooo d8b oooo oooo .oooo888 .ooooo. .oooo.o 888 oooo
* 888 `888""8P `888 `888 d88' `888 d88' `88b d88( "8 888 .8P'
* 888 888 888 888 888 888 888ooo888 `"Y88b. 888888.
* 888 . 888 888 888 888 888 888 .o o. )88b 888 `88b.
* "888" d888b `V88V"V8P' `Y8bod88P" `Y8bod8P' 8""888P' o888o o888o
* ========================================================================
* Author: Chris Brame
* Updated: 1/20/19 4:43 PM
* Copyright (c) 2014-2019. All rights reserved.
*/
var async = require('async')
var mongoose = require('mongoose')
var winston = require('winston')
var _ = require('lodash')
var moment = require('moment')
var sanitizeHtml = require('sanitize-html')
// var redisCache = require('../cache/rediscache');
var xss = require('xss')
// Needed - For Population
var groupSchema = require('./group')
require('./tickettype')
var userSchema = require('./user')
var commentSchema = require('./comment')
var noteSchema = require('./note')
var attachmentSchema = require('./attachment')
var historySchema = require('./history')
require('./tag')
require('./ticketpriority')
var COLLECTION = 'tickets'
/**
* Ticket Schema
* @module models/ticket
* @class Ticket
* @requires {@link Group}
* @requires {@link TicketType}
* @requires {@link User}
* @requires {@link Comment}
* @requires {@link Attachment}
* @requires {@link History}
*
* @property {object} _id ```Required``` ```unique``` MongoDB Object ID
* @property {Number} uid ```Required``` ```unique``` Readable Ticket ID
* @property {User} owner ```Required``` Reference to User Object. Owner of this Object.
* @property {Group} group ```Required``` Group this Ticket is under.
* @property {User} assignee User currently assigned to this Ticket.
* @property {Date} date ```Required``` [default: Date.now] Date Ticket was created.
* @property {Date} updated Date ticket was last updated
* @property {Boolean} deleted ```Required``` [default: false] If they ticket is flagged as deleted.
* @property {TicketType} type ```Required``` Reference to the TicketType
* @property {Number} status ```Required``` [default: 0] Ticket Status. (See {@link Ticket#setStatus})
* @property {Number} priority ```Required```
* @property {Array} tags An array of Tags.
* @property {String} subject ```Required``` The subject of the ticket. (Overview)
* @property {String} issue ```Required``` Detailed information about the ticket problem/task
* @property {Date} closedDate show the datetime the ticket was moved to status 3.
* @property {Array} comments An array of {@link Comment} items
* @property {Array} notes An array of {@link Comment} items for internal notes
* @property {Array} attachments An Array of {@link Attachment} items
* @property {Array} history An array of {@link History} items
* @property {Array} subscribers An array of user _ids that receive notifications on ticket changes.
*/
var ticketSchema = mongoose.Schema({
uid: { type: Number, unique: true, index: true },
owner: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'accounts'
},
group: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'groups'
},
assignee: {
type: mongoose.Schema.Types.ObjectId,
ref: 'accounts'
},
date: { type: Date, default: Date.now, required: true, index: true },
updated: { type: Date },
deleted: { type: Boolean, default: false, required: true, index: true },
type: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'tickettypes'
},
status: { type: Number, default: 0, required: true, index: true },
priority: {
type: mongoose.Schema.Types.ObjectId,
ref: 'priorities',
required: true
},
tags: [{ type: mongoose.Schema.Types.ObjectId, ref: 'tags', autopopulate: true }],
subject: { type: String, required: true },
issue: { type: String, required: true },
closedDate: { type: Date },
dueDate: { type: Date },
comments: [commentSchema],
notes: [noteSchema],
attachments: [attachmentSchema],
history: [historySchema],
subscribers: [{ type: mongoose.Schema.Types.ObjectId, ref: 'accounts' }]
})
ticketSchema.index({ deleted: -1, group: 1, status: 1 })
var autoPopulate = function (next) {
this.populate('priority')
return next()
}
ticketSchema.pre('findOne', autoPopulate).pre('find', autoPopulate)
ticketSchema.pre('save', function (next) {
this.subject = this.subject.trim()
this.wasNew = this.isNew
if (!_.isUndefined(this.uid) || this.uid) {
return next()
}
var c = require('./counters')
var self = this
c.increment('tickets', function (err, res) {
if (err) return next(err)
self.uid = res.value.next
if (_.isUndefined(self.uid)) {
var error = new Error('Invalid UID.')
return next(error)
}
return next()
})
})
ticketSchema.post('save', function (doc, next) {
if (!this.wasNew) {
var emitter = require('../emitter')
doc
.populate(
'owner assignee comments.owner notes.owner subscribers history.owner',
'_id username fullname email role image title'
)
.populate('type tags')
.populate({
path: 'group',
model: groupSchema,
populate: [
{
path: 'members',
model: userSchema,
select: '-__v -accessToken -tOTPKey'
},
{
path: 'sendMailTo',
model: userSchema,
select: '-__v -accessToken -tOTPKey'
}
]
})
.execPopulate(function (err, savedTicket) {
if (err) return winston.warn(err)
emitter.emit('ticket:updated', savedTicket)
return next()
})
} else {
return next()
}
})
ticketSchema.virtual('statusFormatted').get(function () {
var s = this.status
var formatted
switch (s) {
case 0:
formatted = 'New'
break
case 1:
formatted = 'Open'
break
case 2:
formatted = 'Pending'
break
case 3:
formatted = 'Closed'
break
default:
formatted = 'New'
}
return formatted
})
ticketSchema.virtual('commentsAndNotes').get(function () {
_.each(this.comments, function (i) {
i.isComment = true
})
_.each(this.notes, function (i) {
i.isNote = true
})
var combined = _.union(this.comments, this.notes)
combined = _.sortBy(combined, 'date')
return combined
})
/**
* Set Status on Instanced Ticket
* @instance
* @method setStatus
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Number} status Status to set
* @param {TicketCallback} callback Callback with the updated ticket.
*
* @example
* Status:
* 0 - New
* 1 - Open
* 2 - Pending
* 3 - Closed
*/
ticketSchema.methods.setStatus = function (ownerId, status, callback) {
if (_.isUndefined(status)) return callback('Invalid Status', null)
var self = this
if (status === 3) {
self.closedDate = new Date()
} else {
self.closedDate = null
}
self.status = status
var historyItem = {
action: 'ticket:set:status:' + status,
description: 'Ticket Status set to: ' + statusToString(status),
owner: ownerId
}
self.history.push(historyItem)
callback(null, self)
}
/**
* Set Assignee on Instanced Ticket
* @instance
* @method setAssignee
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} userId User ID to set as assignee
* @param {TicketCallback} callback Callback with the updated ticket.
*/
ticketSchema.methods.setAssignee = function (ownerId, userId, callback) {
if (_.isUndefined(userId)) return callback('Invalid User Id', null)
var permissions = require('../permissions')
var self = this
self.assignee = userId
userSchema.getUser(userId, function (err, user) {
if (err) return callback(err, null)
if (!permissions.canThis(user.role, 'tickets:update') && !permissions.canThis(user.role, 'agent:*')) {
return callback('User does not have permission to be set as an assignee.', null)
}
var historyItem = {
action: 'ticket:set:assignee',
description: user.fullname + ' was set as assignee',
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
})
}
/**
* Clear the current assignee
* @instance
* @method clearAssignee
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {TicketCallback} callback Callback with the updated ticket.
*/
ticketSchema.methods.clearAssignee = function (ownerId, callback) {
var self = this
self.assignee = undefined
var historyItem = {
action: 'ticket:set:assignee',
description: 'Assignee was cleared',
owner: ownerId
}
self.history.push(historyItem)
callback(null, self)
}
/**
* Sets the ticket type for the instanced Ticket
* @instance
* @method setTicketType
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} typeId TicketType Id to set as ticket type
* @param {TicketCallback} callback Callback with the updated ticket.
*/
ticketSchema.methods.setTicketType = function (ownerId, typeId, callback) {
var typeSchema = require('./tickettype')
var self = this
self.type = typeId
typeSchema.findOne({ _id: typeId }, function (err, type) {
if (err) return callback(err)
if (!type) return callback('Invalid Type Id: ' + typeId)
var historyItem = {
action: 'ticket:set:type',
description: 'Ticket type set to: ' + type.name,
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') return callback(null, self)
})
}
/**
* Sets the ticket priority
* @instance
* @method setTicketPriority
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Number} priority Priority to set
* @param {TicketCallback} callback Callback with the updated ticket.
*/
ticketSchema.methods.setTicketPriority = function (ownerId, priority, callback) {
if (_.isUndefined(priority) || !_.isObject(priority)) return callback('Priority must be a PriorityObject.', null)
var self = this
self.priority = priority._id
var historyItem = {
action: 'ticket:set:priority',
description: 'Ticket Priority set to: ' + priority.name,
owner: ownerId
}
self.history.push(historyItem)
self
.populate('priority')
.execPopulate()
.then(function (updatedSelf) {
return callback(null, updatedSelf)
})
.catch(function (err) {
return callback(err, null)
})
}
/**
* Sets this ticket under the given group Id
* @instance
* @method setTicketGroup
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} groupId MongoDB group Id to assign this ticket to
* @param {TicketCallback} callback Callback with the updated ticket.
*/
ticketSchema.methods.setTicketGroup = function (ownerId, groupId, callback) {
var self = this
self.group = groupId
self.populate('group', function (err, ticket) {
if (err) return callback(err)
var historyItem = {
action: 'ticket:set:group',
description: 'Ticket Group set to: ' + ticket.group.name,
owner: ownerId
}
self.history.push(historyItem)
return callback(null, ticket)
})
}
ticketSchema.methods.setTicketDueDate = function (ownerId, dueDate, callback) {
var self = this
self.dueDate = dueDate
var historyItem = {
action: 'ticket:set:duedate',
description: 'Ticket Due Date set to: ' + self.dueDate,
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
/**
* Sets this ticket's issue text
* @instance
* @method setIssue
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} issue Issue text to set on the ticket
* @param {TicketCallback} callback Callback with the updated ticket.
* @example
* ticket.setIssue({ownerId}, 'This is the new issue string.', function(err, t) {
* if (err) throw err;
*
* ticket.save(function(err, t) {
* if (err) throw err;
* });
* });
*/
ticketSchema.methods.setIssue = function (ownerId, issue, callback) {
var marked = require('marked')
var self = this
issue = issue.replace(/(\r\n|\n\r|\r|\n)/g, '<br>')
issue = sanitizeHtml(issue).trim()
self.issue = xss(marked(issue))
var historyItem = {
action: 'ticket:update:issue',
description: 'Ticket Issue was updated.',
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
ticketSchema.methods.setSubject = function (ownerId, subject, callback) {
var self = this
self.subject = subject
var historyItem = {
action: 'ticket:update:subject',
description: 'Ticket Subject was updated.',
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
/**
* Updates a given comment inside the comment array on this ticket
* @instance
* @method updateComment
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} commentId Comment ID to update
* @param {String} commentText Text to update the comment to
* @param {TicketCallback} callback Callback with the updated ticket.
* @example
* ticket.updateComment({ownerId}, {commentId} 'This is the new comment string.', function(err, t) {
* if (err) throw err;
*
* ticket.save(function(err, t) {
* if (err) throw err;
* });
* });
*/
ticketSchema.methods.updateComment = function (ownerId, commentId, commentText, callback) {
var self = this
var comment = _.find(self.comments, function (c) {
return c._id.toString() === commentId.toString()
})
if (_.isUndefined(comment)) return callback('Invalid Comment', null)
comment.comment = commentText
var historyItem = {
action: 'ticket:comment:updated',
description: 'Comment was updated: ' + commentId,
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
/**
* Removes a comment from the comment array on this ticket.
* @instance
* @method removeComment
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} commentId Comment ID to remove
* @param {TicketCallback} callback Callback with the updated ticket.
*/
ticketSchema.methods.removeComment = function (ownerId, commentId, callback) {
var self = this
self.comments = _.reject(self.comments, function (o) {
return o._id.toString() === commentId.toString()
})
var historyItem = {
action: 'ticket:delete:comment',
description: 'Comment was deleted: ' + commentId,
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
/**
* Updates a given Note inside the note array on this ticket
* @instance
* @method updateNote
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} noteId Note ID to update
* @param {String} noteText Text to update the note to
* @param {TicketCallback} callback Callback with the updated ticket.
* @example
* ticket.updateNote({ownerId}, {noteId} 'This is the new note string.', function(err, t) {
* if (err) throw err;
*
* ticket.save(function(err, t) {
* if (err) throw err;
* });
* });
*/
ticketSchema.methods.updateNote = function (ownerId, noteId, noteText, callback) {
var self = this
var note = _.find(self.notes, function (c) {
return c._id.toString() === noteId.toString()
})
if (_.isUndefined(note)) return callback('Invalid Note', null)
note.note = noteText
var historyItem = {
action: 'ticket:note:updated',
description: 'Note was updated: ' + noteId,
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
/**
* Removes a note from the note array on this ticket.
* @instance
* @method removeNote
* @memberof Ticket
*
* @param {Object} ownerId Account ID preforming this action
* @param {Object} noteId Comment ID to remove
* @param {TicketCallback} callback Callback with the updated ticket.
*/
ticketSchema.methods.removeNote = function (ownerId, noteId, callback) {
var self = this
self.notes = _.reject(self.notes, function (o) {
return o._id.toString() === noteId.toString()
})
var historyItem = {
action: 'ticket:delete:note',
description: 'Note was deleted: ' + noteId,
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
ticketSchema.methods.getAttachment = function (attachmentId, callback) {
var self = this
var attachment = _.find(self.attachments, function (o) {
return o._id.toString() === attachmentId.toString()
})
return callback(attachment)
}
ticketSchema.methods.removeAttachment = function (ownerId, attachmentId, callback) {
var self = this
var attachment = _.find(self.attachments, function (o) {
return o._id.toString() === attachmentId.toString()
})
self.attachments = _.reject(self.attachments, function (o) {
return o._id.toString() === attachmentId.toString()
})
if (_.isUndefined(attachment)) {
return callback(null, self)
}
var historyItem = {
action: 'ticket:delete:attachment',
description: 'Attachment was deleted: ' + attachment.name,
owner: ownerId
}
self.history.push(historyItem)
return callback(null, self)
}
ticketSchema.methods.addSubscriber = function (userId, callback) {
var self = this
var hasSub = _.some(self.subscribers, function (i) {
return i._id.toString() === userId.toString()
})
if (!hasSub) {
self.subscribers.push(userId)
}
return callback(null, self)
}
ticketSchema.methods.removeSubscriber = function (userId, callback) {
var self = this
var user = _.find(self.subscribers, function (i) {
return i._id.toString() === userId.toString()
})
if (_.isUndefined(user) || _.isEmpty(user) || _.isNull(user)) return callback(null, self)
self.subscribers = _.reject(self.subscribers, function (i) {
return i._id.toString() === userId.toString()
})
return callback(null, self)
}
/**
* Gets all tickets that are not marked as deleted <br> <br>
*
* **Deep populates: group, group.members, group.sendMailTo, comments, comments.owner**
*
* @memberof Ticket
* @static
* @method getAll
* @param {QueryCallback} callback MongoDB Query Callback
*
* @example
* ticketSchema.getAll(function(err, tickets) {
* if (err) throw err;
*
* //tickets is an array
* });
*/
ticketSchema.statics.getAll = function (callback) {
var self = this
var q = self
.model(COLLECTION)
.find({ deleted: false })
.populate('owner assignee', '-password -__v -preferences -iOSDeviceTokens -tOTPKey')
.populate('type tags group')
.sort({ status: 1 })
.lean()
return q.exec(callback)
}
ticketSchema.statics.getForCache = function (callback) {
var self = this
var t365 = moment
.utc()
.hour(23)
.minute(59)
.second(59)
.subtract(365, 'd')
.toDate()
self
.model(COLLECTION)
.find({ date: { $gte: t365 }, deleted: false })
.select('_id uid date status history comments assignee owner tags')
.sort('date')
.lean()
.exec(callback)
}
ticketSchema.statics.getAllNoPopulate = function (callback) {
var self = this
var q = self
.model(COLLECTION)
.find({ deleted: false })
.sort({ status: 1 })
.lean()
return q.exec(callback)
}
ticketSchema.statics.getAllByStatus = function (status, callback) {
var self = this
if (!_.isArray(status)) {
status = [status]
}
var q = self
.model(COLLECTION)
.find({ status: { $in: status }, deleted: false })
.populate(
'owner assignee comments.owner notes.owner subscribers history.owner',
'username fullname email role image title'
)
.populate('type tags group')
.sort({ status: 1 })
.lean()
return q.exec(callback)
}
/**
* Gets Tickets with a given group id.
*
* @memberof Ticket
* @static
* @method getTickets
* @param {Array} grpIds Group Id to retrieve tickets for.
* @param {QueryCallback} callback MongoDB Query Callback
*/
ticketSchema.statics.getTickets = function (grpIds, callback) {
if (_.isUndefined(grpIds)) {
return callback('Invalid GroupId - TicketSchema.GetTickets()', null)
}
if (!_.isArray(grpIds)) {
return callback('Invalid GroupId (Must be of type Array) - TicketSchema.GetTickets()', null)
}
var self = this
var q = self
.model(COLLECTION)
.find({ group: { $in: grpIds }, deleted: false })
.populate(
'owner assignee comments.owner notes.owner subscribers history.owner',
'username fullname email role image title'
)
.populate('type tags group')
.sort({ status: 1 })
return q.exec(callback)
}
/**
* Gets Tickets with a given group id and a JSON Object <br/><br/>
* *Sorts on UID desc.*
* @memberof Ticket
* @static
* @method getTicketsWithObject
*
* @param {Object} grpId Group Id to retrieve tickets for.
* @param {Object} object JSON Object with various options
* @param {QueryCallback} callback MongoDB Query Callback
*
* @example
* //Object Options
* {
* limit: 10,
* page: 0,
* closed: false,
* status: 1
* }
*/
ticketSchema.statics.getTicketsByDepartments = function (departments, object, callback) {
if (!departments || !_.isObject(departments) || !object)
return callback('Invalid Data - TicketSchema.GetTicketsByDepartments()')
var self = this
if (_.some(departments, { allGroups: true })) {
groupSchema.find({}, function (err, groups) {
if (err) return callback({ error: err })
return self.getTicketsWithObject(groups, object, callback)
})
} else {
var groups = _.flattenDeep(
departments.map(function (d) {
return d.groups.map(function (g) {
return g._id
})
})
)
return self.getTicketsWithObject(groups, object, callback)
}
}
ticketSchema.statics.getTicketsWithObject = function (grpId, object, callback) {
if (_.isUndefined(grpId)) {
return callback('Invalid GroupId - TicketSchema.GetTickets()', null)
}
if (!_.isArray(grpId)) {
return callback('Invalid GroupId (Must be of type Array) - TicketSchema.GetTicketsWithObject()', null)
}
if (!_.isObject(object)) {
return callback('Invalid Object (Must be of type Object) - TicketSchema.GetTicketsWithObject()', null)
}
var self = this
var limit = !object.limit ? 10 : object.limit
var page = !object.page ? 0 : object.page
var _status = object.status
if (!_.isUndefined(object.filter) && !_.isUndefined(object.filter.groups)) {
var g = _.map(grpId, '_id').map(String)
grpId = _.intersection(object.filter.groups, g)
}
var q = self
.model(COLLECTION)
.find({ group: { $in: grpId }, deleted: false })
.populate(
'owner assignee subscribers comments.owner notes.owner history.owner',
'username fullname email role image title'
)
.populate('assignee', 'username fullname email role image title')
.populate('type tags group')
.sort({ uid: -1 })
if (limit !== -1) {
q.skip(page * limit).limit(limit)
}
if (_.isArray(_status) && _.size(_status) > 0) {
q.where({ status: { $in: _status } })
}
if (!_.isUndefined(object.filter)) {
if (!_.isUndefined(object.filter.uid)) {
object.filter.uid = parseInt(object.filter.uid)
if (!_.isNaN(object.filter.uid)) {
q.or([{ uid: object.filter.uid }])
}
}
if (!_.isUndefined(object.filter.priority)) {
q.where({ priority: { $in: object.filter.priority } })
}
if (!_.isUndefined(object.filter.types)) {
q.where({ type: { $in: object.filter.types } })
}
if (!_.isUndefined(object.filter.tags)) {
q.where({ tags: { $in: object.filter.tags } })
}
if (!_.isUndefined(object.filter.assignee)) {
q.where({ assignee: { $in: object.filter.assignee } })
}
if (!_.isUndefined(object.filter.unassigned)) {
q.where({ assignee: { $exists: false } })
}
if (!_.isUndefined(object.filter.owner)) {
q.where({ owner: { $in: object.filter.owner } })
}
if (!_.isUndefined(object.filter.subject)) {
q.or([{ subject: new RegExp(object.filter.subject, 'i') }])
}
if (!_.isUndefined(object.filter.issue)) {
q.or([{ issue: new RegExp(object.filter.issue, 'i') }])
}
if (!_.isUndefined(object.filter.date)) {
var startDate = new Date(2000, 0, 1, 0, 0, 1)
var endDate = new Date()
if (!_.isUndefined(object.filter.date.start)) {
startDate = new Date(object.filter.date.start)
}
if (!_.isUndefined(object.filter.date.end)) {
endDate = new Date(object.filter.date.end)
}
q.where({ date: { $gte: startDate, $lte: endDate } })
}
}
if (!_.isUndefined(object.assignedSelf) && !_.isNull(object.assignedSelf)) q.where('assignee', object.user)
if (!_.isUndefined(object.unassigned) && !_.isNull(object.unassigned)) q.where({ assignee: { $exists: false } })
return q.exec(callback)
}
ticketSchema.statics.getCountWithObject = function (grpId, object, callback) {
if (_.isUndefined(grpId)) {
return callback('Invalid GroupId - TicketSchema.GetCountWithObject()', null)
}
if (!_.isArray(grpId)) {
return callback('Invalid GroupId (Must be of type Array) - TicketSchema.GetCountWithObject()', null)
}
if (!_.isObject(object)) {
return callback('Invalid Object (Must be of type Object) - TicketSchema.GetCountWithObject()', null)
}
var self = this
if (!_.isUndefined(object.filter) && !_.isUndefined(object.filter.groups)) {
var g = _.map(grpId, '_id').map(String)
grpId = _.intersection(object.filter.groups, g)
}
var q = self.model(COLLECTION).countDocuments({ group: { $in: grpId }, deleted: false })
if (!_.isUndefined(object.status) && _.isArray(object.status)) {
var status = object.status.map(Number)
q.where({ status: { $in: status } })
}
if (!_.isUndefined(object.filter) && !_.isUndefined(object.filter.assignee)) {
q.where({ assignee: { $in: object.filter.assignee } })
}
if (!_.isUndefined(object.filter) && !_.isUndefined(object.filter.types)) {
q.where({ type: { $in: object.filter.types } })
}
if (!_.isUndefined(object.filter) && !_.isUndefined(object.filter.subject))
q.where({ subject: new RegExp(object.filter.subject, 'i') })
if (
!_.isUndefined(object.assignedSelf) &&
object.assignedSelf === true &&
!_.isUndefined(object.assignedUserId) &&
!_.isNull(object.assignedUserId)
) {
q.where('assignee', object.assignedUserId)
}
if (!_.isUndefined(object.unassigned) && object.unassigned === true) {
q.where({ assignee: { $exists: false } })
}
return q.lean().exec(callback)
}
/**
* Gets Tickets for status in given group. <br/><br/>
* *Sorts on UID desc*
* @memberof Ticket
* @static
* @method getTicketsByStatus
*
* @param {Object} grpId Group Id to retrieve tickets for.
* @param {Number} status Status number to check
* @param {QueryCallback} callback MongoDB Query Callback
*/
ticketSchema.statics.getTicketsByStatus = function (grpId, status, callback) {
if (_.isUndefined(grpId)) {
return callback('Invalid GroupId - TicketSchema.GetTickets()', null)
}
if (!_.isArray(grpId)) {
return callback('Invalid GroupId (Must be of type Array) - TicketSchema.GetTickets()', null)
}
var self = this
var q = self
.model(COLLECTION)
.find({ group: { $in: grpId }, status: status, deleted: false })
.populate(
'owner assignee comments.owner notes.owner subscribers history.owner',