From a6dfe0ff36b294e66ea3d90b33e2fd4c1fd80fe5 Mon Sep 17 00:00:00 2001
From: Jorran de Wit <jorrandewit@outlook.com>
Date: Wed, 19 Jul 2017 08:51:45 +0200
Subject: [PATCH] Explicitly determine which contacts to promote

---
 partners/constants.py |  4 ++--
 partners/forms.py     | 33 +++++++++++++++++++++++++++------
 partners/views.py     |  6 ++----
 3 files changed, 31 insertions(+), 12 deletions(-)

diff --git a/partners/constants.py b/partners/constants.py
index e3f6224cd..d5f0a97a1 100644
--- a/partners/constants.py
+++ b/partners/constants.py
@@ -81,9 +81,9 @@ PARTNER_EVENTS = (
     ('comment', 'Comment added'),
 )
 
-
+CONTACT_GENERAL = 'gen'
 CONTACT_TYPES = (
-    ('gen', 'General Contact'),
+    (CONTACT_GENERAL, 'General Contact'),
     ('tech', 'Technical Contact'),
     ('fin', 'Financial Contact'),
     ('leg', 'Legal Contact')
diff --git a/partners/forms.py b/partners/forms.py
index 6454802bb..588c3ca2d 100644
--- a/partners/forms.py
+++ b/partners/forms.py
@@ -11,7 +11,7 @@ from django_countries.widgets import CountrySelectWidget
 from django_countries.fields import LazyTypedChoiceField
 
 from .constants import PARTNER_KINDS, PROSPECTIVE_PARTNER_PROCESSED, CONTACT_TYPES,\
-                       PARTNER_STATUS_UPDATE, REQUEST_PROCESSED, REQUEST_DECLINED
+                       PARTNER_STATUS_UPDATE, REQUEST_PROCESSED, REQUEST_DECLINED, CONTACT_GENERAL
 from .models import Partner, ProspectivePartner, ProspectiveContact, ProspectivePartnerEvent,\
                     Institution, Contact, PartnerEvent, MembershipAgreement, ContactRequest,\
                     PartnersAttachment
@@ -208,6 +208,10 @@ class ContactForm(forms.ModelForm):
             'kind',
         )
 
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.fields['kind'].required = False
+
 
 class NewContactForm(ContactForm):
     """
@@ -355,7 +359,9 @@ class PromoteToContactForm(forms.ModelForm):
     """
     This form is used to create a new `partners.Contact`
     """
-    kind = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
+    promote = forms.BooleanField(label='Activate/Promote this contact', initial=True,
+                                 required=False)
+    kind = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, initial=[CONTACT_GENERAL],
                                      label='Contact types', choices=CONTACT_TYPES, required=False)
 
     class Meta:
@@ -372,6 +378,9 @@ class PromoteToContactForm(forms.ModelForm):
         Check if email address is already used.
         """
         email = self.cleaned_data['email']
+        if not self.cleaned_data.get('promote', False):
+            # Don't promote the Contact
+            return email
         if User.objects.filter(Q(email=email) | Q(username=email)).exists():
             self.add_error('email', 'This emailadres has already been used.')
         return email
@@ -382,8 +391,11 @@ class PromoteToContactForm(forms.ModelForm):
         Promote ProspectiveContact's to Contact's related to a certain Partner.
         The status update after promotion is handled outside this method, in the Partner model.
         """
-        # How to handle empty instances?
+        if not self.cleaned_data.get('promote', False):
+            # Don't promote the Contact
+            return
 
+        # How to handle empty instances?
         if self.errors:
             return forms.ValidationError  # Is this a valid exception?
 
@@ -391,7 +403,6 @@ class PromoteToContactForm(forms.ModelForm):
         contact_form = NewContactForm(self.cleaned_data, partner=partner)
         if contact_form.is_valid():
             return contact_form.save(current_user=current_user)
-        r = contact_form.errors
         raise forms.ValidationError('NewContactForm invalid. Please contact Admin.')
 
 
@@ -411,12 +422,22 @@ class PromoteToContactFormset(forms.BaseModelFormSet):
         """
         contacts = []
         for form in self.forms:
-            contacts.append(form.promote_contact(partner, current_user))
-        partner.main_contact = contacts[0]
+            new_contact = form.promote_contact(partner, current_user)
+            if new_contact:
+                contacts.append(new_contact)
+        try:
+            partner.main_contact = contacts[0]
+        except IndexError:
+            # No contacts at all means no main-contact as well...
+            pass
         partner.save()
         return contacts
 
 
+ContactModelFormset = forms.modelformset_factory(ProspectiveContact, PromoteToContactForm,
+                                                 formset=PromoteToContactFormset, extra=0)
+
+
 class ProspectivePartnerForm(forms.ModelForm):
     """
     This form is used to internally add a ProspectivePartner.
diff --git a/partners/views.py b/partners/views.py
index 33d20a49f..e49685e99 100644
--- a/partners/views.py
+++ b/partners/views.py
@@ -16,8 +16,8 @@ from .models import Partner, ProspectivePartner, ProspectiveContact, ContactRequ
                     PartnersAttachment
 from .forms import ProspectivePartnerForm, ProspectiveContactForm,\
                    EmailProspectivePartnerContactForm, PromoteToPartnerForm,\
-                   ProspectivePartnerEventForm, MembershipQueryForm, PromoteToContactForm,\
-                   PromoteToContactFormset, PartnerForm, ContactForm, ContactFormset,\
+                   ProspectivePartnerEventForm, MembershipQueryForm,\
+                   PartnerForm, ContactForm, ContactFormset, ContactModelFormset,\
                    NewContactForm, InstitutionForm, ActivationForm, PartnerEventForm,\
                    MembershipAgreementForm, RequestContactForm, RequestContactFormSet,\
                    ProcessRequestContactForm, PartnersAttachmentFormSet, PartnersAttachmentForm,\
@@ -98,8 +98,6 @@ def promote_prospartner(request, prospartner_id):
     prospartner = get_object_or_404(ProspectivePartner.objects.not_yet_partner(),
                                     pk=prospartner_id)
     form = PromoteToPartnerForm(request.POST or None, instance=prospartner)
-    ContactModelFormset = modelformset_factory(ProspectiveContact, PromoteToContactForm,
-                                               formset=PromoteToContactFormset, extra=0)
     contact_formset = ContactModelFormset(request.POST or None,
                                           queryset=prospartner.prospective_contacts.all())
     if form.is_valid() and contact_formset.is_valid():
-- 
GitLab