From 572d6ebd0647f0238671a2f18a003d7625abdad3 Mon Sep 17 00:00:00 2001
From: "J.-S. Caux" <J.S.Caux@uva.nl>
Date: Mon, 28 Sep 2020 07:58:05 +0200
Subject: [PATCH] Update registration and update personal data forms

---
 ontology/views.py                             |  6 ++-
 scipost/admin.py                              |  1 +
 scipost/forms.py                              | 45 ++++++++++++-------
 .../update-personal-data-expertises.js        | 33 --------------
 .../scipost/personal_page/account.html        | 24 +++++-----
 .../templates/scipost/_expertises_as_ul.html  |  9 ----
 .../scipost/update_personal_data.html         |  6 ---
 scipost/views.py                              |  2 +-
 8 files changed, 48 insertions(+), 78 deletions(-)
 delete mode 100644 scipost/static/scipost/update-personal-data-expertises.js
 delete mode 100644 scipost/templates/scipost/_expertises_as_ul.html

diff --git a/ontology/views.py b/ontology/views.py
index 4c15f76bc..7959ccedf 100644
--- a/ontology/views.py
+++ b/ontology/views.py
@@ -32,9 +32,11 @@ class AcademicFieldAutocompleteView(autocomplete.Select2QuerySetView):
     """To feed the Select2 widget."""
     def get_queryset(self):
         qs = AcademicField.objects.all()
+        if self.request.GET.get('exclude'):
+            qs = qs.exclude(slug=self.request.GET['exclude'])
         if self.q:
             qs = qs.filter(name__icontains=self.q)
-        return qs
+        return qs.order_by('name')
 
 
 class SpecialtyAutocompleteView(autocomplete.Select2QuerySetView):
@@ -43,7 +45,7 @@ class SpecialtyAutocompleteView(autocomplete.Select2QuerySetView):
         qs = Specialty.objects.all()
         if self.q:
             qs = qs.filter(name__icontains=self.q)
-        return qs
+        return qs.order_by('name')
 
 
 class TagAutocompleteView(autocomplete.Select2QuerySetView):
diff --git a/scipost/admin.py b/scipost/admin.py
index db84bfffa..e370d7789 100644
--- a/scipost/admin.py
+++ b/scipost/admin.py
@@ -14,6 +14,7 @@ from scipost.models import TOTPDevice, Contributor, Remark,\
 
 from organizations.admin import ContactInline
 from production.admin import ProductionUserInline
+from profiles.models import Profile
 from submissions.models import Submission
 
 
diff --git a/scipost/forms.py b/scipost/forms.py
index 56191453c..2bcaddde8 100644
--- a/scipost/forms.py
+++ b/scipost/forms.py
@@ -20,7 +20,7 @@ from haystack.forms import ModelSearchForm as HayStackSearchForm
 
 from .behaviors import orcid_validator
 from .constants import (
-    SCIPOST_DISCIPLINES, TITLE_CHOICES, SCIPOST_FROM_ADDRESSES,
+    TITLE_CHOICES, SCIPOST_FROM_ADDRESSES,
     UNVERIFIABLE_CREDENTIALS, NO_SCIENTIST, DOUBLE_ACCOUNT, BARRED)
 from .fields import ReCaptchaField
 from .models import Contributor, UnavailabilityPeriod, \
@@ -91,7 +91,25 @@ class RegistrationForm(forms.Form):
         label="ORCID id", max_length=20, required=False, validators=[orcid_validator],
         widget=forms.TextInput({
             'placeholder': 'Recommended. Get one at orcid.org'}))
-    discipline = forms.ChoiceField(choices=SCIPOST_DISCIPLINES, label='* Main discipline')
+    acad_field = forms.ModelChoiceField(
+        queryset=AcademicField.objects.all(),
+        widget=autocomplete.ModelSelect2(
+            url='/ontology/acad_field-autocomplete?exclude=multidisciplinary'
+        ),
+        label='Academic field',
+        help_text='Your main field of activity',
+        required=False
+    )
+    specialties = forms.ModelMultipleChoiceField(
+        queryset=Specialty.objects.all(),
+        widget=autocomplete.ModelSelect2Multiple(
+            url='/ontology/specialty-autocomplete',
+            attrs={'data-html': True}
+        ),
+        label='Specialties',
+        help_text='Type to search, click to include',
+        required=False
+    )
     current_affiliation = forms.ModelChoiceField(
         queryset=Organization.objects.all(),
         widget=autocomplete.ModelSelect2(
@@ -137,14 +155,11 @@ class RegistrationForm(forms.Form):
             )
 
         profile = Profile.objects.filter(
-            title=self.cleaned_data['title'],
-            first_name=self.cleaned_data['first_name'],
-            last_name=self.cleaned_data['last_name'],
-            discipline=self.cleaned_data['discipline']).first()
+            emails__email__icontains=self.cleaned_data['email']).first()
         try:
             if profile and profile.contributor:
                 raise forms.ValidationError(
-                    'There is already a registered Contributor with your first and last names. '
+                    'There is already a registered Contributor with your email address. '
                     'Please contact techsupport@scipost.org to clarify this issue.'
                 )
         except Contributor.DoesNotExist:
@@ -190,18 +205,16 @@ class RegistrationForm(forms.Form):
         })
         # Get or create a Profile
         profile = Profile.objects.filter(
-            title=self.cleaned_data['title'],
-            first_name=self.cleaned_data['first_name'],
-            last_name=self.cleaned_data['last_name'],
-            discipline=self.cleaned_data['discipline']).first()
+            emails__email__icontains=self.cleaned_data['email']).first()
         if profile is None:
             profile = Profile.objects.create(
                 title=self.cleaned_data['title'],
                 first_name=self.cleaned_data['first_name'],
                 last_name=self.cleaned_data['last_name'],
-                discipline=self.cleaned_data['discipline'],
+                acad_field=self.cleaned_data['acad_field'],
                 orcid_id=self.cleaned_data['orcid_id'],
                 webpage=self.cleaned_data['personalwebpage'])
+            profile.specialties.set(self.cleaned_data['specialties'])
         # Add a ProfileEmail to this Profile
         profile_email, created = ProfileEmail.objects.get_or_create(
             profile=profile, email=self.cleaned_data['email'])
@@ -254,10 +267,11 @@ class UpdatePersonalDataForm(forms.ModelForm):
     acad_field = forms.ModelChoiceField(
         queryset=AcademicField.objects.all(),
         widget=autocomplete.ModelSelect2(
-            url='/ontology/acad_field-autocomplete'
+            url='/ontology/acad_field-autocomplete?exclude=multidisciplinary'
         ),
         label='Academic field',
-        help_text='Your main field of activity'
+        help_text='Your main field of activity',
+        required=False
     )
     specialties = forms.ModelMultipleChoiceField(
         queryset=Specialty.objects.all(),
@@ -266,7 +280,8 @@ class UpdatePersonalDataForm(forms.ModelForm):
             attrs={'data-html': True}
         ),
         label='Specialties',
-        help_text='Type to search, click to include'
+        help_text='Type to search, click to include',
+        required=False
     )
     class Meta:
         model = Contributor
diff --git a/scipost/static/scipost/update-personal-data-expertises.js b/scipost/static/scipost/update-personal-data-expertises.js
deleted file mode 100644
index d772bea3b..000000000
--- a/scipost/static/scipost/update-personal-data-expertises.js
+++ /dev/null
@@ -1,33 +0,0 @@
-$(document).ready(function(){
-    $('select#id_discipline').on('change', function() {
-        var selection = $(this).val();
-        $("ul[id^='id_expertises_']").closest("li").hide();
-
-        switch(selection){
-        case "physics":
-	    $('li:contains("Physics")').filter(function(){
-		return $(this).text().indexOf('Physics') == 0;}).show();
-            break;
-        case "astrophysics":
-	    $('li:contains("Astrophysics")').filter(function(){
-		return $(this).text().indexOf('Astrophysics') == 0;}).show();
-            break;
-        case "mathematics":
-	    $('li:contains("Mathematics")').filter(function(){
-		return $(this).text().indexOf('Mathematics') == 0;}).show();
-            break;
-        case "chemistry":
-	    $('li:contains("Chemistry")').filter(function(){
-		return $(this).text().indexOf('Chemistry') == 0;}).show();
-            break;
-        case "computerscience":
-	    $('li:contains("Computer Science")').filter(function(){
-		return $(this).text().indexOf('Computer Science') == 0;}).show();
-            break;
-        default:
-            $("ul[id^='id_expertises_']").closest("li").show();
-            break;
-        }
-    }).trigger('change');
-
-});
diff --git a/scipost/templates/partials/scipost/personal_page/account.html b/scipost/templates/partials/scipost/personal_page/account.html
index f8088019d..870cc3241 100644
--- a/scipost/templates/partials/scipost/personal_page/account.html
+++ b/scipost/templates/partials/scipost/personal_page/account.html
@@ -31,18 +31,18 @@
 
     {% if contributor %}
       {# Scientist fields #}
-      <h3 class="mt-3">Your main discipline:</h3>
-      <ul><li>{{ contributor.get_discipline_display }}</li></ul>
-
-      <h3 class="mt-3">Your expertises:</h3>
-      {% if contributor.expertises %}
-        {% include "scipost/_expertises_as_ul.html" with contributor=contributor %}
-      {% else %}
-        <p>You haven't listed your expertise(s).<br/>
-          Do so by <a href="{% url 'scipost:update_personal_data' %}">updating your personal data</a>
-        </p>
-      {% endif %}
-      {# END: Scientist fields #}
+      <h3 class="mt-3">Your main academic field:</h3>
+      <ul><li>{{ contributor.profile.acad_field }}</li></ul>
+
+      <h3 class="mt-3">Your specialties:</h3>
+      <ul>
+	{% for specialty in contributor.profile.specialties.all %}
+	  <li>{{ specialty }}</li>
+	{% empty %}
+          <li>You haven't listed your specialties yet.</li>
+	{% endfor %}
+      </ul>
+      <p>You can add/remove specialties by <a href="{% url 'scipost:update_personal_data' %}">updating your personal data</a>.</p>
     {% endif %}
   </div>
 
diff --git a/scipost/templates/scipost/_expertises_as_ul.html b/scipost/templates/scipost/_expertises_as_ul.html
deleted file mode 100644
index a58ec6fbf..000000000
--- a/scipost/templates/scipost/_expertises_as_ul.html
+++ /dev/null
@@ -1,9 +0,0 @@
-{% load scipost_extras %}
-
-<ul>
-  {% for expertise in contributor.expertises %}
-    <li>
-      {{ expertise|get_specialization_display }}
-    </li>
-  {% endfor %}
-</ul>
diff --git a/scipost/templates/scipost/update_personal_data.html b/scipost/templates/scipost/update_personal_data.html
index 65e1efa3c..b611cb18a 100644
--- a/scipost/templates/scipost/update_personal_data.html
+++ b/scipost/templates/scipost/update_personal_data.html
@@ -12,12 +12,6 @@
 
 {% block content %}
 
-  {% if cont_form %}
-    <script src="{% static 'scipost/update-personal-data-expertises.js' %}"></script>
-  {% endif %}
-
-
-
   <form action="{% url 'scipost:update_personal_data' %}" method="post">
     {% csrf_token %}
     <div class="row justify-content-center">
diff --git a/scipost/views.py b/scipost/views.py
index 75e59448a..786bc5252 100644
--- a/scipost/views.py
+++ b/scipost/views.py
@@ -898,7 +898,7 @@ def _update_personal_data_contributor(request):
         if 'orcid_id' in cont_form.changed_data:
             cont_form.propagate_orcid()
         messages.success(request, 'Your personal data has been updated.')
-        return redirect(reverse('scipost:update_personal_data'))
+        return redirect(reverse('scipost:personal_page'))
 
     context = {
         'user_form': user_form,
-- 
GitLab