From 6e577c7036114c3ff16c198953ce80bf06742723 Mon Sep 17 00:00:00 2001
From: Valentin Deniaud <vdeniaud@entrouvert.com>
Date: Mon, 13 Dec 2021 12:13:01 +0100
Subject: [PATCH 2/2] fix order for subscriptions in recurring events list

---
 chrono/api/views.py         | 16 ++++++++++++++--
 tests/api/test_datetimes.py | 33 ++++++++++++++++++++++++++++++---
 2 files changed, 44 insertions(+), 5 deletions(-)

diff --git a/chrono/api/views.py b/chrono/api/views.py
index 12828f93..4438560e 100644
--- a/chrono/api/views.py
+++ b/chrono/api/views.py
@@ -1080,7 +1080,7 @@ class RecurringEventsList(APIView):
             raise APIErrorBadRequest(N_('invalid payload'), errors=serializer.errors)
         data = serializer.validated_data
 
-        agendas = Agenda.prefetch_recurring_events(data['agendas'])
+        agendas = Agenda.prefetch_recurring_events(data['agendas']).select_related('category')
         events = []
         for agenda in agendas:
             for event in agenda.get_open_recurring_events():
@@ -1093,7 +1093,19 @@ class RecurringEventsList(APIView):
             agenda_querystring_indexes = {
                 agenda_slug: i for i, agenda_slug in enumerate(data['agenda_slugs'])
             }
-            events.sort(key=lambda event: (event.day, agenda_querystring_indexes[event.agenda.slug]))
+            events.sort(
+                key=lambda event: (event.day, agenda_querystring_indexes[event.agenda.slug], event.slug)
+            )
+        elif 'subscribed' in request.query_params and data['subscribed'] != ['all']:
+            category_querystring_indexes = {category: i for i, category in enumerate(data['subscribed'])}
+            events.sort(
+                key=lambda event: (
+                    event.day,
+                    category_querystring_indexes[event.agenda.category.slug],
+                    event.agenda.slug,
+                    event.slug,
+                )
+            )
 
         return Response(
             {
diff --git a/tests/api/test_datetimes.py b/tests/api/test_datetimes.py
index efa31948..770ad929 100644
--- a/tests/api/test_datetimes.py
+++ b/tests/api/test_datetimes.py
@@ -1448,18 +1448,30 @@ def test_recurring_events_api_list_multiple_agendas(app):
 
 @pytest.mark.freeze_time('2021-09-06 12:00')
 def test_recurring_events_api_list_multiple_agendas_queries(app):
+    category = Category.objects.create(label='Category A')
     for i in range(20):
-        agenda = Agenda.objects.create(slug=f'{i}', kind='events')
+        agenda = Agenda.objects.create(slug=f'{i}', kind='events', category=category)
         Desk.objects.create(agenda=agenda, slug='_exceptions_holder')
         start, end = now(), now() + datetime.timedelta(days=30)
         Event.objects.create(
             start_datetime=start, places=2, recurrence_end_date=end, recurrence_days=[1, 2], agenda=agenda
         )
+        Subscription.objects.create(
+            agenda=agenda,
+            user_external_id='xxx',
+            date_start=now(),
+            date_end=now() + datetime.timedelta(days=60),
+        )
     with CaptureQueriesContext(connection) as ctx:
         resp = app.get('/api/agendas/recurring-events/?agendas=%s' % ','.join(str(i) for i in range(20)))
         assert len(resp.json['data']) == 40
         assert len(ctx.captured_queries) == 3
 
+    with CaptureQueriesContext(connection) as ctx:
+        resp = app.get('/api/agendas/recurring-events/?subscribed=category-a&user_external_id=xxx')
+        assert len(resp.json['data']) == 40
+        assert len(ctx.captured_queries) == 3
+
 
 @pytest.mark.freeze_time('2021-09-06 12:00')
 def test_recurring_events_api_list_subscribed(app, user):
@@ -1472,7 +1484,6 @@ def test_recurring_events_api_list_subscribed(app, user):
         start_datetime=now(),
         recurrence_days=[0, 1, 3, 4],  # Monday, Tuesday, Thursday, Friday
         places=2,
-        waiting_list_places=1,
         agenda=first_agenda,
         recurrence_end_date=now() + datetime.timedelta(days=364),
     )
@@ -1481,7 +1492,6 @@ def test_recurring_events_api_list_subscribed(app, user):
         start_datetime=now(),
         recurrence_days=[6],
         places=2,
-        waiting_list_places=1,
         agenda=second_agenda,
         recurrence_end_date=now() + datetime.timedelta(days=364),
     )
@@ -1528,6 +1538,23 @@ def test_recurring_events_api_list_subscribed(app, user):
     resp = app.get('/api/agendas/recurring-events/?user_external_id=yyy&subscribed=all')
     assert len(resp.json['data']) == 1
 
+    # sorting depends on querystring order
+    Event.objects.create(
+        slug='event',
+        start_datetime=now(),
+        recurrence_days=[0],
+        places=2,
+        agenda=second_agenda,
+        recurrence_end_date=now() + datetime.timedelta(days=364),
+    )
+    resp = app.get('/api/agendas/recurring-events/?subscribed=category-a,category-b&user_external_id=xxx')
+    event_ids = [x['id'] for x in resp.json['data']]
+    assert event_ids.index('first-agenda@event:0') < event_ids.index('second-agenda@event:0')
+
+    resp = app.get('/api/agendas/recurring-events/?subscribed=category-b,category-a&user_external_id=xxx')
+    event_ids = [x['id'] for x in resp.json['data']]
+    assert event_ids.index('first-agenda@event:0') > event_ids.index('second-agenda@event:0')
+
 
 @pytest.mark.freeze_time('2021-05-06 14:00')
 def test_datetimes_multiple_agendas(app):
-- 
2.30.2

