431 lines
16 KiB
Python
431 lines
16 KiB
Python
# chrono - agendas system
|
|
# Copyright (C) 2016 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
from collections import defaultdict
|
|
import datetime
|
|
import operator
|
|
|
|
from intervaltree import IntervalTree
|
|
|
|
from django.core.urlresolvers import reverse
|
|
from django.http import Http404
|
|
from django.shortcuts import get_object_or_404
|
|
from django.utils.dateparse import parse_date
|
|
from django.utils.timezone import now, make_aware, localtime
|
|
|
|
from rest_framework import permissions, serializers
|
|
from rest_framework.generics import GenericAPIView
|
|
from rest_framework.response import Response
|
|
from rest_framework.views import APIView
|
|
|
|
from ..agendas.models import (Agenda, Event, Booking, MeetingType,
|
|
TimePeriod, Desk)
|
|
|
|
|
|
def get_open_slots(agenda, meeting_type):
|
|
min_datetime = now() + datetime.timedelta(days=agenda.minimal_booking_delay)
|
|
max_datetime = now() + datetime.timedelta(days=agenda.maximal_booking_delay)
|
|
time_period_filters = {
|
|
'min_datetime': min_datetime,
|
|
'max_datetime': max_datetime,
|
|
'meeting_type': meeting_type
|
|
}
|
|
|
|
open_slots_by_desk = defaultdict(lambda: IntervalTree())
|
|
for time_period in TimePeriod.objects.filter(desk__agenda=agenda):
|
|
for slot in time_period.get_time_slots(**time_period_filters):
|
|
open_slots_by_desk[time_period.desk_id].addi(slot.start_datetime, slot.end_datetime, slot.desk)
|
|
|
|
for event in agenda.event_set.filter(
|
|
agenda=agenda, start_datetime__gte=min_datetime,
|
|
start_datetime__lte=max_datetime + datetime.timedelta(meeting_type.duration)).select_related(
|
|
'meeting_type').extra(
|
|
select={
|
|
'booking_count': """SELECT COUNT(*) FROM agendas_booking
|
|
WHERE agendas_booking.event_id = agendas_event.id
|
|
AND agendas_booking.cancellation_datetime IS NOT NULL"""}):
|
|
if event.booking_count:
|
|
continue
|
|
open_slots_by_desk[event.desk_id].remove_overlap(event.start_datetime, event.end_datetime)
|
|
|
|
open_slots = reduce(operator.__or__, open_slots_by_desk.values())
|
|
return open_slots
|
|
|
|
|
|
def get_agenda_detail(request, agenda):
|
|
agenda_detail = {
|
|
'id': agenda.id,
|
|
'slug': agenda.slug,
|
|
'text': agenda.label,
|
|
'kind': agenda.kind,
|
|
}
|
|
|
|
if agenda.kind == 'events':
|
|
agenda_detail['api'] = {
|
|
'datetimes_url': request.build_absolute_uri(
|
|
reverse('api-agenda-datetimes',
|
|
kwargs={'agenda_identifier': agenda.slug}))
|
|
}
|
|
elif agenda.kind == 'meetings':
|
|
agenda_detail['api'] = {
|
|
'meetings_url': request.build_absolute_uri(
|
|
reverse('api-agenda-meetings',
|
|
kwargs={'agenda_identifier': agenda.slug}))
|
|
}
|
|
|
|
return agenda_detail
|
|
|
|
|
|
class Agendas(GenericAPIView):
|
|
permission_classes = ()
|
|
|
|
def get(self, request, format=None):
|
|
agendas = [get_agenda_detail(request, agenda)
|
|
for agenda in Agenda.objects.all().order_by('label')]
|
|
return Response({'data': agendas})
|
|
|
|
agendas = Agendas.as_view()
|
|
|
|
|
|
class AgendaDetail(GenericAPIView):
|
|
'''
|
|
Retrieve an agenda instance.
|
|
'''
|
|
permission_classes = ()
|
|
|
|
def get(self, request, agenda_identifier):
|
|
agenda = get_object_or_404(Agenda, slug=agenda_identifier)
|
|
return Response({'data': get_agenda_detail(request, agenda)})
|
|
|
|
agenda_detail = AgendaDetail.as_view()
|
|
|
|
|
|
class Datetimes(GenericAPIView):
|
|
permission_classes = ()
|
|
|
|
def get(self, request, agenda_identifier=None, format=None):
|
|
try:
|
|
agenda = Agenda.objects.get(slug=agenda_identifier)
|
|
except Agenda.DoesNotExist:
|
|
try:
|
|
# legacy access by agenda id
|
|
agenda = Agenda.objects.get(id=int(agenda_identifier))
|
|
except (ValueError, Agenda.DoesNotExist):
|
|
raise Http404()
|
|
if agenda.kind != 'events':
|
|
raise Http404('agenda found, but it was not an events agenda')
|
|
|
|
entries = Event.objects.filter(agenda=agenda)
|
|
|
|
# we never want to allow booking for past events.
|
|
entries = entries.filter(start_datetime__gte=localtime(now()))
|
|
|
|
if agenda.minimal_booking_delay:
|
|
entries = entries.filter(
|
|
start_datetime__gte=localtime(now() + datetime.timedelta(days=agenda.minimal_booking_delay)).date())
|
|
|
|
if agenda.maximal_booking_delay:
|
|
entries = entries.filter(
|
|
start_datetime__lt=localtime(now() + datetime.timedelta(days=agenda.maximal_booking_delay)).date())
|
|
|
|
if 'date_start' in request.GET:
|
|
entries = entries.filter(start_datetime__gte=parse_date(request.GET['date_start']))
|
|
|
|
if 'date_end' in request.GET:
|
|
entries = entries.filter(start_datetime__lt=parse_date(request.GET['date_end']))
|
|
|
|
response = {'data': [{'id': x.id,
|
|
'text': unicode(x),
|
|
'datetime': localtime(x.start_datetime).strftime('%Y-%m-%d %H:%M:%S'),
|
|
'disabled': bool(x.full),
|
|
'api': {
|
|
'fillslot_url': request.build_absolute_uri(
|
|
reverse('api-fillslot',
|
|
kwargs={
|
|
'agenda_identifier': agenda.slug,
|
|
'event_pk': x.id,
|
|
})),
|
|
},
|
|
} for x in entries]}
|
|
return Response(response)
|
|
|
|
datetimes = Datetimes.as_view()
|
|
|
|
|
|
class MeetingDatetimes(GenericAPIView):
|
|
permission_classes = ()
|
|
|
|
def get(self, request, agenda_identifier=None, meeting_identifier=None, format=None):
|
|
try:
|
|
if agenda_identifier is None:
|
|
# legacy access by meeting id
|
|
meeting_type = MeetingType.objects.get(id=meeting_identifier)
|
|
else:
|
|
meeting_type = MeetingType.objects.get(slug=meeting_identifier,
|
|
agenda__slug=agenda_identifier)
|
|
except (ValueError, MeetingType.DoesNotExist):
|
|
raise Http404()
|
|
|
|
agenda = meeting_type.agenda
|
|
|
|
now_datetime = now()
|
|
min_datetime = now() + datetime.timedelta(days=agenda.minimal_booking_delay)
|
|
max_datetime = now() + datetime.timedelta(days=agenda.maximal_booking_delay)
|
|
|
|
all_time_slots = []
|
|
for time_period in TimePeriod.objects.filter(desk__agenda=agenda):
|
|
all_time_slots.extend(time_period.get_time_slots(min_datetime=min_datetime, max_datetime=max_datetime,
|
|
meeting_type=meeting_type))
|
|
|
|
open_slots = get_open_slots(agenda, meeting_type)
|
|
open_entries = {}
|
|
closed_entries = {}
|
|
for time_slot in all_time_slots:
|
|
if time_slot.start_datetime < now_datetime:
|
|
continue
|
|
key = '%s-%s' % (time_slot.start_datetime, time_slot.end_datetime)
|
|
if open_slots.search(time_slot.start_datetime, time_slot.end_datetime, strict=True):
|
|
time_slot.full = False
|
|
open_entries[key] = time_slot
|
|
else:
|
|
time_slot.full = True
|
|
closed_entries[key] = time_slot
|
|
|
|
closed_entries.update(open_entries)
|
|
entries = sorted(closed_entries.values(), key=lambda x: x.start_datetime)
|
|
|
|
fake_event_pk = '__event_id__'
|
|
fillslot_url = request.build_absolute_uri(
|
|
reverse('api-fillslot',
|
|
kwargs={
|
|
'agenda_identifier': agenda.slug,
|
|
'event_pk': fake_event_pk,
|
|
}))
|
|
|
|
response = {'data': [{'id': x.id,
|
|
'datetime': localtime(x.start_datetime).strftime('%Y-%m-%d %H:%M:%S'),
|
|
'text': unicode(x),
|
|
'disabled': bool(x.full),
|
|
'api': {
|
|
'fillslot_url': fillslot_url.replace(fake_event_pk, str(x.id)),
|
|
},
|
|
} for x in entries]}
|
|
return Response(response)
|
|
|
|
meeting_datetimes = MeetingDatetimes.as_view()
|
|
|
|
|
|
class MeetingList(GenericAPIView):
|
|
permission_classes = ()
|
|
|
|
def get(self, request, agenda_identifier=None, format=None):
|
|
try:
|
|
agenda = Agenda.objects.get(slug=agenda_identifier)
|
|
except Agenda.DoesNotExist:
|
|
raise Http404()
|
|
if agenda.kind != 'meetings':
|
|
raise Http404('agenda found, but it was not a meetings agenda')
|
|
|
|
meeting_types = []
|
|
for meeting_type in agenda.meetingtype_set.all():
|
|
meeting_types.append({
|
|
'text': meeting_type.label,
|
|
'id': meeting_type.slug,
|
|
'api': {
|
|
'datetimes_url': request.build_absolute_uri(
|
|
reverse('api-agenda-meeting-datetimes',
|
|
kwargs={'agenda_identifier': agenda.slug,
|
|
'meeting_identifier': meeting_type.slug})),
|
|
}
|
|
})
|
|
|
|
return Response({'data': meeting_types})
|
|
|
|
meeting_list = MeetingList.as_view()
|
|
|
|
|
|
class SlotSerializer(serializers.Serializer):
|
|
pass
|
|
|
|
|
|
class Fillslot(GenericAPIView):
|
|
serializer_class = SlotSerializer
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
def post(self, request, agenda_identifier=None, event_pk=None, format=None):
|
|
try:
|
|
agenda = Agenda.objects.get(slug=agenda_identifier)
|
|
except Agenda.DoesNotExist:
|
|
try:
|
|
# legacy access by agenda id
|
|
agenda = Agenda.objects.get(id=int(agenda_identifier))
|
|
except (ValueError, Agenda.DoesNotExist):
|
|
raise Http404()
|
|
|
|
if 'count' in request.GET:
|
|
places_count = int(request.GET['count'])
|
|
else:
|
|
places_count = 1
|
|
|
|
if agenda.kind == 'meetings':
|
|
# event is actually a timeslot, convert to a real event object
|
|
meeting_type_id, start_datetime_str = event_pk.split(':')
|
|
start_datetime = make_aware(datetime.datetime.strptime(
|
|
start_datetime_str, '%Y-%m-%d-%H%M'))
|
|
|
|
event = Event.objects.create(agenda=agenda,
|
|
meeting_type_id=meeting_type_id,
|
|
start_datetime=start_datetime,
|
|
full=False, places=1)
|
|
|
|
available_desk = None
|
|
|
|
open_slots = get_open_slots(agenda, MeetingType.objects.get(id=meeting_type_id))
|
|
slot = open_slots[event.start_datetime:event.end_datetime]
|
|
if slot:
|
|
available_desk = slot.pop().data
|
|
|
|
if not available_desk:
|
|
return Response({'err': 1, 'reason': 'no more desk available'})
|
|
|
|
event.desk = available_desk
|
|
event.save()
|
|
event_pk = event.id
|
|
|
|
event = Event.objects.filter(id=event_pk)[0]
|
|
new_booking = Booking(event_id=event_pk, extra_data=request.data)
|
|
|
|
if event.waiting_list_places:
|
|
if (event.booked_places + places_count) > event.places or event.waiting_list:
|
|
# if this is full or there are people waiting, put new bookings
|
|
# in the waiting list.
|
|
new_booking.in_waiting_list = True
|
|
|
|
if (event.waiting_list + places_count) > event.waiting_list_places:
|
|
return Response({'err': 1, 'reason': 'sold out'})
|
|
|
|
else:
|
|
if (event.booked_places + places_count) > event.places:
|
|
return Response({'err': 1, 'reason': 'sold out'})
|
|
|
|
new_booking.save()
|
|
for i in range(places_count-1):
|
|
additional_booking = Booking(event_id=event_pk, extra_data=request.data)
|
|
additional_booking.in_waiting_list = new_booking.in_waiting_list
|
|
additional_booking.primary_booking = new_booking
|
|
additional_booking.save()
|
|
|
|
response = {
|
|
'err': 0,
|
|
'in_waiting_list': new_booking.in_waiting_list,
|
|
'booking_id': new_booking.id,
|
|
'datetime': localtime(event.start_datetime),
|
|
'api': {
|
|
'cancel_url': request.build_absolute_uri(
|
|
reverse('api-cancel-booking', kwargs={'booking_pk': new_booking.id}))
|
|
}
|
|
}
|
|
if new_booking.in_waiting_list:
|
|
response['api']['accept_url'] = request.build_absolute_uri(
|
|
reverse('api-accept-booking', kwargs={'booking_pk': new_booking.id}))
|
|
|
|
return Response(response)
|
|
|
|
fillslot = Fillslot.as_view()
|
|
|
|
|
|
class BookingAPI(APIView):
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
def initial(self, request, *args, **kwargs):
|
|
super(BookingAPI, self).initial(request, *args, **kwargs)
|
|
self.booking = Booking.objects.get(id=kwargs.get('booking_pk'),
|
|
cancellation_datetime__isnull=True)
|
|
|
|
def delete(self, request, *args, **kwargs):
|
|
self.booking.cancel()
|
|
response = {'err': 0, 'booking_id': self.booking.id}
|
|
return Response(response)
|
|
|
|
booking = BookingAPI.as_view()
|
|
|
|
|
|
class CancelBooking(APIView):
|
|
'''
|
|
Cancel a booking.
|
|
|
|
It will return an error (code 1) if the booking was already cancelled.
|
|
'''
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
def post(self, request, booking_pk=None, format=None):
|
|
booking = get_object_or_404(Booking, id=booking_pk)
|
|
if booking.cancellation_datetime:
|
|
response = {'err': 1, 'reason': 'already cancelled'}
|
|
return Response(response)
|
|
booking.cancel()
|
|
response = {'err': 0, 'booking_id': booking.id}
|
|
return Response(response)
|
|
|
|
cancel_booking = CancelBooking.as_view()
|
|
|
|
|
|
class AcceptBooking(APIView):
|
|
'''
|
|
Accept a booking currently in the waiting list.
|
|
|
|
It will return error codes if the booking was cancelled before (code 1) and
|
|
if the booking was not in waiting list (code 2).
|
|
'''
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
def post(self, request, booking_pk=None, format=None):
|
|
booking = get_object_or_404(Booking, id=booking_pk)
|
|
if booking.cancellation_datetime:
|
|
response = {'err': 1, 'reason': 'booking is cancelled'}
|
|
return Response(response)
|
|
if not booking.in_waiting_list:
|
|
response = {'err': 2, 'reason': 'booking is not in waiting list'}
|
|
return Response(response)
|
|
booking.accept()
|
|
response = {'err': 0, 'booking_id': booking.id}
|
|
return Response(response)
|
|
|
|
accept_booking = AcceptBooking.as_view()
|
|
|
|
|
|
class SlotStatus(GenericAPIView):
|
|
serializer_class = SlotSerializer
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
def get(self, request, agenda_identifier=None, event_pk=None, format=None):
|
|
event = get_object_or_404(Event, id=event_pk)
|
|
response = {
|
|
'err': 0,
|
|
'places': {
|
|
'total': event.places,
|
|
'reserved': event.booked_places,
|
|
'available': event.places - event.booked_places,
|
|
}
|
|
}
|
|
if event.waiting_list_places:
|
|
response['places']['waiting_list_total'] = event.waiting_list_places
|
|
response['places']['waiting_list_reserved'] = event.waiting_list
|
|
response['places']['waiting_list_available'] = (event.waiting_list_places - event.waiting_list)
|
|
return Response(response)
|
|
|
|
slot_status = SlotStatus.as_view()
|