Add Installer and Scenario fields to bookings
[pharos.git] / tools / pharos-dashboard / src / booking / views.py
1 ##############################################################################
2 # Copyright (c) 2016 Max Breitenfeldt and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10
11 from datetime import timedelta
12
13 from django.conf import settings
14 from django.contrib import messages
15 from django.contrib.auth.mixins import LoginRequiredMixin
16 from django.http import JsonResponse
17 from django.shortcuts import get_object_or_404
18 from django.urls import reverse
19 from django.utils import timezone
20 from django.views import View
21 from django.views.generic import FormView
22 from django.views.generic import TemplateView
23 from jira import JIRAError
24
25 from account.jira_util import get_jira
26 from booking.forms import BookingForm
27 from booking.models import Booking
28 from dashboard.models import Resource
29
30
31 def create_jira_ticket(user, booking):
32     jira = get_jira(user)
33     issue_dict = {
34         'project': 'PHAROS',
35         'summary': str(booking.resource) + ': Access Request',
36         'description': booking.purpose,
37         'issuetype': {'name': 'Task'},
38         'components': [{'name': 'POD Access Request'}],
39         'assignee': {'name': booking.resource.owner.username}
40     }
41     issue = jira.create_issue(fields=issue_dict)
42     jira.add_attachment(issue, user.userprofile.pgp_public_key)
43     jira.add_attachment(issue, user.userprofile.ssh_public_key)
44     booking.jira_issue_id = issue.id
45     booking.save()
46
47
48 class BookingFormView(LoginRequiredMixin, FormView):
49     template_name = "booking/booking_calendar.html"
50     form_class = BookingForm
51
52     def dispatch(self, request, *args, **kwargs):
53         self.resource = get_object_or_404(Resource, id=self.kwargs['resource_id'])
54         return super(BookingFormView, self).dispatch(request, *args, **kwargs)
55
56     def get_context_data(self, **kwargs):
57         title = 'Booking: ' + self.resource.name
58         context = super(BookingFormView, self).get_context_data(**kwargs)
59         context.update({'title': title, 'resource': self.resource})
60         return context
61
62     def get_success_url(self):
63         return reverse('booking:create', kwargs=self.kwargs)
64
65     def form_valid(self, form):
66         user = self.request.user
67         booking = Booking(start=form.cleaned_data['start'],
68                           end=form.cleaned_data['end'],
69                           purpose=form.cleaned_data['purpose'],
70                           installer=form.cleaned_data['installer'],
71                           scenario=form.cleaned_data['scenario'],
72                           resource=self.resource, user=user)
73         try:
74             booking.save()
75         except ValueError as err:
76             messages.add_message(self.request, messages.ERROR, err)
77             return super(BookingFormView, self).form_invalid(form)
78         except PermissionError as err:
79             messages.add_message(self.request, messages.ERROR, err)
80             return super(BookingFormView, self).form_invalid(form)
81         try:
82             if settings.CREATE_JIRA_TICKET:
83                 create_jira_ticket(user, booking)
84         except JIRAError:
85             messages.add_message(self.request, messages.ERROR, 'Failed to create Jira Ticket. '
86                                                                'Please check your Jira '
87                                                                'permissions.')
88             booking.delete()
89             return super(BookingFormView, self).form_invalid(form)
90         messages.add_message(self.request, messages.SUCCESS, 'Booking saved')
91         return super(BookingFormView, self).form_valid(form)
92
93
94 class BookingView(TemplateView):
95     template_name = "booking/booking_detail.html"
96
97     def get_context_data(self, **kwargs):
98         booking = get_object_or_404(Booking, id=self.kwargs['booking_id'])
99         title = 'Booking Details'
100         context = super(BookingView, self).get_context_data(**kwargs)
101         context.update({'title': title, 'booking': booking})
102         return context
103
104 class BookingListView(TemplateView):
105     template_name = "booking/booking_list.html"
106
107     def get_context_data(self, **kwargs):
108         bookings = Booking.objects.filter(end__gte=timezone.now())
109         title = 'Search Booking'
110         context = super(BookingListView, self).get_context_data(**kwargs)
111         context.update({'title': title, 'bookings': bookings})
112         return context
113
114
115 class ResourceBookingsJSON(View):
116     def get(self, request, *args, **kwargs):
117         resource = get_object_or_404(Resource, id=self.kwargs['resource_id'])
118         bookings = resource.booking_set.get_queryset().values('id', 'start', 'end', 'purpose',
119                                                               'jira_issue_status',
120                                                               'installer__name', 'scenario__name')
121         return JsonResponse({'bookings': list(bookings)})