From dd88abe75d948e0d4a5e34890cc42a6dd157ca16 Mon Sep 17 00:00:00 2001
From: "J.-S. Caux" <J.S.Caux@uva.nl>
Date: Mon, 29 Oct 2018 09:00:03 +0100
Subject: [PATCH] Facility for matching Profiles to Contrib, UnregAuth, RefInv,
 RegInv

---
 profiles/forms.py                             |  1 -
 .../templates/profiles/_profile_card.html     | 12 ++++
 profiles/templates/profiles/profile_form.html | 11 ++++
 profiles/urls.py                              |  5 ++
 profiles/views.py                             | 66 +++++++++++++++++++
 scipost/apps.py                               |  4 +-
 6 files changed, 96 insertions(+), 3 deletions(-)

diff --git a/profiles/forms.py b/profiles/forms.py
index 11181e99d..43e8174f1 100644
--- a/profiles/forms.py
+++ b/profiles/forms.py
@@ -57,7 +57,6 @@ class ProfileForm(forms.ModelForm):
         profile.emails.filter(id=email.id).update(primary=True, still_valid=True)
         instance_pk = self.cleaned_data['instance_pk']
         if instance_pk:
-            print('%s, %s' % (instance_pk, self.cleaned_data['instance_from_type']))
             if self.cleaned_data['instance_from_type'] == 'contributor':
                 contributor = get_object_or_404(Contributor, pk=instance_pk)
                 contributor.profile = profile
diff --git a/profiles/templates/profiles/_profile_card.html b/profiles/templates/profiles/_profile_card.html
index 6692bc6b3..4ed906fb4 100644
--- a/profiles/templates/profiles/_profile_card.html
+++ b/profiles/templates/profiles/_profile_card.html
@@ -51,6 +51,18 @@
 	<tr><td>Accepts SciPost emails</td><td>{{ profile.accepts_SciPost_emails }}</td></tr>
 	<tr><td>Accepts refereeing requests</td><td>{{ profile.accepts_refereeing_requests }}</td></tr>
 	<tr><td>Contributor</td><td>{% if profile.contributor %}Yes (<a href="{% url 'scipost:contributor_info' contributor_id=profile.contributor.id %}" target="_blank">info link</a>){% else %}No{% endif %}</td></tr>
+	<tr>
+	  <td>Referee Invitations</td>
+	  <td>
+	    <ul>
+	      {% for inv in profile.refereeinvitation_set.all %}
+	      <li>{{ inv.submission.title }}<br/>(invited {{ inv.date_invited }}; fulfilled: {% if inv.fulfilled %}<i class="fa fa-check-square text-success"></i>{% else %}<i class="fa fa-times-circle"></i>{% endif %})</li>
+	      {% empty %}
+	      <li>No refereeing invitation found</li>
+	      {% endfor %}
+	    </ul>
+	  </td>
+	</tr>
       </table>
     </div>
     <div class="col-6">
diff --git a/profiles/templates/profiles/profile_form.html b/profiles/templates/profiles/profile_form.html
index e94df9dfc..202bf6896 100644
--- a/profiles/templates/profiles/profile_form.html
+++ b/profiles/templates/profiles/profile_form.html
@@ -12,6 +12,17 @@
 {% block content %}
 <div class="row">
   <div class="col-12">
+    {% if matching_profiles %}
+    <h4>Matching profiles found for this {{ from_type }}, {{ pk }}</h4>
+    <ul>
+      {% for matching_profile in matching_profiles %}
+      <li>{{ matching_profile }} <a href="{% url 'profiles:profile_match' profile_id=matching_profile.id from_type=from_type pk=pk %}">match this {{ from_type }} to this Profile</a>
+      </li>
+      {% endfor %}
+    </ul>
+    {% endif %}
+
+
     <form action="" method="post">
       {% csrf_token %}
       {{ form|bootstrap }}
diff --git a/profiles/urls.py b/profiles/urls.py
index 36ea79c05..842f711be 100644
--- a/profiles/urls.py
+++ b/profiles/urls.py
@@ -17,6 +17,11 @@ urlpatterns = [
         views.ProfileCreateView.as_view(),
         name='profile_create'
     ),
+    url(
+        r'^match/(?P<profile_id>[0-9]+)/(?P<from_type>[a-z]+)/(?P<pk>[0-9]+)$',
+        views.profile_match,
+        name='profile_match'
+    ),
     url(
         r'^(?P<pk>[0-9]+)/update/$',
         views.ProfileUpdateView.as_view(),
diff --git a/profiles/views.py b/profiles/views.py
index fe4766baf..039ada7f7 100644
--- a/profiles/views.py
+++ b/profiles/views.py
@@ -5,6 +5,7 @@ __license__ = "AGPL v3"
 from django.contrib import messages
 from django.core.urlresolvers import reverse, reverse_lazy
 from django.db import IntegrityError
+from django.db.models import Q
 from django.shortcuts import get_object_or_404, render, redirect
 from django.views.decorators.http import require_POST
 from django.views.generic.edit import CreateView, UpdateView, DeleteView
@@ -35,6 +36,42 @@ class ProfileCreateView(PermissionsMixin, CreateView):
     template_name = 'profiles/profile_form.html'
     success_url = reverse_lazy('profiles:profiles')
 
+    def get_context_data(self, *args, **kwargs):
+        """
+        When creating a Profile, if initial data obtained from another model
+        (Contributor, UnregisteredAuthor, RefereeInvitation or RegistrationInvitation)
+        is provided, this fills the context with possible already-existing Profiles.
+        """
+        context = super().get_context_data(*args, **kwargs)
+        from_type = self.kwargs.get('from_type', None)
+        pk = self.kwargs.get('pk', None)
+        context['from_type'] = from_type
+        context['pk'] = pk
+        print ('Hello, %s, %s' % (from_type, pk))
+        if pk and from_type:
+            matching_profiles = Profile.objects.all()
+            if from_type == 'contributor':
+                contributor = get_object_or_404(Contributor, pk=pk)
+                matching_profiles = matching_profiles.filter(
+                    Q(last_name=contributor.user.last_name) |
+                    Q(emails__email__in=contributor.user.email))
+            elif from_type == 'unregisteredauthor':
+                unreg_auth = get_object_or_404(UnregisteredAuthor, pk=pk)
+                matching_profiles = matching_profiles.filter(last_name=unreg_auth.last_name)
+            elif from_type == 'refereeinvitation':
+                print ('Here refinv')
+                refinv = get_object_or_404(RefereeInvitation, pk=pk)
+                matching_profiles = matching_profiles.filter(
+                    Q(last_name=refinv.last_name) |
+                    Q(emails__email__in=refinv.email_address))
+            elif from_type == 'registrationinvitation':
+                reginv = get_object_or_404(RegistrationInvitation, pk=pk)
+                matching_profiles = matching_profiles.filter(
+                    Q(last_name=reginv.last_name) |
+                    Q(emails__email__in=reginv.email))
+            context['matching_profiles'] = matching_profiles[:10]
+        return context
+
     def get_initial(self):
         """
         Provide initial data based on kwargs.
@@ -89,6 +126,35 @@ class ProfileCreateView(PermissionsMixin, CreateView):
             })
         return initial
 
+@permission_required('scipost.can_create_profiles')
+def profile_match(request, profile_id, from_type, pk):
+    """
+    Links an existing Profile to one of existing
+    Contributor, UnregisteredAuthor, RefereeInvitation, RegistrationInvitation.
+    """
+    profile = get_object_or_404(Profile, pk=profile_id)
+    if from_type == 'contributor':
+        contributor = get_object_or_404(Contributor, pk=pk)
+        contributor.profile = profile
+        contributor.save()
+        messages.success(request, 'Profile matched with Contributor')
+    elif from_type == 'unregisteredauthor':
+        unreg_auth = get_object_or_404(UnregisteredAuthor, pk=pk)
+        unreg_auth.profile = profile
+        unreg_auth.save()
+        messages.success(request, 'Profile matched with UnregisteredAuthor')
+    elif from_type == 'refereeinvitation':
+        ref_inv = get_object_or_404(RefereeInvitation, pk=pk)
+        ref_inv.profile = profile
+        ref_inv.save()
+        messages.success(request, 'Profile matched with RefereeInvitation')
+    elif from_type == 'registrationinvitation':
+        reg_inv = get_object_or_404(RegistrationInvitation, pk=pk)
+        reg_inv.profile = profile
+        reg_inv.save()
+        messages.success(request, 'Profile matched with RegistrationInvitation')
+    return redirect(reverse('profiles:profiles'))
+
 
 class ProfileUpdateView(PermissionsMixin, UpdateView):
     """
diff --git a/scipost/apps.py b/scipost/apps.py
index 109e1e5ed..dc85270be 100644
--- a/scipost/apps.py
+++ b/scipost/apps.py
@@ -14,5 +14,5 @@ class SciPostConfig(AppConfig):
 
         from . import signals
         from profiles.models import Profile
-        # post_save.connect(signals.link_created_profile_to_contributor,
-        #                   sender=Profile)
+        post_save.connect(signals.link_created_profile_to_contributor,
+                          sender=Profile)
-- 
GitLab