Skip to content
This repository has been archived by the owner. It is now read-only.
Permalink
Browse files
button to claim/unclaim paper for user profile
  • Loading branch information
a3nm committed Jul 8, 2017
1 parent 643a192 commit 0deb6928eb57099a68e340652a4f2f5a35c9a50e
@@ -126,6 +126,44 @@ def harvestingStatus(request, pk):
return resp


@user_passes_test(is_authenticated)
@json_view
@require_POST
def claimPaper(request):
"""claim paper pk for current user"""
success = False
try:
paper = Paper.objects.get(pk=int(request.POST["pk"]))
except (KeyError, ValueError, Paper.DoesNotExist):
return {'success': success, 'message': 'Invalid paper id'}, 404
try:
# returns true or false depending on whether something was actually
# changed
paper.claim_for(request.user)
except ValueError:
# paper cannot be claimed
return {'success': success,
'message': 'Paper cannot be claimed by user'}, 403
success = True
return {'success': success}


@user_passes_test(is_authenticated)
@json_view
@require_POST
def unclaimPaper(request):
"""unclaim paper pk for current user"""
success = False
try:
paper = Paper.objects.get(pk=int(request.POST["pk"]))
except (KeyError, ValueError, Paper.DoesNotExist):
return {'success': success, 'message': 'Invalid paper id'}, 404
# returns true or false depending on whether something was actually changed
paper.unclaim_for(request.user)
success = True
return {'success': success}


@user_passes_test(is_authenticated)
@json_view
def waitForConsolidatedField(request):
@@ -227,4 +265,8 @@ def get_queryset(self):
name='ajax-setResearcherDepartment'),
url(r'^institutions.geojson', InstitutionsMapView.as_view(),
name='ajax-institutions-geojson'),
url(r'^claim-paper$',
claimPaper, name='ajax-claimPaper'),
url(r'^unclaim-paper$',
unclaimPaper, name='ajax-unclaimPaper'),
]
@@ -804,6 +804,10 @@ def serialize(self):
'full': self.full,
}

@property
def pair(self):
return (self.first, self.last)

@classmethod
def deserialize(cls, rep):
"""
@@ -911,14 +911,90 @@ def can_be_asked_for_upload(self):
@cached_property
def owners(self):
"""
Returns the list of users that own this papers (listed as authors and identified as such).
Returns the list of users that own this paper (listed as authors and identified as such).
"""
users = []
for a in self.authors:
if a.researcher and a.researcher.user:
users.append(a.researcher.user)
return users

def can_be_claimed_by(self, user):
"""
Is it possible for user to claim this paper?
"""
for author in self.authors:
first_name = None
last_name = None
try:
first_name = user.first_name
last_name = user.last_name
except AttributeError:
# anonymous user
return False
if not match_names(author.name.pair,
(first_name, last_name)):
continue
if author.orcid:
continue
if author.researcher_id:
continue
return True
return False

def unclaim_for(self, user):
"""
Remove all associations between this paper and user
"""
try:
user_researcher = Researcher.objects.get(user=user)
except Researcher.DoesNotExist:
user_researcher = None
user_orcid = None
if user_researcher:
user_orcid = user_researcher.orcid
for idx, author in enumerate(self.authors):
if (author.orcid == user_orcid or author.researcher_id ==
user_researcher.id):
# remove association between this author and user
self.authors_list[idx]['orcid'] = None
self.authors_list[idx]['researcher_id'] = None
self.save()
self.update_index()
return True
# nothing was done, paper cannot be unclaimed
raise False

def claim_for(self, user):
"""
Associate this paper to the requested user
"""
if user in self.owners:
# user already owns the paper
return False
try:
user_researcher = Researcher.objects.get(user=user)
except Researcher.DoesNotExist:
user_researcher = None
user_orcid = None
if user_researcher:
user_orcid = user_researcher.orcid
for idx, author in enumerate(self.authors):
if not match_names(author.name.pair,
(user.first_name, user.last_name)):
continue
if author.orcid:
continue
if author.researcher_id:
continue
self.authors_list[idx]['orcid'] = user_orcid
self.authors_list[idx]['researcher_id'] = user_researcher.id
self.save()
self.update_index()
return True
# paper cannot be claimed by user
raise ValueError

def is_owned_by(self, user, flexible=False):
"""
Is this user one of the owners of that paper?
@@ -15,7 +15,7 @@
{% endif %}
<ul class="withoutTriangles">
{% endifchanged %}
<li class="pubItem">
<li class="pubItem" id="paper-{{ paper.id }}">
{% if paper.pk %}
{% include "papers/publiListItem.html" with paper=paper with_buttons=request.user.is_authenticated %}
</li>
@@ -1,15 +1,16 @@
{% load author %}
{% load i18n %}
{% load cache %}
{% load canclaim %}
{% load domain %}
{% get_current_language as LANGUAGE_CODE %}
{% cache 60000 publiListItem paper.pk LANGUAGE_CODE researcher_id %}
<div class="pubLogo logoHelpPopover" data-content="{{ paper.status_helptext }}" rel="popover"
data-placement="bottom">
<img src="/static/img/logos/{{ paper.combined_status }}.png" width="52" height="70" />
</div>

<div class="publicationText">
{% cache 60000 publiListItem paper.pk LANGUAGE_CODE researcher_id %}
<p class="paperAuthors">
{% include "papers/authorList.html" with author_list=paper.displayed_authors %}
{% if paper.has_many_authors %}
@@ -29,6 +30,7 @@
</p>
{% endif %}
{% endwith %}
{% endcache %}

<p class="paperDownload">
{% if paper.pdf_url %}
@@ -37,6 +39,18 @@
{% else %}
<a href="{% url 'upload_paper' paper.pk %}" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-open"></span> {% trans "Upload" %}</a>
{% endif %}
{% if request.user in paper.owners %}
<a class="btn btn-default btn-xs unclaim-button"
data-pk="{{ paper.id }}" data-action="unclaim">
{% trans "Exclude from my profile" %}
</a>
{% else %}
{% canclaim request.user paper as can_claim %}
{% if can_claim %}
<a class="btn btn-default btn-xs claim-button"
data-pk="{{ paper.id }}" data-action="claim">
{% trans "Include in my profile" %}</a>
{% endif %}
{% endif %}
</p>
</div>
{% endcache %}
@@ -44,7 +44,63 @@
isSuperUser: {{ request.user.is_superuser|yesno:"true,false,false" }},
initialMessages: {{ messages | safe }}
}
init_paper_module(config)
init_paper_module(config);
function claim_unclaim (evt) {
var obj = $(evt.target);
var pk = obj.attr("data-pk");
var action = obj.attr("data-action");
if (action != "claim" && action != "unclaim") {
// action currently ongoing
return;
}
var my_url = "";
if (action == "claim") {
obj.text("{% trans "Claiming..." %}");
my_url = "{% url "ajax-claimPaper" %}";
} else {
obj.text("{% trans "Unclaiming..." %}");
my_url = "{% url "ajax-unclaimPaper" %}";
}
obj.toggleClass("disabled");
$.ajax({
method: "post",
url: my_url,
data: {"pk": pk,
"csrfmiddlewaretoken": '{{csrf_token}}'},
cache: false,
success: function (data) {
if (action == "claim") {
obj.text("{% trans "Exclude from my profile" %}");
obj.attr("data-action", "unclaim");
} else {
obj.text("{% trans "Include in my profile" %}");
obj.attr("data-action", "claim");
{% if user_researcher == researcher %}
// user_researcher is only defined on profile views
// in which case it is equal to the researcher of the currently
// logged in user; if it is the profile currently being viewed,
// we must remove the paper entirely
console.log("#paper-" + pk);
$("#paper-" + pk).fadeOut(300, function() { $(this).remove(); });
{% endif %}
}
obj.toggleClass("claim-button");
obj.toggleClass("unclaim-button");
obj.toggleClass("disabled");
},
fail: function(data) {
if (action == "claim") {
obj.text("{% trans "Claiming failed!" %}");
} else {
obj.text("{% trans "Unclaiming failed!" %}");
}
obj.toggleClass("disabled");
}
});
}

$(".unclaim-button").click(claim_unclaim);
$(".claim-button").click(claim_unclaim);
});
{% endblock %}

@@ -0,0 +1,11 @@
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals

from django import template

register = template.Library()


@register.simple_tag(name="canclaim")
def canclaim(user, paper):
return paper.can_be_claimed_by(user)
@@ -229,6 +229,11 @@ def get(self, request, *args, **kwargs):
def get_context_data(self, **kwargs):
context = super(ResearcherView, self).get_context_data(**kwargs)
researcher = self.researcher
# researcher corresponding to the currently logged in user
try:
context['user_researcher'] = Researcher.objects.get(user=self.request.user)
except Researcher.DoesNotExist:
pass # no logged in user
context['researcher'] = researcher
context['researcher_id'] = researcher.id
context['search_description'] += _(' authored by ')+unicode(researcher)

0 comments on commit 0deb692

Please sign in to comment.