-
Notifications
You must be signed in to change notification settings - Fork 633
/
models.py
2088 lines (1725 loc) · 62.2 KB
/
models.py
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
"""
django-helpdesk - A Django powered ticket tracker for small enterprise.
(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.
models.py - Model (and hence database) definitions. This is the core of the
helpdesk structure.
"""
from .lib import convert_value
from .templated_email import send_templated_mail
from .validators import validate_file_extension
from .webhooks import send_new_ticket_webhook
import datetime
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy as _
from helpdesk import settings as helpdesk_settings
from io import StringIO
from markdown import markdown
from markdown.extensions import Extension
import mimetypes
import os
import re
from rest_framework import serializers
import uuid
def format_time_spent(time_spent):
if time_spent:
time_spent = "{0:02d}h:{1:02d}m".format(
time_spent.seconds // 3600,
time_spent.seconds % 3600 // 60
)
else:
time_spent = ""
return time_spent
class EscapeHtml(Extension):
def extendMarkdown(self, md):
md.preprocessors.deregister('html_block')
md.inlinePatterns.deregister('html')
def get_markdown(text):
if not text:
return ""
pattern = r'([\[\s\S\]]*?)\(([\s\S]*?):([\s\S]*?)\)'
# Regex check
if re.match(pattern, text):
# get get value of group regex
scheme = re.search(pattern, text, re.IGNORECASE).group(2)
# scheme check
if scheme in helpdesk_settings.ALLOWED_URL_SCHEMES:
replacement = '\\1(\\2:\\3)'
else:
replacement = '\\1(\\3)'
text = re.sub(pattern, replacement, text, flags=re.IGNORECASE)
return mark_safe(
markdown(
text,
extensions=[
EscapeHtml(), 'markdown.extensions.nl2br',
'markdown.extensions.fenced_code'
]
)
)
class Queue(models.Model):
"""
A queue is a collection of tickets into what would generally be business
areas or departments.
For example, a company may have a queue for each Product they provide, or
a queue for each of Accounts, Pre-Sales, and Support.
"""
title = models.CharField(
_('Title'),
max_length=100,
)
slug = models.SlugField(
_('Slug'),
max_length=50,
unique=True,
help_text=_('This slug is used when building ticket ID\'s. Once set, '
'try not to change it or e-mailing may get messy.'),
)
email_address = models.EmailField(
_('E-Mail Address'),
blank=True,
null=True,
help_text=_('All outgoing e-mails for this queue will use this e-mail '
'address. If you use IMAP or POP3, this should be the e-mail '
'address for that mailbox.'),
)
locale = models.CharField(
_('Locale'),
max_length=10,
blank=True,
null=True,
help_text=_('Locale of this queue. All correspondence in this '
'queue will be in this language.'),
)
allow_public_submission = models.BooleanField(
_('Allow Public Submission?'),
blank=True,
default=False,
help_text=_(
'Should this queue be listed on the public submission form?'),
)
allow_email_submission = models.BooleanField(
_('Allow E-Mail Submission?'),
blank=True,
default=False,
help_text=_('Do you want to poll the e-mail box below for new '
'tickets?'),
)
escalate_days = models.IntegerField(
_('Escalation Days'),
blank=True,
null=True,
help_text=_('For tickets which are not held, how often do you wish to '
'increase their priority? Set to 0 for no escalation.'),
)
new_ticket_cc = models.CharField(
_('New Ticket CC Address'),
blank=True,
null=True,
max_length=200,
help_text=_('If an e-mail address is entered here, then it will '
'receive notification of all new tickets created for this queue. '
'Enter a comma between multiple e-mail addresses.'),
)
updated_ticket_cc = models.CharField(
_('Updated Ticket CC Address'),
blank=True,
null=True,
max_length=200,
help_text=_('If an e-mail address is entered here, then it will '
'receive notification of all activity (new tickets, closed '
'tickets, updates, reassignments, etc) for this queue. Separate '
'multiple addresses with a comma.'),
)
enable_notifications_on_email_events = models.BooleanField(
_('Notify contacts when email updates arrive'),
blank=True,
default=False,
help_text=_('When an email arrives to either create a ticket or to '
'interact with an existing discussion. Should email notifications be sent ? '
'Note: the new_ticket_cc and updated_ticket_cc work independently of this feature'),
)
email_box_type = models.CharField(
_('E-Mail Box Type'),
max_length=5,
choices=(('pop3', _('POP 3')),
('imap', _('IMAP')),
('oauth', _('IMAP OAUTH')),
('local', _('Local Directory'))),
blank=True,
null=True,
help_text=_('E-Mail server type for creating tickets automatically '
'from a mailbox - both POP3 and IMAP are supported, as well as '
'reading from a local directory.'),
)
email_box_host = models.CharField(
_('E-Mail Hostname'),
max_length=200,
blank=True,
null=True,
help_text=_('Your e-mail server address - either the domain name or '
'IP address. May be "localhost".'),
)
email_box_port = models.IntegerField(
_('E-Mail Port'),
blank=True,
null=True,
help_text=_('Port number to use for accessing e-mail. Default for '
'POP3 is "110", and for IMAP is "143". This may differ on some '
'servers. Leave it blank to use the defaults.'),
)
email_box_ssl = models.BooleanField(
_('Use SSL for E-Mail?'),
blank=True,
default=False,
help_text=_('Whether to use SSL for IMAP or POP3 - the default ports '
'when using SSL are 993 for IMAP and 995 for POP3.'),
)
email_box_user = models.CharField(
_('E-Mail Username'),
max_length=200,
blank=True,
null=True,
help_text=_('Username for accessing this mailbox.'),
)
email_box_pass = models.CharField(
_('E-Mail Password'),
max_length=200,
blank=True,
null=True,
help_text=_('Password for the above username'),
)
email_box_imap_folder = models.CharField(
_('IMAP Folder'),
max_length=100,
blank=True,
null=True,
help_text=_('If using IMAP, what folder do you wish to fetch messages '
'from? This allows you to use one IMAP account for multiple '
'queues, by filtering messages on your IMAP server into separate '
'folders. Default: INBOX.'),
)
email_box_local_dir = models.CharField(
_('E-Mail Local Directory'),
max_length=200,
blank=True,
null=True,
help_text=_('If using a local directory, what directory path do you '
'wish to poll for new email? '
'Example: /var/lib/mail/helpdesk/'),
)
permission_name = models.CharField(
_('Django auth permission name'),
max_length=72, # based on prepare_permission_name() pre-pending chars to slug
blank=True,
null=True,
editable=False,
help_text=_('Name used in the django.contrib.auth permission system'),
)
email_box_interval = models.IntegerField(
_('E-Mail Check Interval'),
help_text=_(
'How often do you wish to check this mailbox? (in Minutes)'),
blank=True,
null=True,
default='5',
)
email_box_last_check = models.DateTimeField(
blank=True,
null=True,
editable=False,
# This is updated by management/commands/get_mail.py.
)
socks_proxy_type = models.CharField(
_('Socks Proxy Type'),
max_length=8,
choices=(('socks4', _('SOCKS4')), ('socks5', _('SOCKS5'))),
blank=True,
null=True,
help_text=_(
'SOCKS4 or SOCKS5 allows you to proxy your connections through a SOCKS server.'),
)
socks_proxy_host = models.GenericIPAddressField(
_('Socks Proxy Host'),
blank=True,
null=True,
help_text=_('Socks proxy IP address. Default: 127.0.0.1'),
)
socks_proxy_port = models.IntegerField(
_('Socks Proxy Port'),
blank=True,
null=True,
help_text=_(
'Socks proxy port number. Default: 9150 (default TOR port)'),
)
logging_type = models.CharField(
_('Logging Type'),
max_length=5,
choices=(
('none', _('None')),
('debug', _('Debug')),
('info', _('Information')),
('warn', _('Warning')),
('error', _('Error')),
('crit', _('Critical'))
),
blank=True,
null=True,
help_text=_('Set the default logging level. All messages at that '
'level or above will be logged to the directory set '
'below. If no level is set, logging will be disabled.'),
)
logging_dir = models.CharField(
_('Logging Directory'),
max_length=200,
blank=True,
null=True,
help_text=_('If logging is enabled, what directory should we use to '
'store log files for this queue? '
'The standard logging mechanims are used if no directory is set'),
)
default_owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
related_name='default_owner',
blank=True,
null=True,
verbose_name=_('Default owner'),
)
dedicated_time = models.DurationField(
help_text=_("Time to be spent on this Queue in total"),
blank=True, null=True
)
def __str__(self):
return "%s" % self.title
class Meta:
ordering = ('title',)
verbose_name = _('Queue')
verbose_name_plural = _('Queues')
def _from_address(self):
"""
Short property to provide a sender address in SMTP format,
eg 'Name <email>'. We do this so we can put a simple error message
in the sender name field, so hopefully the admin can see and fix it.
"""
if not self.email_address:
# must check if given in format "Foo <foo@example.com>"
default_email = re.match(
".*<(?P<email>.*@*.)>", settings.DEFAULT_FROM_EMAIL)
if default_email is not None:
# already in the right format, so just include it here
return u'NO QUEUE EMAIL ADDRESS DEFINED %s' % settings.DEFAULT_FROM_EMAIL
else:
return u'NO QUEUE EMAIL ADDRESS DEFINED <%s>' % settings.DEFAULT_FROM_EMAIL
else:
return u'%s <%s>' % (self.title, self.email_address)
from_address = property(_from_address)
@property
def time_spent(self):
"""Return back total time spent on the ticket. This is calculated value
based on total sum from all FollowUps
"""
total = datetime.timedelta(0)
for val in self.ticket_set.all():
if val.time_spent:
total = total + val.time_spent
return total
@property
def time_spent_formated(self):
return format_time_spent(self.time_spent)
def prepare_permission_name(self):
"""Prepare internally the codename for the permission and store it in permission_name.
:return: The codename that can be used to create a new Permission object.
"""
# Prepare the permission associated to this Queue
basename = "queue_access_%s" % self.slug
self.permission_name = "helpdesk.%s" % basename
return basename
def save(self, *args, **kwargs):
if self.email_box_type == 'imap' and not self.email_box_imap_folder:
self.email_box_imap_folder = 'INBOX'
if self.socks_proxy_type:
if not self.socks_proxy_host:
self.socks_proxy_host = '127.0.0.1'
if not self.socks_proxy_port:
self.socks_proxy_port = 9150
else:
self.socks_proxy_host = None
self.socks_proxy_port = None
if not self.email_box_port:
if self.email_box_type == 'imap' and self.email_box_ssl:
self.email_box_port = 993
elif self.email_box_type == 'imap' and not self.email_box_ssl:
self.email_box_port = 143
elif self.email_box_type == 'pop3' and self.email_box_ssl:
self.email_box_port = 995
elif self.email_box_type == 'pop3' and not self.email_box_ssl:
self.email_box_port = 110
if not self.id:
# Prepare the permission codename and the permission
# (even if they are not needed with the current configuration)
basename = self.prepare_permission_name()
Permission.objects.create(
name=_("Permission for queue: ") + self.title,
content_type=ContentType.objects.get_for_model(self.__class__),
codename=basename,
)
super(Queue, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
permission_name = self.permission_name
super(Queue, self).delete(*args, **kwargs)
# once the Queue is safely deleted, remove the permission (if exists)
if permission_name:
try:
p = Permission.objects.get(codename=permission_name[9:])
p.delete()
except ObjectDoesNotExist:
pass
def mk_secret():
return str(uuid.uuid4())
class Ticket(models.Model):
"""
To allow a ticket to be entered as quickly as possible, only the
bare minimum fields are required. These basically allow us to
sort and manage the ticket. The user can always go back and
enter more information later.
A good example of this is when a customer is on the phone, and
you want to give them a ticket ID as quickly as possible. You can
enter some basic info, save the ticket, give the customer the ID
and get off the phone, then add in further detail at a later time
(once the customer is not on the line).
Note that assigned_to is optional - unassigned tickets are displayed on
the dashboard to prompt users to take ownership of them.
"""
OPEN_STATUS = 1
REOPENED_STATUS = 2
RESOLVED_STATUS = 3
CLOSED_STATUS = 4
DUPLICATE_STATUS = 5
STATUS_CHOICES = (
(OPEN_STATUS, _('Open')),
(REOPENED_STATUS, _('Reopened')),
(RESOLVED_STATUS, _('Resolved')),
(CLOSED_STATUS, _('Closed')),
(DUPLICATE_STATUS, _('Duplicate')),
)
PRIORITY_CHOICES = helpdesk_settings.TICKET_PRIORITY_CHOICES
title = models.CharField(
_('Title'),
max_length=200,
)
queue = models.ForeignKey(
Queue,
on_delete=models.CASCADE,
verbose_name=_('Queue'),
)
created = models.DateTimeField(
_('Created'),
blank=True,
help_text=_('Date this ticket was first created'),
)
modified = models.DateTimeField(
_('Modified'),
blank=True,
help_text=_('Date this ticket was most recently changed.'),
)
submitter_email = models.EmailField(
_('Submitter E-Mail'),
blank=True,
null=True,
help_text=_('The submitter will receive an email for all public '
'follow-ups left for this task.'),
)
assigned_to = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='assigned_to',
blank=True,
null=True,
verbose_name=_('Assigned to'),
)
status = models.IntegerField(
_('Status'),
choices=STATUS_CHOICES,
default=OPEN_STATUS,
)
on_hold = models.BooleanField(
_('On Hold'),
blank=True,
default=False,
help_text=_(
'If a ticket is on hold, it will not automatically be escalated.'),
)
description = models.TextField(
_('Description'),
blank=True,
null=True,
help_text=_('The content of the customers query.'),
)
resolution = models.TextField(
_('Resolution'),
blank=True,
null=True,
help_text=_('The resolution provided to the customer by our staff.'),
)
priority = models.IntegerField(
_('Priority'),
choices=PRIORITY_CHOICES,
default=3,
blank=3,
help_text=_('1 = Highest Priority, 5 = Low Priority'),
)
due_date = models.DateTimeField(
_('Due on'),
blank=True,
null=True,
)
last_escalation = models.DateTimeField(
blank=True,
null=True,
editable=False,
help_text=_('The date this ticket was last escalated - updated '
'automatically by management/commands/escalate_tickets.py.'),
)
secret_key = models.CharField(
_("Secret key needed for viewing/editing ticket by non-logged in users"),
max_length=36,
default=mk_secret,
)
kbitem = models.ForeignKey(
"KBItem",
blank=True,
null=True,
on_delete=models.CASCADE,
verbose_name=_(
'Knowledge base item the user was viewing when they created this ticket.'),
)
merged_to = models.ForeignKey(
'self',
verbose_name=_('merged to'),
related_name='merged_tickets',
on_delete=models.CASCADE,
null=True,
blank=True
)
@property
def time_spent(self):
"""Return back total time spent on the ticket. This is calculated value
based on total sum from all FollowUps
"""
total = datetime.timedelta(0)
for val in self.followup_set.all():
if val.time_spent:
total = total + val.time_spent
return total
@property
def time_spent_formated(self):
return format_time_spent(self.time_spent)
def send(self, roles, dont_send_to=None, **kwargs):
"""
Send notifications to everyone interested in this ticket.
The the roles argument is a dictionary mapping from roles to (template, context) pairs.
If a role is not present in the dictionary, users of that type will not receive the notification.
The following roles exist:
- 'submitter'
- 'new_ticket_cc'
- 'ticket_cc'
- 'assigned_to'
Here is an example roles dictionary:
{
'submitter': (template_name, context),
'assigned_to': (template_name2, context),
}
**kwargs are passed to send_templated_mail defined in templated_email.py
returns the set of email addresses the notification was delivered to.
"""
recipients = set()
if dont_send_to is not None:
recipients.update(dont_send_to)
recipients.add(self.queue.email_address)
def should_receive(email):
return email and email not in recipients
def send(role, recipient):
if recipient and recipient not in recipients and role in roles:
template, context = roles[role]
send_templated_mail(
template, context, recipient, sender=self.queue.from_address, **kwargs)
recipients.add(recipient)
send('submitter', self.submitter_email)
send('ticket_cc', self.queue.updated_ticket_cc)
send('new_ticket_cc', self.queue.new_ticket_cc)
if self.assigned_to:
send('assigned_to', self.assigned_to.email)
if self.queue.enable_notifications_on_email_events:
for cc in self.ticketcc_set.all():
send('ticket_cc', cc.email_address)
if "new_ticket_cc" in roles:
send_new_ticket_webhook(self)
return recipients
def _get_assigned_to(self):
""" Custom property to allow us to easily print 'Unassigned' if a
ticket has no owner, or the users name if it's assigned. If the user
has a full name configured, we use that, otherwise their username. """
if not self.assigned_to:
return _('Unassigned')
else:
if self.assigned_to.get_full_name():
return self.assigned_to.get_full_name()
else:
return self.assigned_to.get_username()
get_assigned_to = property(_get_assigned_to)
def _get_ticket(self):
""" A user-friendly ticket ID, which is a combination of ticket ID
and queue slug. This is generally used in e-mail subjects. """
return u"[%s]" % self.ticket_for_url
ticket = property(_get_ticket)
def _get_ticket_for_url(self):
""" A URL-friendly ticket ID, used in links. """
return u"%s-%s" % (self.queue.slug, self.id)
ticket_for_url = property(_get_ticket_for_url)
def _get_priority_css_class(self):
"""
Return the boostrap class corresponding to the priority.
"""
if self.priority == 2:
return "warning"
elif self.priority == 1:
return "danger"
elif self.priority == 5:
return "success"
else:
return ""
get_priority_css_class = property(_get_priority_css_class)
def _get_status(self):
"""
Displays the ticket status, with an "On Hold" message if needed.
"""
held_msg = ''
if self.on_hold:
held_msg = _(' - On Hold')
dep_msg = ''
if not self.can_be_resolved:
dep_msg = _(' - Open dependencies')
return u'%s%s%s' % (self.get_status_display(), held_msg, dep_msg)
get_status = property(_get_status)
def _get_ticket_url(self):
"""
Returns a publicly-viewable URL for this ticket, used when giving
a URL to the submitter of a ticket.
"""
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
try:
site = Site.objects.get_current()
except ImproperlyConfigured:
site = Site(domain='configure-django-sites.com')
if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK:
protocol = 'https'
else:
protocol = 'http'
return u"%s://%s%s?ticket=%s&email=%s&key=%s" % (
protocol,
site.domain,
reverse('helpdesk:public_view'),
self.ticket_for_url,
self.submitter_email,
self.secret_key
)
ticket_url = property(_get_ticket_url)
def _get_staff_url(self):
"""
Returns a staff-only URL for this ticket, used when giving a URL to
a staff member (in emails etc)
"""
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
try:
site = Site.objects.get_current()
except ImproperlyConfigured:
site = Site(domain='configure-django-sites.com')
if helpdesk_settings.HELPDESK_USE_HTTPS_IN_EMAIL_LINK:
protocol = 'https'
else:
protocol = 'http'
return u"%s://%s%s" % (
protocol,
site.domain,
reverse('helpdesk:view',
args=[self.id])
)
staff_url = property(_get_staff_url)
def _can_be_resolved(self):
"""
Returns a boolean.
True = any dependencies are resolved
False = There are non-resolved dependencies
"""
OPEN_STATUSES = (Ticket.OPEN_STATUS, Ticket.REOPENED_STATUS)
return TicketDependency.objects.filter(ticket=self).filter(
depends_on__status__in=OPEN_STATUSES).count() == 0
can_be_resolved = property(_can_be_resolved)
def get_submitter_userprofile(self):
User = get_user_model()
try:
return User.objects.get(email=self.submitter_email)
except (User.DoesNotExist, User.MultipleObjectsReturned):
return None
class Meta:
get_latest_by = "created"
ordering = ('id',)
verbose_name = _('Ticket')
verbose_name_plural = _('Tickets')
def __str__(self):
return '%s %s' % (self.id, self.title)
def get_absolute_url(self):
from django.urls import reverse
return reverse('helpdesk:view', args=(self.id,))
def save(self, *args, **kwargs):
if not self.id:
# This is a new ticket as no ID yet exists.
self.created = timezone.now()
if not self.priority:
self.priority = 3
self.modified = timezone.now()
if len(self.title) > 200:
self.title = self.title[:197] + "..."
super(Ticket, self).save(*args, **kwargs)
@staticmethod
def queue_and_id_from_query(query):
# Apply the opposite logic here compared to self._get_ticket_for_url
# Ensure that queues with '-' in them will work
parts = query.split('-')
queue = '-'.join(parts[0:-1])
return queue, parts[-1]
def get_markdown(self):
return get_markdown(self.description)
@property
def get_resolution_markdown(self):
return get_markdown(self.resolution)
def add_email_to_ticketcc_if_not_in(self, email=None, user=None, ticketcc=None):
"""
Check that given email/user_email/ticketcc_email is not already present on the ticket
(submitter email, assigned to, or in ticket CCs) and add it to a new ticket CC,
or move the given one
:param str email:
:param User user:
:param TicketCC ticketcc:
:rtype: TicketCC|None
"""
if ticketcc:
email = ticketcc.display
elif user:
if user.email:
email = user.email
else:
# Ignore if user has no email address
return
elif not email:
raise ValueError(
'You must provide at least one parameter to get the email from')
# Prepare all emails already into the ticket
ticket_emails = [x.display for x in self.ticketcc_set.all()]
if self.submitter_email:
ticket_emails.append(self.submitter_email)
if self.assigned_to and self.assigned_to.email:
ticket_emails.append(self.assigned_to.email)
# Check that email is not already part of the ticket
if email not in ticket_emails:
if ticketcc:
ticketcc.ticket = self
ticketcc.save(update_fields=['ticket'])
elif user:
ticketcc = self.ticketcc_set.create(user=user)
else:
ticketcc = self.ticketcc_set.create(email=email)
return ticketcc
def set_custom_field_values(self):
for field in CustomField.objects.all():
try:
value = self.ticketcustomfieldvalue_set.get(field=field).value
except TicketCustomFieldValue.DoesNotExist:
value = None
setattr(self, 'custom_%s' % field.name, value)
def save_custom_field_values(self, data):
for field, value in data.items():
if field.startswith('custom_'):
field_name = field.replace('custom_', '', 1)
customfield = CustomField.objects.get(name=field_name)
cfv, created = self.ticketcustomfieldvalue_set.get_or_create(
field=customfield,
defaults={'value': convert_value(value)}
)
if not created:
cfv.value = convert_value(value)
cfv.save()
class FollowUpManager(models.Manager):
def private_followups(self):
return self.filter(public=False)
def public_followups(self):
return self.filter(public=True)
class FollowUp(models.Model):
"""
A FollowUp is a comment and/or change to a ticket. We keep a simple
title, the comment entered by the user, and the new status of a ticket
to enable easy flagging of details on the view-ticket page.
The title is automatically generated at save-time, based on what action
the user took.
Tickets that aren't public are never shown to or e-mailed to the submitter,
although all staff can see them.
"""
ticket = models.ForeignKey(
Ticket,
on_delete=models.CASCADE,
verbose_name=_('Ticket'),
)
date = models.DateTimeField(
_('Date'),
default=timezone.now
)
title = models.CharField(
_('Title'),
max_length=200,
blank=True,
null=True,
)
comment = models.TextField(
_('Comment'),
blank=True,
null=True,
)
public = models.BooleanField(
_('Public'),
blank=True,
default=False,
help_text=_(
'Public tickets are viewable by the submitter and all '
'staff, but non-public tickets can only be seen by staff.'
),
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True,
verbose_name=_('User'),
)
new_status = models.IntegerField(
_('New Status'),
choices=Ticket.STATUS_CHOICES,
blank=True,
null=True,
help_text=_('If the status was changed, what was it changed to?'),
)
message_id = models.CharField(
_('E-Mail ID'),
max_length=256,
blank=True,
null=True,
help_text=_("The Message ID of the submitter's email."),
editable=False,
)
objects = FollowUpManager()
time_spent = models.DurationField(
help_text=_("Time spent on this follow up"),
blank=True, null=True
)
class Meta:
ordering = ('date',)
verbose_name = _('Follow-up')
verbose_name_plural = _('Follow-ups')
def __str__(self):
return '%s' % self.title
def get_absolute_url(self):
return u"%s#followup%s" % (self.ticket.get_absolute_url(), self.id)
def save(self, *args, **kwargs):
t = self.ticket
t.modified = timezone.now()
t.save()
super(FollowUp, self).save(*args, **kwargs)
def get_markdown(self):
return get_markdown(self.comment)
@property