Add a REST API for the dashboard
[pharos.git] / tools / pharos-dashboard / booking / models.py
1 from django.contrib.auth.models import User
2 from django.db import models
3 from jira import JIRA
4 from jira import JIRAError
5
6 from dashboard.models import Resource
7 from django.conf import settings
8
9
10 class Booking(models.Model):
11     id = models.AutoField(primary_key=True)
12     user = models.ForeignKey(User, models.CASCADE)  # delete if user is deleted
13     resource = models.ForeignKey(Resource, models.PROTECT)
14     start = models.DateTimeField()
15     end = models.DateTimeField()
16     jira_issue_id = models.IntegerField(null=True)
17     jira_issue_status = models.CharField(max_length=50)
18
19     purpose = models.CharField(max_length=300, blank=False)
20
21     class Meta:
22         db_table = 'booking'
23
24     def get_jira_issue(self):
25         try:
26             jira = JIRA(server=settings.JIRA_URL,
27                         basic_auth=(settings.JIRA_USER_NAME, settings.JIRA_USER_PASSWORD))
28             issue = jira.issue(self.jira_issue_id)
29             return issue
30         except JIRAError:
31             return None
32
33     def authorization_test(self):
34         """
35         Return True if self.user is authorized to make this booking.
36         """
37         user = self.user
38         # Check if User is troubleshooter / admin
39         if user.has_perm('booking.add_booking'):
40             return True
41         # Check if User owns this resource
42         if user == self.resource.owner:
43             return True
44         return False
45
46     def save(self, *args, **kwargs):
47         """
48         Save the booking if self.user is authorized and there is no overlapping booking.
49         Raise PermissionError if the user is not authorized
50         Raise ValueError if there is an overlapping booking
51         """
52         if not self.authorization_test():
53             raise PermissionError('Insufficient permissions to save this booking.')
54         if self.start >= self.end:
55             raise ValueError('Start date is after end date')
56         # conflicts end after booking starts, and start before booking ends
57         conflicting_dates = Booking.objects.filter(resource=self.resource).exclude(id=self.id)
58         conflicting_dates = conflicting_dates.filter(end__gt=self.start)
59         conflicting_dates = conflicting_dates.filter(start__lt=self.end)
60         if conflicting_dates.count() > 0:
61             raise ValueError('This booking overlaps with another booking')
62         return super(Booking, self).save(*args, **kwargs)
63
64     def __str__(self):
65         return str(self.resource) + ' from ' + str(self.start) + ' until ' + str(self.end)