From 61378354ae59cf72f777752d51a43cd4fc1658ef 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 |  25 ++++++++-
 chrono/api/urls.py        |   5 ++
 chrono/api/views.py       |  22 ++++++++
 tests/api/test_event.py   | 105 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 156 insertions(+), 1 deletion(-)

diff --git a/chrono/api/serializers.py b/chrono/api/serializers.py
index 485de7b..8ff9a63 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,31 @@ 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):
+    recurrence_days = CommaSeparatedStringField(
+        required=False, child=serializers.SlugField(max_length=160, allow_blank=False)
+    )
+
+    class Meta:
+        model = Event
+        fields = [
+            'start_datetime',
+            'recurrence_days',
+            'recurrence_week_interval',
+            'recurrence_end_date',
+            '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..2e596c3 100644
--- a/tests/api/test_event.py
+++ b/tests/api/test_event.py
@@ -153,8 +153,113 @@ 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):
+    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.'
+
+    app.authorization = ('Basic', ('john.doe', 'password'))
+
+    # missing agenda
+    resp = app.post(api_url, status=404)
+    assert resp.json['detail'] == 'Not found.'
+
+    # using meeting agenda
+    meeting_agenda = Agenda(label='Foo bar Meeting', kind='meetings')
+    meeting_agenda.save()
+    api_url = '/api/agenda/%s/add-event/' % (meeting_agenda.slug)
+    resp = app.post(api_url, status=404)
+    assert resp.json['detail'] == 'Not found.'
+
+    agenda = Agenda(label='Foo bar')
+    agenda.maximal_booking_delay = 0
+    agenda.save()
+    api_url = '/api/agenda/%s/add-event/' % (agenda.slug)
+
+    # missing fields
+    resp = app.post(api_url, status=200)
+    assert resp.json['err']
+    assert resp.json['errors'] == {
+        'start_datetime': ['This field is required.'],
+        'places': ['This field is required.'],
+    }
+
+    # add with errors in datetime parts
+    params = {
+        'start_datetime': '2021-11-15 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]
+
+    # add an event
+    params = {
+        'start_datetime': '2021-11-15 15:38',
+        'places': 10,
+    }
+    resp = app.post(api_url, params=params)
+    assert not resp.json['err']
+    event_id = resp.json['event_id']
+    event = Event.objects.filter(agenda=agenda).get(id=event_id)
+    assert event.slug == 'foo-bar-event'
+    assert str(event.start_datetime) == '2021-11-15 14:38:00+00:00'
+    assert str(event.start_datetime.tzinfo) == 'UTC'
+    assert event.places == 10
+    assert event.publication_date is None
+
+    # add with almost all optional managed fields
+    params = {
+        'start_datetime': '2021-11-15 15:38',
+        'duration': 42,
+        'publication_date': '2021-09-20',
+        'places': 11,
+        'waiting_list_places': 3,
+        'label': 'EO camp',
+        'description': 'An event',
+        'pricing': 'free',
+        'url': 'http://example.org/foo/bar/?',
+    }
+    resp = app.post(api_url, params=params)
+    event_id = resp.json['event_id']
+    event = Event.objects.filter(agenda=agenda).get(id=event_id)
+    assert event.slug == 'eo-camp'
+    assert event.duration == 42
+    assert event.waiting_list_places == 3
+    assert event.label == 'EO camp'
+    assert event.description == 'An event'
+    assert event.pricing == 'free'
+    assert event.url == 'http://example.org/foo/bar/?'
+
+    # add a recurrent event
+    params = {
+        'start_datetime': '2021-11-15 15:38',
+        'places': 1,
+        'recurrence_days': '0,3,5',
+        'recurrence_week_interval': '2',
+        'recurrence_end_date': '2022-11-29',
+        'description': 'A recurrent event',
+    }
+    resp = app.post(api_url, params=params)
+    event_id = resp.json['event_id']
+    event = Event.objects.filter(agenda=agenda).get(id=event_id)
+    assert event.slug == 'foo-bar-event-1'
+    assert event.description == 'A recurrent event'
+    assert event.recurrence_days == [0, 3, 5]
+    assert event.recurrence_week_interval == 2
+    assert event.recurrence_end_date == datetime.date(2022, 11, 29)
-- 
2.30.2

