From 2bcefbf8fcc82b5148d2759ea36595ed170332b7 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Tue, 8 Dec 2020 16:27:57 +0100
Subject: [PATCH] api: add add-event endpoint (#47337)

---
 chrono/api/serializers.py | 18 +++++++++-
 chrono/api/urls.py        |  5 +++
 chrono/api/views.py       | 22 ++++++++++++
 tests/api/test_event.py   | 74 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 118 insertions(+), 1 deletion(-)

diff --git a/chrono/api/serializers.py b/chrono/api/serializers.py
index 485de7b..df42f4c 100644
--- a/chrono/api/serializers.py
+++ b/chrono/api/serializers.py
@@ -1,13 +1,13 @@
 from django.utils.translation import ugettext_lazy as _
 from rest_framework import serializers
 from rest_framework.exceptions import ValidationError
 
-from chrono.agendas.models import AbsenceReason, Booking
+from chrono.agendas.models import AbsenceReason, Booking, Event
 
 
 class StringOrListField(serializers.ListField):
     def to_internal_value(self, data):
         if isinstance(data, str):
             data = [s.strip() for s in data.split(',') if s.strip()]
         return super().to_internal_value(data)
 
@@ -128,8 +128,24 @@ class DatetimesSerializer(DateRangeSerializer):
             )
         return attrs
 
 
 class MultipleAgendasDatetimesSerializer(DatetimesSerializer):
     agendas = CommaSeparatedStringField(
         required=True, child=serializers.SlugField(max_length=160, allow_blank=False)
     )
+
+
+class EventSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Event
+        fields = [
+            'start_datetime',
+            'duration',
+            'publication_date',
+            'places',
+            'waiting_list_places',
+            'label',
+            'description',
+            'pricing',
+            'url',
+        ]
diff --git a/chrono/api/urls.py b/chrono/api/urls.py
index a1fd336..4179e66 100644
--- a/chrono/api/urls.py
+++ b/chrono/api/urls.py
@@ -59,16 +59,21 @@ urlpatterns = [
         views.event_bookings,
         name='api-event-bookings',
     ),
     url(
         r'^agenda/(?P<agenda_identifier>[\w-]+)/check/(?P<event_identifier>[\w:-]+)/$',
         views.event_check,
         name='api-event-check',
     ),
+    url(
+        r'^agenda/(?P<agenda_identifier>[\w-]+)/add-event/$',
+        views.agenda_add_event,
+        name='api-agenda-add-event',
+    ),
     url(
         r'^agenda/meetings/(?P<meeting_identifier>[\w-]+)/datetimes/$',
         views.meeting_datetimes,
         name='api-agenda-meeting-datetimes-legacy',
     ),
     url(r'^agenda/(?P<agenda_identifier>[\w-]+)/meetings/$', views.meeting_list, name='api-agenda-meetings'),
     url(
         r'^agenda/(?P<agenda_identifier>[\w-]+)/meetings/(?P<meeting_identifier>[\w-]+)/$',
diff --git a/chrono/api/views.py b/chrono/api/views.py
index f733a78..52b2567 100644
--- a/chrono/api/views.py
+++ b/chrono/api/views.py
@@ -2402,8 +2402,30 @@ class BookingsStatistics(APIView):
                     'series': series,
                 },
                 'err': 0,
             }
         )
 
 
 bookings_statistics = BookingsStatistics.as_view()
+
+
+class AgendaAddEventView(APIView):
+    permission_classes = (permissions.IsAuthenticated,)
+    serializer_class = serializers.EventSerializer
+
+    def post(self, request, agenda_identifier):
+        agenda = get_object_or_404(Agenda, slug=agenda_identifier, kind='events')
+
+        serializer = self.serializer_class(data=request.data)
+        if not serializer.is_valid():
+            return APIError(
+                _('invalid payload'), err_class='invalid payload', errors=serializer.errors
+            ).to_response()
+
+        payload = serializer.validated_data
+        event = Event.objects.create(agenda=agenda, **payload)
+        response = {'err': 0, 'event_id': event.pk}
+        return Response(response)
+
+
+agenda_add_event = AgendaAddEventView.as_view()
diff --git a/tests/api/test_event.py b/tests/api/test_event.py
index 9a6f5d6..89b048f 100644
--- a/tests/api/test_event.py
+++ b/tests/api/test_event.py
@@ -153,8 +153,82 @@ def test_event_checked(app, user):
 
     # wrong kind
     agenda.kind = 'meetings'
     agenda.save()
     app.post('/api/agenda/%s/check/%s/' % (agenda.slug, event.slug), status=404)
     agenda.kind = 'virtual'
     agenda.save()
     app.post('/api/agenda/%s/check/%s/' % (agenda.slug, event.slug), status=404)
+
+
+def test_add_event(app, user):
+    agenda = Agenda(label='Foo bar')
+    agenda.maximal_booking_delay = 0
+    agenda.save()
+
+    params = {
+        'start_datetime': '2020-12-08 15:38',
+        'places': 10,
+        'slug': 123,
+    }
+    api_url = '/api/agenda/%s/add-event/' % (agenda.slug)
+    app.authorization = ('Basic', ('john.doe', 'password'))
+
+    # add an event
+    resp = app.post(api_url, params=params)
+    assert not resp.json['err']
+    event_id = resp.json['event_id']
+    assert Event.objects.filter(agenda=agenda).count() == 1
+    event = Event.objects.filter(agenda=agenda, id=event_id)[0]
+    assert str(event.start_datetime) == '2020-12-08 14:38:00+00:00'
+    assert str(event.start_datetime.tzinfo) == 'UTC'
+    assert event.places == 10
+    assert event.publication_date is None
+
+    # add with a description
+    params = {
+        'start_datetime': '2020-12-08 15:38',
+        'publication_date': '2020-05-11',
+        'description': 'A description',
+        'places': 11,
+    }
+    resp = app.post(api_url, params=params)
+    event_id = resp.json['event_id']
+    event = Event.objects.filter(agenda=agenda, id=event_id)[0]
+    assert event.description == 'A description'
+    assert event.publication_date == datetime.date(2020, 5, 11)
+
+    # add with errors in datetime parts
+    params = {
+        'start_datetime': '2020-12-08 minuit',
+        'places': 10,
+    }
+    resp = app.post(api_url, params=params, status=200)
+    assert resp.json['err']
+    assert resp.json['err_desc'] == 'invalid payload'
+    assert 'Datetime has wrong format' in resp.json['errors']['start_datetime'][0]
+    assert Event.objects.filter(agenda=agenda).count() == 2
+
+
+def test_add_event_on_missing_agenda(app, user):
+    agenda = Agenda(label='Foo bar Meeting', kind='meetings')
+    agenda.save()
+    api_url = '/api/agenda/%s/add-event/' % ('999')
+
+    # no authentication
+    resp = app.post(api_url, status=401)
+    assert resp.json['detail'] == 'Authentication credentials were not provided.'
+
+    # wrong password
+    app.authorization = ('Basic', ('john.doe', 'wrong'))
+    resp = app.post(api_url, status=401)
+    assert resp.json['detail'] == 'Invalid username/password.'
+
+    # missing agenda
+    app.authorization = ('Basic', ('john.doe', 'password'))
+    resp = app.post(api_url, status=404)
+    assert resp.json['detail'] == 'Not found.'
+
+    # meeting agenda
+    api_url = '/api/agenda/%s/add-event/' % (agenda.slug)
+    resp = app.post(api_url, status=404)
+    assert resp.json['detail'] == 'Not found.'
-- 
2.30.2

