1 from django.contrib.auth.models import User
2 from django.db import models
4 from jira import JIRAError
6 from dashboard.models import Resource
7 from django.conf import settings
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)
19 purpose = models.CharField(max_length=300, blank=False)
24 def get_jira_issue(self):
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)
33 def authorization_test(self):
35 Return True if self.user is authorized to make this booking.
38 # Check if User is troubleshooter / admin
39 if user.has_perm('booking.add_booking'):
41 # Check if User owns this resource
42 if user == self.resource.owner:
46 def save(self, *args, **kwargs):
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
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)
65 return str(self.resource) + ' from ' + str(self.start) + ' until ' + str(self.end)