From 5eb0174347d9af9fbd0bf68910df21a3e3f53638 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/urls.py  |  5 +++
 chrono/api/views.py | 40 ++++++++++++++++++++++++
 tests/test_api.py   | 74 +++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 119 insertions(+)

diff --git a/chrono/api/urls.py b/chrono/api/urls.py
index e2f2df6..b995031 100644
--- a/chrono/api/urls.py
+++ b/chrono/api/urls.py
@@ -33,16 +33,21 @@ urlpatterns = [
         views.slot_status,
         name='api-event-status',
     ),
     url(
         r'^agenda/(?P<agenda_identifier>[\w-]+)/bookings/(?P<event_identifier>[\w-]+)/$',
         views.slot_bookings,
         name='api-event-bookings',
     ),
+    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 d134495..b94ba81 100644
--- a/chrono/api/views.py
+++ b/chrono/api/views.py
@@ -1483,8 +1483,48 @@ class BookingICS(APIView):
 
     def get(self, request, booking_pk=None, format=None):
         booking = get_object_or_404(Booking, id=booking_pk)
         response = HttpResponse(booking.get_ics(request), content_type='text/calendar')
         return response
 
 
 booking_ics = BookingICS.as_view()
+
+
+class EventSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = Event
+        fields = [
+            'start_datetime',
+            'duration',
+            'publication_date',
+            'places',
+            'waiting_list_places',
+            'label',
+            'description',
+            'pricing',
+            'url',
+        ]
+
+
+class AgendaAddEventView(APIView):
+    permission_classes = (permissions.IsAuthenticated, )
+    serializer_class = 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/test_api.py b/tests/test_api.py
index b486cae..9266b89 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -4573,8 +4573,82 @@ def test_meetings_and_virtual_datetimes_date_filter(app):
     agenda_foo.save()
     resp = app.get(foo_api_url, params=params)
     assert len(resp.json['data']) == 16
     # also on virtual agenda
     virtual_agenda.maximal_booking_delay = 5
     virtual_agenda.save()
     resp = app.get(virtual_api_url, params=params)
     assert len(resp.json['data']) == 16
+
+
+def test_add_event(app, user):
+    agenda = Agenda(label=u'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=u'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.29.2

