/
ticket.js
1713 lines (1457 loc) · 47.5 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.
*/
const async = require('async')
const mongoose = require('mongoose')
const winston = require('../logger')
const _ = require('lodash')
const moment = require('moment')
const sanitizeHtml = require('sanitize-html')
// const redisCache = require('../cache/rediscache');
const xss = require('xss')
const utils = require('../helpers/utils')
// Needed - For Population
const groupSchema = require('./group')
const userSchema = require('./user')
const commentSchema = require('./comment')
const noteSchema = require('./note')
const attachmentSchema = require('./attachment')
const historySchema = require('./history')
const statusSchema = require('./ticketStatus')
require('./tag')
require('./ticketpriority')
require('./tickettype')
const 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.
*/
const 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: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'statuses',
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 })
const autoPopulate = function (next) {
this.populate('priority')
return next()
}
ticketSchema.pre('findOne', autoPopulate).pre('find', autoPopulate)
ticketSchema.pre('save', function (next) {
this.subject = utils.sanitizeFieldPlainText(this.subject.trim())
this.wasNew = this.isNew
if (!_.isUndefined(this.uid) || this.uid) {
return next()
}
const c = require('./counters')
const self = this
c.increment('tickets', function (err, res) {
if (err) return next(err)
self.uid = res.value.next
if (_.isUndefined(self.uid)) {
const error = new Error('Invalid UID.')
return next(error)
}
return next()
})
})
ticketSchema.post('save', async function (doc, next) {
if (!this.wasNew) {
const emitter = require('../emitter')
try {
const savedTicket = await doc.populate([
{
path: 'owner assignee comments.owner notes.owner subscribers history.owner',
select: '_id username fullname email role image title'
},
{ path: 'type tags' },
{
path: 'group',
model: groupSchema,
populate: [
{
path: 'members',
model: userSchema,
select: '-__v -accessToken -tOTPKey'
},
{
path: 'sendMailTo',
model: userSchema,
select: '-__v -accessToken -tOTPKey'
}
]
}
])
emitter.emit('ticket:updated', savedTicket)
} catch (err) {
winston.warn('WARNING: ' + err)
}
return next()
} else {
return next()
}
})
ticketSchema.virtual('statusFormatted').get(function (callback) {
const s = this.status
const ticketStatus = require('./ticketStatus')
ticketStatus.findOne({ uid: s }, function (err, status) {
if (err) return callback(err)
if (!status) return callback('Invalid Status Id: ' + typeId)
if (typeof callback === 'function') return callback(null, status.get('name'))
})
})
ticketSchema.virtual('commentsAndNotes').get(function () {
_.each(this.comments, function (i) {
i.isComment = true
})
_.each(this.notes, function (i) {
i.isNote = true
})
let 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 {string} status Status to set
* @param {function} callback Callback with the updated ticket.
*
* @example
* Status:
* 0 - New
* 1 - Open
* 2 - Pending
* 3 - Closed
*/
ticketSchema.methods.setStatus = function (ownerId, status, callback) {
const self = this
return new Promise((resolve, reject) => {
if (_.isUndefined(status)) {
if (typeof callback === 'function') callback('Invalid Status', null)
return reject(new Error('Invalid Status'))
}
const statusSchema = require('./ticketStatus')
statusSchema.getStatusById(status, function (err, statusModel) {
if (err) {
if (typeof callback === 'function') return callback(err)
return reject(new Error('Invalid Status'))
}
if (!status) {
if (typeof callback === 'function') return callback('Invalid Status')
return reject(new Error('Invalid Status'))
}
self.closedDate = statusModel.isResolved ? new Date() : null
self.status = status
const historyItem = {
action: 'ticket:set:status:' + statusModel.name,
description: 'Ticket Status set to: ' + statusModel.name,
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(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 {function} callback Callback with the updated ticket.
*/
ticketSchema.methods.setAssignee = function (ownerId, userId, callback) {
if (_.isUndefined(userId)) return callback('Invalid User Id', null)
const permissions = require('../permissions')
const 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)
}
const 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 {function} callback Callback with the updated ticket.
*/
ticketSchema.methods.clearAssignee = function (ownerId, callback) {
const self = this
return new Promise(resolve => {
self.assignee = undefined
const historyItem = {
action: 'ticket:set:assignee',
description: 'Assignee was cleared',
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(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 {function} callback Callback with the updated ticket.
*/
ticketSchema.methods.setTicketType = function (ownerId, typeId, callback) {
const typeSchema = require('./tickettype')
const 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)
const 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 {function} 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)
const self = this
self.priority = priority._id
const historyItem = {
action: 'ticket:set:priority',
description: 'Ticket Priority set to: ' + priority.name,
owner: ownerId
}
self.history.push(historyItem)
self
.populate(['priority'])
.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 {function} callback Callback with the updated ticket.
*/
ticketSchema.methods.setTicketGroup = function (ownerId, groupId, callback) {
const self = this
self.group = groupId
self.populate('group', function (err, ticket) {
if (err) return callback(err)
const 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) {
const self = this
self.dueDate = dueDate
const 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 {function} 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) {
const marked = require('marked')
const self = this
return new Promise(resolve => {
issue = issue.replace(/(\r\n|\n\r|\r|\n)/g, '<br>')
issue = sanitizeHtml(issue).trim()
self.issue = xss(marked.parse(issue))
const historyItem = {
action: 'ticket:update:issue',
description: 'Ticket Issue was updated.',
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(self)
})
}
ticketSchema.methods.setSubject = function (ownerId, subject, callback) {
const self = this
return new Promise(resolve => {
self.subject = subject
const historyItem = {
action: 'ticket:update:subject',
description: 'Ticket Subject was updated.',
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(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 {function} 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) {
const self = this
return new Promise((resolve, reject) => {
const comment = _.find(self.comments, function (c) {
return c._id.toString() === commentId.toString()
})
if (_.isUndefined(comment)) {
if (typeof callback === 'function') callback('Invalid Comment', null)
return reject(new Error('Invalid Comment'))
}
comment.comment = commentText
const historyItem = {
action: 'ticket:comment:updated',
description: 'Comment was updated: ' + commentId,
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(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 {function} callback Callback with the updated ticket.
*/
ticketSchema.methods.removeComment = function (ownerId, commentId, callback) {
const self = this
return new Promise(resolve => {
self.comments = _.reject(self.comments, function (o) {
return o._id.toString() === commentId.toString()
})
const historyItem = {
action: 'ticket:delete:comment',
description: 'Comment was deleted: ' + commentId,
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(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 {function} 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) {
const self = this
return new Promise((resolve, reject) => {
const note = _.find(self.notes, function (c) {
return c._id.toString() === noteId.toString()
})
if (_.isUndefined(note)) {
if (typeof callback === 'function') callback('Invalid Note', null)
return reject(new Error('Invalid Note'))
}
note.note = noteText
const historyItem = {
action: 'ticket:note:updated',
description: 'Note was updated: ' + noteId,
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(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 {function} callback Callback with the updated ticket.
*/
ticketSchema.methods.removeNote = function (ownerId, noteId, callback) {
const self = this
return new Promise(resolve => {
self.notes = _.reject(self.notes, function (o) {
return o._id.toString() === noteId.toString()
})
const historyItem = {
action: 'ticket:delete:note',
description: 'Note was deleted: ' + noteId,
owner: ownerId
}
self.history.push(historyItem)
if (typeof callback === 'function') callback(null, self)
return resolve(self)
})
}
ticketSchema.methods.getAttachment = function (attachmentId, callback) {
const self = this
const attachment = _.find(self.attachments, function (o) {
return o._id.toString() === attachmentId.toString()
})
return callback(attachment)
}
ticketSchema.methods.removeAttachment = function (ownerId, attachmentId, callback) {
const self = this
const 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)
}
const 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) {
const self = this
const 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) {
const self = this
const 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 {function} callback MongoDB Query Callback
*
* @example
* ticketSchema.getAll(function(err, tickets) {
* if (err) throw err;
*
* //tickets is an array
* });
*/
ticketSchema.statics.getAll = function (callback) {
const self = this
const q = self
.model(COLLECTION)
.find({ deleted: false })
.populate('owner assignee', '-password -__v -preferences -iOSDeviceTokens -tOTPKey')
.populate('type tags status group')
.sort({ status: 1 })
.lean()
return q.exec(callback)
}
ticketSchema.statics.getForCache = function (callback) {
const self = this
return new Promise((resolve, reject) => {
;(async () => {
try {
const t365 = moment
.utc()
.hour(23)
.minute(59)
.second(50)
.subtract(365, 'd')
.toDate()
const query = self
.model(COLLECTION)
.find({ date: { $gte: t365 }, deleted: false })
.sort('date')
.lean()
if (typeof callback === 'function') return query.exec(callback)
const results = await query.exec()
return resolve(results)
} catch (err) {
if (typeof callback === 'function') return callback(err)
return reject(err)
}
})()
})
}
ticketSchema.statics.getAllNoPopulate = function (callback) {
const self = this
const q = self
.model(COLLECTION)
.find({ deleted: false })
.sort({ status: 1 })
.lean()
return q.exec(callback)
}
ticketSchema.statics.getAllByStatus = function (status, callback) {
const self = this
if (!_.isArray(status)) {
status = [status]
}
const 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 status 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 {function} 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)
}
const self = this
const 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 status group')
.sort({ status: 1 })
return q.exec(callback)
}
/**
* Gets Tickets with a given departments and a JSON Object <br/><br/>
* *Sorts on UID desc.*
* @memberof Ticket
* @static
* @method getTicketsByDepartments
*
* @param {Object} departments Departments to retrieve tickets for.
* @param {Object} object JSON Object with query options
* @param {function} 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()')
const 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 {
const groups = _.flattenDeep(
departments.map(function (d) {
return d.groups.map(function (g) {
return g._id
})
})
)
return self.getTicketsWithObject(groups, object, callback)
}
}
function buildQueryWithObject (SELF, grpId, object, count) {
const limit = object.limit || 10
const page = object.page || 0
let _status = object.status
// Check up on status formatting
if (_.isArray(_status)) {
// This is a hack - querystring adds status in the array as [ "1,2,3" ]
// This will convert the array to [ "1", "2", "3" ]
_status = _.join(_status, ',').split(',')
}
if (object.filter && object.filter.groups)
grpId = _.intersection(
object.filter.groups,
_.map(grpId, g => g._id.toString())
)
let query
if (count) query = SELF.model(COLLECTION).countDocuments({ groups: { $in: grpId }, deleted: false })
else {
query = 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 status group')
.sort({ uid: -1 })
}
// Query with Limit?
if (limit !== -1) query.skip(page * limit).limit(limit)
// Status Query
if (_.isArray(_status) && _status.length > 0) {
query.where({ status: { $in: _status } })
}
// Filter Query
if (object.filter) {
// Filter on UID
if (object.filter.uid) {
object.filter.uid = parseInt(object.filter.uid)
if (!_.isNaN(object.filter.uid)) query.or([{ uid: object.filter.uid }])
}
// Priority Filter
if (object.filter.priority) query.where({ priority: { $in: object.filter.priority } })
// Ticket Type Filter
if (object.filter.types) query.where({ type: { $in: object.filter.types } })
// Tags Filter
if (object.filter.tags) query.where({ tags: { $in: object.filter.tags } })
// Assignee Filter
if (object.filter.assignee) query.where({ assignee: { $in: object.filter.assignee } })
// Unassigned Filter
if (object.filter.unassigned) query.where({ assignee: { $exists: false } })
// Owner Filter
if (object.filter.owner) query.where({ owner: { $in: object.filter.owner } })
// Subject Filter
if (object.filter.subject) query.or([{ subject: new RegExp(object.filter.subject, 'i') }])
// Issue Filter
if (object.filter.issue) query.or([{ issue: new RegExp(object.filter.issue, 'i') }])
// Date Filter
if (object.filter.date) {
let startDate = new Date(2000, 0, 1, 0, 0, 1)
let endDate = new Date()
if (object.filter.date.start) startDate = new Date(object.filter.date.start)
if (object.filter.date.end) endDate = new Date(object.filter.date.end)
query.where({ date: { $gte: startDate, $lte: endDate } })
}
}
if (object.owner) query.where('owner', object.owner)
if (object.assignedSelf) query.where('assignee', object.user)
if (object.unassigned) query.where({ assignee: { $exists: false } })
return query
}
ticketSchema.statics.getTicketsWithObject = async function (grpId, object, callback) {
const self = this
return new Promise((resolve, reject) => {
;(async () => {
try {
if (!grpId || !_.isArray(grpId) || !_.isObject(object))
throw new Error('Invalid parameter in - TicketSchema.GetTicketsWithObject()')
const query = buildQueryWithObject(self, grpId, object)
if (typeof callback === 'function') return query.exec(callback)
const resTickets = await query.exec()
return resolve(resTickets)
} catch (e) {
if (typeof callback === 'function') return callback(e)
return reject(e)
}
})()
})
}
ticketSchema.statics.getCountWithObject = async function (grpId, object, callback) {
const self = this
return new Promise((resolve, reject) => {
;(async () => {
try {