From 8321708807c27dfe9046ca718218e9cc243715ee Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jean-S=C3=A9bastien=20Caux?= <git@jscaux.org>
Date: Wed, 9 Feb 2022 15:23:11 +0100
Subject: [PATCH] More to-the-point filter for reports needed

---
 scipost_django/submissions/forms.py               |  2 +-
 scipost_django/submissions/managers/submission.py | 13 ++++++++++++-
 2 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/scipost_django/submissions/forms.py b/scipost_django/submissions/forms.py
index bbdb2d25d..59f187868 100644
--- a/scipost_django/submissions/forms.py
+++ b/scipost_django/submissions/forms.py
@@ -138,7 +138,7 @@ class SubmissionSearchForm(forms.Form):
             )
         if self.reports_needed:
             submissions = submissions.actively_refereeing(
-            ).open_for_reporting().order_by('submission_date')
+            ).open_for_reporting().reports_needed().order_by('submission_date')
         return submissions
 
 
diff --git a/scipost_django/submissions/managers/submission.py b/scipost_django/submissions/managers/submission.py
index 009dd716d..7a9bfeb92 100644
--- a/scipost_django/submissions/managers/submission.py
+++ b/scipost_django/submissions/managers/submission.py
@@ -204,9 +204,20 @@ class SubmissionQuerySet(models.QuerySet):
         return self._newest_version_only(self.filter(status=constants.STATUS_WITHDRAWN))
 
     def open_for_reporting(self):
-        """Return Submission that allow for reporting."""
+        """Return Submissions open for reporting."""
         return self.filter(open_for_reporting=True)
 
+    def reports_needed(self):
+        """
+        Return Submissions for which the nr of Reports is less than required by target Journal.
+        """
+        qs = self.prefetch_related(
+            'reports', 'submitted_to'
+        ).annotate(nr_reports=models.Count('reports'))
+        ids_list = [s.id for s in qs.all() if (
+            s.nr_reports < s.submitted_to.minimal_nr_of_reports)]
+        return self.filter(id__in=ids_list)
+
     def open_for_commenting(self):
         """Return Submission that allow for commenting."""
         return self.filter(open_for_commenting=True)
-- 
GitLab