From 1e9ae5c6ad8773e8aa6806f2edec9b3cd45ae2c1 Mon Sep 17 00:00:00 2001
From: sks444 <krishnasingh.ss30@gmail.com>
Date: Wed, 11 Nov 2020 13:49:40 +0530
Subject: [PATCH] When default screening status changes replace submission with
 new default

---
 hypha/apply/funds/admin_forms.py | 26 ++++++++++++++++----------
 1 file changed, 16 insertions(+), 10 deletions(-)

diff --git a/hypha/apply/funds/admin_forms.py b/hypha/apply/funds/admin_forms.py
index 759e54a5e..bfda88721 100644
--- a/hypha/apply/funds/admin_forms.py
+++ b/hypha/apply/funds/admin_forms.py
@@ -4,6 +4,7 @@ from django.apps import apps
 from wagtail.admin.forms import WagtailAdminModelForm, WagtailAdminPageForm
 
 from .workflow import WORKFLOWS
+from .models.submissions import ApplicationSubmission
 
 
 class WorkflowFormAdminForm(WagtailAdminPageForm):
@@ -87,20 +88,25 @@ class RoundBasePageAdminForm(WagtailAdminPageForm):
 
 class ScreeningStatusAdminForm(WagtailAdminModelForm):
 
-    def clean(self):
-        cleaned_data = super().clean()
-        default = cleaned_data['default']
-        yes = cleaned_data['yes']
+    def save(self, commit=True):
+        default = self.cleaned_data['default']
+        yes = self.cleaned_data['yes']
         ScreeningStatus = apps.get_model('funds', 'ScreeningStatus')
         if default:
             try:
-                default_yes = ScreeningStatus.objects.get(
-                    default=True, yes=yes
+                default_screening = ScreeningStatus.objects.get(
+                    default=default, yes=yes
                 )
             except ScreeningStatus.DoesNotExist:
                 pass
             else:
-                if default_yes.id != self.instance.id:
-                    yes_or_no = 'yes' if yes else 'no'
-                    self.add_error('default', f'Can not set two ScreeningStatus as default {yes_or_no}')
-        return cleaned_data
+                screening = super().save(commit)
+                if default_screening.id != screening.id:
+                    submissions = ApplicationSubmission.objects.filter(screening_statuses__id=default_screening.id)
+                    for submission in submissions:
+                        submission.screening_statuses.remove(default_screening)
+                        submission.screening_statuses.add(screening)
+                    default_screening.default = False
+                    default_screening.save()
+                return screening
+        return super().save(commit)
-- 
GitLab