From 6db3a2fb68a082935c8d97f3e8aa99057ae61400 Mon Sep 17 00:00:00 2001
From: Eva Bardou <ebardou@teklia.com>
Date: Mon, 30 Nov 2020 17:56:17 +0100
Subject: [PATCH] Refactor selected elements deletion endpoint

---
 arkindex/documents/api/elements.py | 23 +++++++++++++++++------
 arkindex/project/api_v1.py         |  2 +-
 2 files changed, 18 insertions(+), 7 deletions(-)

diff --git a/arkindex/documents/api/elements.py b/arkindex/documents/api/elements.py
index 2d4e56cbb8..e6900c8f4b 100644
--- a/arkindex/documents/api/elements.py
+++ b/arkindex/documents/api/elements.py
@@ -1170,12 +1170,23 @@ class ElementBulkCreate(CreateAPIView):
         return [{'id': element_data['element'].id} for element_data in elements]
 
 
-class CorpusDeleteSelection(ElementsListMixin, SelectionMixin, DestroyAPIView):
+class CorpusDeleteSelection(SelectionMixin, DestroyAPIView):
     """
-    Delete selected elements on a corpus
+    Delete all selected elements on a corpus
     """
+    serializer_class = CorpusSerializer
+    openapi_overrides = {
+        'operationId': 'DeleteCorpusSelection',
+        'tags': ['elements']
+    }
 
-    def get_queryset(self):
-        # Should not be possible due to the URL
-        assert self.selected_corpus, 'Missing corpus ID'
-        return self.get_selection(corpus_id=self.selected_corpus.id)
+    def delete(self, request, *args, **kwargs):
+        selected_elements = self.get_selection(corpus_id=self.kwargs['pk'])
+        if not selected_elements.exists():
+            raise NotFound
+
+        for batch in range(0, selected_elements.count(), 50):
+            queryset = Element.objects.filter(id__in=list(selected_elements[batch:batch + 50].values_list('id', flat=True)))
+            element_trash(queryset, user_id=self.request.user.id)
+
+        return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/arkindex/project/api_v1.py b/arkindex/project/api_v1.py
index eab6c01e1d..57749b163d 100644
--- a/arkindex/project/api_v1.py
+++ b/arkindex/project/api_v1.py
@@ -145,7 +145,7 @@ api = [
     path('corpus/<uuid:pk>/ml-stats/', CorpusMLStats.as_view(), name='corpus-ml-stats'),
     path('corpus/<uuid:pk>/allowed-metadata/', CorpusAllowedMetaData.as_view(), name='corpus-allowed-metadata'),
     path('corpus/<uuid:pk>/versions/', CorpusWorkerVersionList.as_view(), name='corpus-versions'),
-    path('corpus/<uuid:corpus>/selection/', CorpusDeleteSelection.as_view(), name='corpus-delete-selection'),
+    path('corpus/<uuid:pk>/selection/', CorpusDeleteSelection.as_view(), name='corpus-delete-selection'),
 
     # Moderation
     path('ml-classes/', MLClassList.as_view(), name='mlclass-list'),
-- 
GitLab