chrono/chrono/api/views.py

345 lines
13 KiB
Python
Raw Normal View History

# 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/>.
import datetime
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.timezone import now, make_aware, localtime
2016-07-20 13:29:09 +02:00
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
class Agendas(GenericAPIView):
permission_classes = ()
def get(self, request, format=None):
agendas = []
for agenda in Agenda.objects.all().order_by('label'):
agenda_data = {
'id': agenda.id,
'slug': agenda.slug,
'text': agenda.label,
'kind': agenda.kind,
}
if agenda.kind == 'events':
agenda_data['api'] = {
'datetimes_url': request.build_absolute_uri(
reverse('api-agenda-datetimes',
kwargs={'agenda_identifier': agenda.slug}))
}
elif agenda.kind == 'meetings':
agenda_data['api'] = {
'meetings_url': request.build_absolute_uri(
reverse('api-agenda-meetings',
kwargs={'agenda_identifier': agenda.slug}))
}
agendas.append(agenda_data)
return Response({'data': agendas})
agendas = Agendas.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')
kwargs = {}
if agenda.minimal_booking_delay:
kwargs['start_datetime__gte'] = localtime(now() + datetime.timedelta(days=agenda.minimal_booking_delay)).date()
else:
# if there's no minimal booking delay we still don't want to allow
# booking for past events.
kwargs['start_datetime__gte'] = localtime(now())
if agenda.maximal_booking_delay:
kwargs['start_datetime__lt'] = localtime(now() + datetime.timedelta(days=agenda.maximal_booking_delay)).date()
entries = Event.objects.filter(agenda=agenda).filter(**kwargs)
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()
2016-02-13 16:52:04 +01:00
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)
2016-10-29 20:39:52 +02:00
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(agenda=agenda):
all_time_slots.extend(time_period.get_time_slots(
min_datetime=min_datetime,
max_datetime=max_datetime,
meeting_type=meeting_type))
busy_time_slots = Event.objects.filter(agenda=agenda,
start_datetime__gte=min_datetime,
start_datetime__lte=max_datetime + datetime.timedelta(meeting_type.duration))
busy_time_slots = list(busy_time_slots)
entries = []
# there's room for optimisations here, for a start both lists
# could be presorted and past busy time slots removed along the way.
for time_slot in all_time_slots:
if time_slot.start_datetime < now_datetime:
continue
if any((x for x in busy_time_slots if x.full and time_slot.intersects(x))):
continue
entries.append(time_slot)
entries.sort(key=lambda x: x.start_datetime)
response = {'data': [{'id': x.id,
'datetime': localtime(x.start_datetime).strftime('%Y-%m-%d %H:%M:%S'),
'text': unicode(x),
'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)
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()
2016-02-13 16:52:04 +01:00
class SlotSerializer(serializers.Serializer):
pass
class Fillslot(GenericAPIView):
serializer_class = SlotSerializer
permission_classes = (permissions.IsAuthenticated,)
2016-02-13 16:52:04 +01:00
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 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, created = Event.objects.get_or_create(agenda=agenda,
meeting_type_id=meeting_type_id,
start_datetime=start_datetime,
defaults={'full': False, 'places': 1})
if created:
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.waiting_list >= event.waiting_list_places:
return Response({'err': 1, 'reason': 'sold out'})
if event.booked_places >= 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
else:
if event.booked_places >= event.places:
return Response({'err': 1, 'reason': 'sold out'})
new_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': reverse('api-cancel-booking', kwargs={'booking_pk': new_booking.id})
}
}
if new_booking.in_waiting_list:
response['api']['accept_url'] = reverse('api-accept-booking',
kwargs={'booking_pk': new_booking.id})
2016-02-13 16:52:04 +01:00
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()