Fix PyCharm warnings in staff.py

This commit is contained in:
Benbb96 2022-08-15 20:15:02 +02:00
parent cf25e5f714
commit bc3d89b555

View File

@ -6,6 +6,8 @@ django-helpdesk - A Django powered ticket tracker for small enterprise.
views/staff.py - The bulk of the application - provides most business logic and views/staff.py - The bulk of the application - provides most business logic and
renders all staff-facing views. renders all staff-facing views.
""" """
from django.contrib.auth.views import redirect_to_login
from ..lib import format_time_spent from ..lib import format_time_spent
from ..templated_email import send_templated_mail from ..templated_email import send_templated_mail
from collections import defaultdict from collections import defaultdict
@ -273,8 +275,7 @@ def followup_edit(request, ticket_id, followup_id):
'time_spent': format_time_spent(followup.time_spent), 'time_spent': format_time_spent(followup.time_spent),
}) })
ticketcc_string, __ = \ ticketcc_string = return_ticketccstring_and_show_subscribe(request.user, ticket)[0]
return_ticketccstring_and_show_subscribe(request.user, ticket)
return render(request, 'helpdesk/followup_edit.html', { return render(request, 'helpdesk/followup_edit.html', {
'followup': followup, 'followup': followup,
@ -356,7 +357,7 @@ def view_ticket(request, ticket_id):
)[1] )[1]
if show_subscribe: if show_subscribe:
subscribe_staff_member_to_ticket(ticket, request.user) subscribe_to_ticket_updates(ticket, request.user)
return HttpResponseRedirect(reverse('helpdesk:view', args=[ticket.id])) return HttpResponseRedirect(reverse('helpdesk:view', args=[ticket.id]))
if 'close' in request.GET and ticket.status == Ticket.RESOLVED_STATUS: if 'close' in request.GET and ticket.status == Ticket.RESOLVED_STATUS:
@ -471,30 +472,19 @@ def subscribe_to_ticket_updates(ticket, user=None, email=None, can_view=True, ca
_('When you add somebody on Cc, you must provide either a User or a valid email. Email: %s' % email) _('When you add somebody on Cc, you must provide either a User or a valid email. Email: %s' % email)
) )
ticketcc = TicketCC( return ticket.ticketcc_set.create(
ticket=ticket,
user=user, user=user,
email=email, email=email,
can_view=can_view, can_view=can_view,
can_update=can_update can_update=can_update
) )
ticketcc.save()
return ticketcc
def subscribe_staff_member_to_ticket(ticket, user, email='', can_view=True, can_update=False):
"""used in view_ticket() and update_ticket()"""
return subscribe_to_ticket_updates(ticket=ticket, user=user, email=email, can_view=can_view, can_update=can_update)
def get_ticket_from_request_with_authorisation( def get_ticket_from_request_with_authorisation(
request: WSGIRequest, request: WSGIRequest,
ticket_id: str, ticket_id: str,
public: bool public: bool
) -> typing.Union[ ) -> Ticket:
Ticket, typing.NoReturn
]:
"""Gets a ticket from the public status and if the user is authenticated and """Gets a ticket from the public status and if the user is authenticated and
has permissions to update tickets has permissions to update tickets
@ -508,20 +498,14 @@ def get_ticket_from_request_with_authorisation(
is_helpdesk_staff(request.user) or is_helpdesk_staff(request.user) or
helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE))): helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE))):
key = request.POST.get('key') try:
email = request.POST.get('mail') return Ticket.objects.get(
if key and email:
ticket = Ticket.objects.get(
id=ticket_id, id=ticket_id,
submitter_email__iexact=email, submitter_email__iexact=request.POST.get('mail'),
secret_key__iexact=key secret_key__iexact=request.POST.get('key')
)
if not ticket:
return HttpResponseRedirect(
'%s?next=%s' % (reverse('helpdesk:login'), request.path)
) )
except (Ticket.DoesNotExist, ValueError):
return redirect_to_login(request.path, 'helpdesk:login')
return get_object_or_404(Ticket, id=ticket_id) return get_object_or_404(Ticket, id=ticket_id)
@ -562,10 +546,10 @@ def get_due_date_from_request_or_ticket(
def get_and_set_ticket_status( def get_and_set_ticket_status(
new_status: str, new_status: int,
ticket: Ticket, ticket: Ticket,
follow_up: FollowUp follow_up: FollowUp
) -> typing.Tuple[str, str]: ) -> typing.Tuple[str, int]:
"""Performs comparision on previous status to new status, """Performs comparision on previous status to new status,
updating the title as required. updating the title as required.
@ -590,7 +574,7 @@ def get_and_set_ticket_status(
follow_up.title = _('Updated') follow_up.title = _('Updated')
follow_up.save() follow_up.save()
return (old_status_str, old_status) return old_status_str, old_status
def get_time_spent_from_request(request: WSGIRequest) -> typing.Optional[timedelta]: def get_time_spent_from_request(request: WSGIRequest) -> typing.Optional[timedelta]:
@ -606,7 +590,7 @@ def update_messages_sent_to_by_public_and_status(
ticket: Ticket, ticket: Ticket,
follow_up: FollowUp, follow_up: FollowUp,
context: str, context: str,
messages_sent_to: typing.List[str], messages_sent_to: typing.Set[str],
files: typing.List[typing.Tuple[str, str]] files: typing.List[typing.Tuple[str, str]]
) -> Ticket: ) -> Ticket:
"""Sets the status of the ticket""" """Sets the status of the ticket"""
@ -648,13 +632,10 @@ def add_staff_subscription(
) -> None: ) -> None:
"""Auto subscribe the staff member if that's what the settigs say and the """Auto subscribe the staff member if that's what the settigs say and the
user is authenticated and a staff member""" user is authenticated and a staff member"""
if helpdesk_settings.HELPDESK_AUTO_SUBSCRIBE_ON_TICKET_RESPONSE and request.user.is_authenticated: if helpdesk_settings.HELPDESK_AUTO_SUBSCRIBE_ON_TICKET_RESPONSE \
SHOW_SUBSCRIBE = return_ticketccstring_and_show_subscribe( and request.user.is_authenticated \
request.user, ticket and return_ticketccstring_and_show_subscribe(request.user, ticket)[1]:
)[1] subscribe_to_ticket_updates(ticket, request.user)
if SHOW_SUBSCRIBE:
subscribe_staff_member_to_ticket(ticket, request.user)
def get_template_staff_and_template_cc( def get_template_staff_and_template_cc(
@ -878,12 +859,13 @@ def mass_update(request):
if not (tickets and action): if not (tickets and action):
return HttpResponseRedirect(reverse('helpdesk:list')) return HttpResponseRedirect(reverse('helpdesk:list'))
user = kbitem = None
if action.startswith('assign_'): if action.startswith('assign_'):
parts = action.split('_') parts = action.split('_')
user = User.objects.get(id=parts[1]) user = User.objects.get(id=parts[1])
action = 'assign' action = 'assign'
if action == 'kbitem_none': if action == 'kbitem_none':
kbitem = None
action = 'set_kbitem' action = 'set_kbitem'
if action.startswith('kbitem_'): if action.startswith('kbitem_'):
parts = action.split('_') parts = action.split('_')
@ -908,52 +890,50 @@ def mass_update(request):
if action == 'assign' and t.assigned_to != user: if action == 'assign' and t.assigned_to != user:
t.assigned_to = user t.assigned_to = user
t.save() t.save()
f = FollowUp(ticket=t, t.followup_set.create(
date=timezone.now(), date=timezone.now(),
title=_('Assigned to %(username)s in bulk update' % { title=_('Assigned to %(username)s in bulk update' % {'username': user.get_username()}),
'username': user.get_username()
}),
public=True, public=True,
user=request.user) user=request.user
f.save() )
elif action == 'unassign' and t.assigned_to is not None: elif action == 'unassign' and t.assigned_to is not None:
t.assigned_to = None t.assigned_to = None
t.save() t.save()
f = FollowUp(ticket=t, t.followup_set.create(
date=timezone.now(), date=timezone.now(),
title=_('Unassigned in bulk update'), title=_('Unassigned in bulk update'),
public=True, public=True,
user=request.user) user=request.user
f.save() )
elif action == 'set_kbitem': elif action == 'set_kbitem':
t.kbitem = kbitem t.kbitem = kbitem
t.save() t.save()
f = FollowUp(ticket=t, t.followup_set.create(
date=timezone.now(), date=timezone.now(),
title=_('KBItem set in bulk update'), title=_('KBItem set in bulk update'),
public=False, public=False,
user=request.user) user=request.user
f.save() )
elif action == 'close' and t.status != Ticket.CLOSED_STATUS: elif action == 'close' and t.status != Ticket.CLOSED_STATUS:
t.status = Ticket.CLOSED_STATUS t.status = Ticket.CLOSED_STATUS
t.save() t.save()
f = FollowUp(ticket=t, t.followup_set.create(
date=timezone.now(), date=timezone.now(),
title=_('Closed in bulk update'), title=_('Closed in bulk update'),
public=False, public=False,
user=request.user, user=request.user,
new_status=Ticket.CLOSED_STATUS) new_status=Ticket.CLOSED_STATUS
f.save() )
elif action == 'close_public' and t.status != Ticket.CLOSED_STATUS: elif action == 'close_public' and t.status != Ticket.CLOSED_STATUS:
t.status = Ticket.CLOSED_STATUS t.status = Ticket.CLOSED_STATUS
t.save() t.save()
f = FollowUp(ticket=t, t.followup_set.create(
date=timezone.now(), date=timezone.now(),
title=_('Closed in bulk update'), title=_('Closed in bulk update'),
public=True, public=True,
user=request.user, user=request.user,
new_status=Ticket.CLOSED_STATUS) new_status=Ticket.CLOSED_STATUS
f.save() )
# Send email to Submitter, Owner, Queue CC # Send email to Submitter, Owner, Queue CC
context = safe_template_context(t) context = safe_template_context(t)
context.update(resolution=t.resolution, context.update(resolution=t.resolution,
@ -1183,19 +1163,17 @@ def check_redirect_on_user_query(request, huser):
if query.find('-') > 0: if query.find('-') > 0:
try: try:
queue, id_ = Ticket.queue_and_id_from_query(query) queue, id_ = Ticket.queue_and_id_from_query(query)
id_ = int(id) id_ = int(id_)
except ValueError: except ValueError:
id_ = None pass
else:
if id_:
filter_ = {'queue__slug': queue, 'id': id_} filter_ = {'queue__slug': queue, 'id': id_}
else: else:
try: try:
query = int(query) query = int(query)
except ValueError: except ValueError:
query = None pass
else:
if query:
filter_ = {'id': int(query)} filter_ = {'id': int(query)}
if filter_: if filter_:
@ -1364,7 +1342,7 @@ def load_saved_query(request, query_params=None):
query_params = query_from_base64(b64query) query_params = query_from_base64(b64query)
except json.JSONDecodeError: except json.JSONDecodeError:
raise QueryLoadError() raise QueryLoadError()
return (saved_query, query_params) return saved_query, query_params
@helpdesk_staff_member_required @helpdesk_staff_member_required
@ -1377,14 +1355,14 @@ def datatables_ticket_list(request, query):
""" """
query = Query(HelpdeskUser(request.user), base64query=query) query = Query(HelpdeskUser(request.user), base64query=query)
result = query.get_datatables_context(**request.query_params) result = query.get_datatables_context(**request.query_params)
return (JsonResponse(result, status=status.HTTP_200_OK)) return JsonResponse(result, status=status.HTTP_200_OK)
@helpdesk_staff_member_required @helpdesk_staff_member_required
@api_view(['GET']) @api_view(['GET'])
def timeline_ticket_list(request, query): def timeline_ticket_list(request, query):
query = Query(HelpdeskUser(request.user), base64query=query) query = Query(HelpdeskUser(request.user), base64query=query)
return (JsonResponse(query.get_timeline_context(), status=status.HTTP_200_OK)) return JsonResponse(query.get_timeline_context(), status=status.HTTP_200_OK)
@helpdesk_staff_member_required @helpdesk_staff_member_required
@ -1615,6 +1593,9 @@ def update_summary_tables(report_queryset, report, summarytable, summarytable2):
metric3 = ticket.modified - ticket.created metric3 = ticket.modified - ticket.created
metric3 = metric3.days metric3 = metric3.days
else:
raise ValueError(f'report "{report}" is unrecognized.')
summarytable[metric1, metric2] += 1 summarytable[metric1, metric2] += 1
if metric3: if metric3:
if report == 'daysuntilticketclosedbymonth': if report == 'daysuntilticketclosedbymonth':
@ -1797,7 +1778,7 @@ class EditUserSettingsView(MustBeStaffMixin, UpdateView):
model = UserSettings model = UserSettings
success_url = reverse_lazy('helpdesk:dashboard') success_url = reverse_lazy('helpdesk:dashboard')
def get_object(self): def get_object(self, queryset=None):
return UserSettings.objects.get_or_create(user=self.request.user)[0] return UserSettings.objects.get_or_create(user=self.request.user)[0]