Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fixed timeslots for bookable #69

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions fars/booking/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,24 @@

# Register your models here.

app = apps.get_app_config('booking')
from .models import Bookable, Timeslot

for model_name, model in app.models.items():
admin.site.register(model)
class TimeslotInline(admin.TabularInline):
model = Timeslot
fields = ("start_weekday", "start_time", "end_weekday", "end_time",)


class BookableAdmin(admin.ModelAdmin):
inlines = [
TimeslotInline,
]

admin.site.register(Bookable, BookableAdmin)


models = apps.get_models()
for model in models:
try:
admin.site.register(model)
except admin.sites.AlreadyRegistered:
pass
2 changes: 1 addition & 1 deletion fars/booking/forms.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django import forms
from booking.models import Booking, RepeatedBookingGroup
from booking.models import Booking, RepeatedBookingGroup, Bookable
from django.contrib.auth.forms import AuthenticationForm
from django.forms.widgets import PasswordInput, TextInput, NumberInput, DateInput
from datetime import datetime, timedelta, date
Expand Down
24 changes: 24 additions & 0 deletions fars/booking/migrations/0012_auto_20201020_1038.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 3.1.2 on 2020-10-20 07:38

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('booking', '0011_auto_20191229_1836'),
]

operations = [
migrations.AlterField(
model_name='bookable',
name='bill_device_id',
field=models.PositiveIntegerField(blank=True, default=None, help_text='BILL device ID if BILL check is needed. If empty no BILL check will be performed', null=True),
),
migrations.AlterField(
model_name='booking',
name='repeatgroup',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='booking.repeatedbookinggroup'),
),
]
25 changes: 25 additions & 0 deletions fars/booking/migrations/0013_timeslot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 3.1.2 on 2020-10-24 15:24

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('booking', '0012_auto_20201020_1038'),
]

operations = [
migrations.CreateModel(
name='Timeslot',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start_time', models.TimeField()),
('start_weekday', models.CharField(choices=[('Mon', 'måndag'), ('Tue', 'tisdag'), ('Wed', 'onsdag'), ('Thu', 'torsdag'), ('Fri', 'fredag'), ('Sat', 'lördag'), ('Sun', 'söndag')], max_length=3)),
('end_time', models.TimeField()),
('end_weekday', models.CharField(choices=[('Mon', 'måndag'), ('Tue', 'tisdag'), ('Wed', 'onsdag'), ('Thu', 'torsdag'), ('Fri', 'fredag'), ('Sat', 'lördag'), ('Sun', 'söndag')], max_length=3)),
('bookable', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='booking.bookable')),
],
),
]
124 changes: 118 additions & 6 deletions fars/booking/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.utils.translation import gettext as _
from datetime import timedelta
from datetime import timedelta, datetime
import time

import logging

Expand Down Expand Up @@ -63,6 +64,114 @@ def notify_external_services(self):
for service in ExternalService.objects.filter(bookable__id=self.id):
service.notify(session)

def has_bookable_timeslots(self):
if Timeslot.objects.filter(bookable=self).count() > 0: return True
return False
Comment on lines +68 to +69
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if Timeslot.objects.filter(bookable=self).count() > 0: return True
return False
return Timeslot.objects.filter(bookable=self).count() > 0


def get_start_slots(self, query=None):
if query is None:
timeslots = Timeslot.objects.filter(bookable=self)
else:
timeslots = query
return [ts.get_start() for ts in timeslots]

def get_end_slots(self, query=None):
if query is None:
timeslots = Timeslot.objects.filter(bookable=self)
else:
timeslots = query
return [ts.get_end() for ts in timeslots]

def get_bookable_timeslots_by_start_and_end_time(self):
timeslot_query = Timeslot.objects.filter(bookable=self)
return [self.get_start_slots(query=timeslot_query), self.get_end_slots(query=timeslot_query)]

def get_closest_start_datetime(self, dt, query=None):
if query is None:
timeslot_query = Timeslot.objects.filter(bookable=self)
else:
timeslot_query = query
timestamps = [ts.get_closest_start_datetime(dt) for ts in timeslot_query]

valid_start_timestamps = list(map(lambda ts: ts + timedelta(days=7) if ts <= datetime.now(dt.tzinfo) else ts, timestamps))
# Calculate the timedelta to dt timestamp for each datetime object
start_timedeltas = list(map(lambda ts: (ts - dt).total_seconds(), valid_start_timestamps))
# Find the closest valid match and return the timestamp that matches that index
closest_index = start_timedeltas.index(min(start_timedeltas, key=abs))
return valid_start_timestamps[closest_index]

def get_closest_end_datetime(self, dt, booking_start_dt, query=None):
if query is None:
timeslot_query = Timeslot.objects.filter(bookable=self)
else:
timeslot_query = query
timestamps = [ts.get_closest_end_datetime(dt) for ts in timeslot_query]

valid_end_timestamps = list(map(lambda ts: ts + timedelta(days=7) if ts <= booking_start_dt else ts, timestamps))
# Calculate the timedelta to dt timestamp for each datetime object
end_timedeltas = list(map(lambda ts: (ts - dt).total_seconds(), valid_end_timestamps))
# Find the closest valid match and return the timestamp that matches that index
closest_index = end_timedeltas.index(min(end_timedeltas, key=abs))
return valid_end_timestamps[closest_index]

def get_closest_start_and_end_datetime(self, start_dt, end_dt):
timeslot_query = Timeslot.objects.filter(bookable=self)
closest_start_datetime = self.get_closest_start_datetime(start_dt, timeslot_query)
closest_end_datetime = self.get_closest_end_datetime(end_dt, closest_start_datetime, timeslot_query)
return ( closest_start_datetime, closest_end_datetime, )


def convert_time_to_closest_datetime(timestamp, datetimestamp):
# timestamp = time struct https://docs.python.org/3/library/time.html#time.struct_time
# datetimestamp = datetime object https://docs.python.org/3/library/datetime.html#datetime-objects
# This function returns a datetime object of the timeslot string regarding the received datetime object (dt)
# The converted datetime object has the same weekday, hour and minute as the time struct
return (datetimestamp + timedelta(timestamp.tm_wday - datetimestamp.weekday())).replace(hour=timestamp.tm_hour, minute=timestamp.tm_min)

class Timeslot(models.Model):
class Weekdays(models.TextChoices):
MON = 'Mon', _('Monday')
TUE = 'Tue', _('Tuesday')
WED = 'Wed', _('Wednesday')
THU = 'Thu', _('Thursday')
FRI = 'Fri', _('Friday')
SAT = 'Sat', _('Saturday')
SUN = 'Sun', _('Sunday')

bookable = models.ForeignKey(Bookable, on_delete=models.CASCADE)
start_time = models.TimeField(auto_now=False, auto_now_add=False)
start_weekday = models.CharField(
max_length=3,
choices=Weekdays.choices,
)
end_time = models.TimeField(auto_now=False, auto_now_add=False)
end_weekday = models.CharField(
max_length=3,
choices=Weekdays.choices,
)

def get_start(self):
return f"{self.start_weekday} {self.start_time.strftime('%H:%M')}"

def get_start_t(self):
# Returns start time as a python time struct
# https://docs.python.org/3/library/time.html#time.struct_time
return time.strptime(self.get_start(), "%a %H:%M")

def get_end(self):
return f"{self.end_weekday} {self.end_time.strftime('%H:%M')}"

def get_end_t(self):
# Returns end time as a python time struct
# https://docs.python.org/3/library/time.html#time.struct_time
return time.strptime(self.get_end(), "%a %H:%M")

def get_closest_start_datetime(self, dt):
return convert_time_to_closest_datetime(self.get_start_t(), dt)

def get_closest_end_datetime(self, dt):
return convert_time_to_closest_datetime(self.get_end_t(), dt)


class ExternalService(models.Model):
name = models.CharField(max_length=64, null=False, blank=False)
Expand All @@ -79,11 +188,6 @@ def notify(self, session):
# Avoid crashes from this
logger.error('Error notifying external service "{}" with URL {}: {}'.format(self.name, self.callback_url, str(e)))

# class TimeSlot(models.Model):
# start = models.CharField(null=False)
# end = models.CharField(max_length=8, null=False)
# bookable = models.ForeignKey(max_length=8, Bookable, on_delete=models.CASCADE)


class RepeatedBookingGroup(models.Model):
name = models.CharField(max_length=128)
Expand Down Expand Up @@ -136,6 +240,14 @@ def clean(self):
if self.end <= self.start:
raise ValidationError(_("Booking cannot end before it begins"))

# Check that the booking's start and end times are on the defined booking slots, if the bookable has such defined
if self.bookable.has_bookable_timeslots():
start_times, end_times = self.bookable.get_bookable_timeslots_by_start_and_end_time()
if self.start.strftime("%a %H:%M") not in start_times:
raise ValidationError(_("Booking start time is not according to the predefined booking timeslots."))
if self.end.strftime("%a %H:%M") not in end_times:
raise ValidationError(_("Booking end time is not according to the predefined booking timeslots."))

# Check that booking group is allowed
if self.booking_group and self.booking_group not in self.get_booker_groups():
raise ValidationError(_("Group booking is not allowed with the provided user and group"))
10 changes: 9 additions & 1 deletion fars/booking/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.http import HttpResponse, JsonResponse, Http404
from django.contrib.auth.models import User
from booking.models import Booking, Bookable
from booking.models import Booking, Bookable, Timeslot
from booking.forms import BookingForm, RepeatingBookingForm, CustomLoginForm
from booking.metadata_forms import get_form_class
from datetime import datetime, timedelta
import time
import dateutil.parser
from django.utils.translation import gettext as _
from django.db import transaction
Expand Down Expand Up @@ -102,8 +103,15 @@ def dispatch(self, request, bookable):
def get(self, request, bookable):
booking = Booking()
booking.start = dateutil.parser.parse(request.GET['st']) if 'st' in request.GET else datetime.now()
# Remove the seconds and microseconds if they are present
booking.start = booking.start.replace(second=0, microsecond=0)
booking.end = dateutil.parser.parse(request.GET['et']) if 'et' in request.GET else booking.start + timedelta(hours=1)
booking.bookable = self.context['bookable']

# if the bookable has defined bookable timeslots, move the start time and end time to the closest valid bookable timespans
if booking.bookable.has_bookable_timeslots():
booking.start, booking.end = booking.bookable.get_closest_start_and_end_datetime(booking.start, booking.end)

booking.user = request.user
form = get_form_class(booking.bookable.metadata_form)(instance=booking)
self.context['form'] = form
Expand Down