From 96b0e3e18d4c9012b1befeafe67bc0a8735c2099 Mon Sep 17 00:00:00 2001
From: Jorran de Wit <jorrandewit@outlook.com>
Date: Thu, 16 Feb 2017 17:11:43 +0100
Subject: [PATCH] Fix errormessage not shown for specific cases

---
 commentaries/forms.py  |   3 +-
 commentaries/models.py |   9 +++
 commentaries/urls.py   |   2 +-
 commentaries/views.py  | 122 +----------------------------------------
 scipost/services.py    |  24 ++++++++
 strings/__init__.py    |  40 ++++++++++++++
 submissions/views.py   |  36 +-----------
 7 files changed, 81 insertions(+), 155 deletions(-)

diff --git a/commentaries/forms.py b/commentaries/forms.py
index 2660f4e5b..6f781e535 100644
--- a/commentaries/forms.py
+++ b/commentaries/forms.py
@@ -37,7 +37,8 @@ class IdentifierToQueryForm(forms.Form):
             commentary = None
 
         if commentary:
-            msg = 'There already exists a Commentary Page on this preprint, see %s' % commentary.header_as_li()
+            msg = 'There already exists a Commentary Page on this preprint, see %s' % (
+                    commentary.title_label())
             self.add_error('identifier', msg)
         return cleaned_data
 
diff --git a/commentaries/models.py b/commentaries/models.py
index 58f56c67a..e42eb4164 100644
--- a/commentaries/models.py
+++ b/commentaries/models.py
@@ -127,6 +127,15 @@ class Commentary(ArxivCallable, TimeStampedModel):
             context['arxiv_link'] = self.arxiv_link
         return template.render(context)
 
+    def title_label(self):
+        context = Context({
+            'scipost_url': self.scipost_url(),
+            'pub_title': self.pub_title
+        })
+        template = Template('<a href="{{scipost_url}}" class="pubtitleli">{{pub_title}}</a>')
+        return template.render(context)
+
+
     def header_as_li(self):
         # for display in search lists
         context = Context({'scipost_url': self.scipost_url(), 'pub_title': self.pub_title,
diff --git a/commentaries/urls.py b/commentaries/urls.py
index 3edb7d4a2..2f203ac38 100644
--- a/commentaries/urls.py
+++ b/commentaries/urls.py
@@ -16,9 +16,9 @@ urlpatterns = [
     url(r'^(?P<arxiv_or_DOI_string>arXiv:[0-9]{4,}.[0-9]{5,}(v[0-9]+)?)/$', views.commentary_detail, name='commentary'),
     # old style identifiers:
     url(r'^(?P<arxiv_or_DOI_string>arXiv:[a-z-]+/[0-9]{7,}(v[0-9]+)?)/$', views.commentary_detail, name='commentary'),
+
     url(r'^request_commentary$', views.RequestCommentary.as_view(), name='request_commentary'),
     url(r'^prefill_using_DOI$', views.prefill_using_DOI, name='prefill_using_DOI'),
-    # url(r'^prefill_using_identifier$', views.prefill_using_identifier, name='prefill_using_identifier'),
     url(r'^prefill_using_identifier$', views.PrefillUsingIdentifierView.as_view(), name='prefill_using_identifier'),
     url(r'^vet_commentary_requests$', views.vet_commentary_requests, name='vet_commentary_requests'),
     url(r'^vet_commentary_request_ack/(?P<commentary_id>[0-9]+)$', views.vet_commentary_request_ack, name='vet_commentary_request_ack'),
diff --git a/commentaries/views.py b/commentaries/views.py
index ea2608cfc..339bab4f9 100644
--- a/commentaries/views.py
+++ b/commentaries/views.py
@@ -152,93 +152,6 @@ def prefill_using_DOI(request):
     return redirect(reverse('commentaries:request_commentary'))
 
 
-# @permission_required('scipost.can_request_commentary_pages', raise_exception=True)
-# def prefill_using_identifier(request):
-#     """Probes arXiv with the identifier, to pre-fill the form"""
-#     if request.method == "POST":
-#         identifierform = IdentifierToQueryForm(request.POST)
-#         if identifierform.is_valid():
-#             # Check if given identifier is of expected form:
-#             # we allow 1 or 2 digits for version
-#             identifierpattern_new = re.compile("^[0-9]{4,}.[0-9]{4,5}v[0-9]{1,2}$")
-#             identifierpattern_old = re.compile("^[-.a-z]+/[0-9]{7,}v[0-9]{1,2}$")
-#             errormessage = ''
-#             existing_commentary = None
-#             if not (identifierpattern_new.match(identifierform.cleaned_data['identifier']) or
-#                     identifierpattern_old.match(identifierform.cleaned_data['identifier'])):
-#                 errormessage = ('The identifier you entered is improperly formatted '
-#                                 '(did you forget the version number?).')
-#             elif (Commentary.objects
-#                   .filter(arxiv_identifier=identifierform.cleaned_data['identifier']).exists()):
-#                 errormessage = 'There already exists a Commentary Page on this preprint, see'
-#                 existing_commentary = get_object_or_404(
-#                     Commentary, arxiv_identifier=identifierform.cleaned_data['identifier'])
-#             if errormessage:
-#                 form = RequestCommentaryForm()
-#                 doiform = DOIToQueryForm()
-#                 context = {'form': form, 'doiform': doiform, 'identifierform': identifierform,
-#                            'errormessage': errormessage,
-#                            'existing_commentary': existing_commentary}
-#                 return render(request, 'commentaries/request_commentary.html', context)
-#             # Otherwise we query arXiv for the information:
-#             try:
-#                 queryurl = ('http://export.arxiv.org/api/query?id_list=%s'
-#                             % identifierform.cleaned_data['identifier'])
-#                 arxivquery = feedparser.parse(queryurl)
-#
-#                 # If paper has been published, should comment on published version
-#                 try:
-#                     arxiv_journal_ref = arxivquery['entries'][0]['arxiv_journal_ref']
-#                     errormessage = ('This paper has been published as ' + arxiv_journal_ref
-#                                     + '. Please comment on the published version.')
-#                 except (IndexError, KeyError):
-#                     pass
-#                 try:
-#                     arxiv_doi = arxivquery['entries'][0]['arxiv_doi']
-#                     errormessage = ('This paper has been published under DOI ' + arxiv_doi
-#                                     + '. Please comment on the published version.')
-#                 except (IndexError, KeyError):
-#                     pass
-#
-#                 if errormessage:
-#                     form = RequestCommentaryForm()
-#                     doiform = DOIToQueryForm()
-#                     context = {'form': form, 'doiform': doiform, 'identifierform': identifierform,
-#                                'errormessage': errormessage,
-#                                'existing_commentary': existing_commentary}
-#                     return render(request, 'commentaries/request_commentary.html', context)
-#
-#                 # otherwise prefill the form:
-#                 metadata = arxivquery
-#                 pub_title = arxivquery['entries'][0]['title']
-#                 authorlist = arxivquery['entries'][0]['authors'][0]['name']
-#                 for author in arxivquery['entries'][0]['authors'][1:]:
-#                     authorlist += ', ' + author['name']
-#                 arxiv_link = arxivquery['entries'][0]['id']
-#                 abstract = arxivquery['entries'][0]['summary']
-#                 form = RequestCommentaryForm(
-#                     initial={'type': 'preprint', 'metadata': metadata,
-#                              'pub_title': pub_title, 'author_list': authorlist,
-#                              'arxiv_identifier': identifierform.cleaned_data['identifier'],
-#                              'arxiv_link': arxiv_link, 'pub_abstract': abstract})
-#                 doiform = DOIToQueryForm()
-#                 context = {'form': form, 'doiform': doiform, 'identifierform': identifierform}
-#                 context['title'] = pub_title
-#                 return render(request, 'commentaries/request_commentary.html', context)
-#             except (IndexError, KeyError, ValueError):
-#                 # something went wrong with processing the arXiv data
-#                 errormessage = ('An error occurred while processing the arXiv data.'
-#                                 ' Are you sure this identifier exists?')
-#                 form = RequestCommentaryForm()
-#                 doiform = DOIToQueryForm()
-#                 context = {'form': form, 'doiform': doiform, 'identifierform': identifierform,
-#                            'errormessage': errormessage,
-#                            'existing_commentary': existing_commentary}
-#                 return render(request, 'commentaries/request_commentary.html', context)
-#         else:
-#             pass
-#     return redirect(reverse('commentaries:request_commentary'))
-
 @method_decorator(permission_required(
     'scipost.can_request_commentary_pages', raise_exception=True), name='dispatch')
 class PrefillUsingIdentifierView(RequestCommentaryMixin, FormView):
@@ -284,39 +197,8 @@ class PrefillUsingIdentifierView(RequestCommentaryMixin, FormView):
             return render(self.request, 'commentaries/request_commentary.html',
                           self.get_context_data(**context))
         else:
-            # Arxiv response is not valid
-            errormessages = {
-                'preprint_does_not_exist':
-                    'A preprint associated to this identifier does not exist.',
-                'paper_published_journal_ref':
-                    ('This paper has been published as ' + caller.arxiv_journal_ref +
-                     '. Please comment on the published version.'),
-                'paper_published_doi':
-                    ('This paper has been published under DOI ' + caller.arxiv_doi +
-                     '. Please comment on the published version.'),
-                'arxiv_timeout': 'Arxiv did not respond in time. Please try again later',
-                'arxiv_bad_request':
-                    ('There was an error with requesting identifier ' +
-                     caller.identifier_with_vn_nr +
-                     ' from Arxiv. Please check the identifier and try again.'),
-                'previous_submission_undergoing_refereeing':
-                    ('There exists a preprint with this arXiv identifier '
-                     'but an earlier version number, which is still undergoing '
-                     'peer refereeing.'
-                     'A resubmission can only be performed after request '
-                     'from the Editor-in-charge. Please wait until the '
-                     'closing of the previous refereeing round and '
-                     'formulation of the Editorial Recommendation '
-                     'before proceeding with a resubmission.'),
-                'preprint_already_submitted':
-                    'This preprint version has already been submitted to SciPost.',
-                'previous_submissions_rejected':
-                    ('This arXiv preprint has previously undergone refereeing '
-                     'and has been rejected. Resubmission is only possible '
-                     'if the manuscript has been substantially reworked into '
-                     'a new arXiv submission with distinct identifier.')
-            }
-            messages.error(self.request, errormessages[caller.errorcode])
+            msg = caller.get_error_message()
+            messages.error(self.request, msg)
             return render(self.request, 'commentaries/request_commentary.html',
                           self.get_context_data(**{}))
 
diff --git a/scipost/services.py b/scipost/services.py
index cd9c511a8..957bb7603 100644
--- a/scipost/services.py
+++ b/scipost/services.py
@@ -3,8 +3,11 @@ import feedparser
 import requests
 import re
 
+from django.template import Template, Context
 from .behaviors import ArxivCallable
 
+from strings import arxiv_caller_errormessages
+
 
 class BaseCaller(object):
     '''Base mixin for caller (Arxiv, DOI).
@@ -22,6 +25,8 @@ class BaseCaller(object):
     _is_processed = False
     caller_regex = None
     errorcode = None
+    errorvariables = {}
+    errormessages = {}
     identifier_without_vn_nr = ''
     identifier_with_vn_nr = ''
     metadata = {}
@@ -63,6 +68,7 @@ class BaseCaller(object):
             self.identifier_with_vn_nr = self.identifier
             self.version_nr = int(self.identifier.rpartition('v')[2])
         else:
+            self.errorvariables['identifier_with_vn_nr'] = self.identifier
             raise ValueError('bad_identifier')
 
     def _check_valid_caller(self):
@@ -141,6 +147,16 @@ class BaseCaller(object):
 
         self._is_processed = True
 
+    def get_error_message(self, errormessages={}):
+        '''Return the errormessages for a specific error code, with the possibility to
+        overrule the default errormessage dictionary for the specific Caller.
+        '''
+        try:
+            t = Template(errormessages[self.errorcode])
+        except KeyError:
+            t = Template(self.errormessages[self.errorcode])
+        return t.render(Context(self.errorvariables))
+
 
 class DOICaller(BaseCaller):
     """Perform a DOI lookup for a given identifier."""
@@ -153,6 +169,12 @@ class ArxivCaller(BaseCaller):
     # # State of the caller
     resubmission = False
     previous_submissions = []
+    errormessages = arxiv_caller_errormessages
+    errorvariables = {
+        'arxiv_journal_ref': '',
+        'arxiv_doi': '',
+        'identifier_with_vn_nr': ''
+    }
     arxiv_journal_ref = ''
     arxiv_doi = ''
     metadata = {}
@@ -195,11 +217,13 @@ class ArxivCaller(BaseCaller):
 
         # Check via journal ref if already published
         self.arxiv_journal_ref = self.published_journal_ref()
+        self.errorvariables['arxiv_journal_ref'] = self.arxiv_journal_ref
         if self.arxiv_journal_ref:
             raise ValueError('paper_published_journal_ref')
 
         # Check via DOI if already published
         self.arxiv_doi = self.published_doi()
+        self.errorvariables['arxiv_doi'] = self.arxiv_doi
         if self.arxiv_doi:
             raise ValueError('paper_published_doi')
 
diff --git a/strings/__init__.py b/strings/__init__.py
index bed3b4266..f51088e3a 100644
--- a/strings/__init__.py
+++ b/strings/__init__.py
@@ -7,3 +7,43 @@ acknowledge_request_commentary = (
     "Your request will soon be handled by an Editor. <br>"
     "Thank you for your request for a Commentary Page."
 )
+
+# Arxiv response is not valid
+arxiv_caller_errormessages = {
+    'preprint_does_not_exist':
+        'A preprint associated to this identifier does not exist.',
+    'paper_published_journal_ref':
+        ('This paper has been published as {{ arxiv_journal_ref }}'
+         '. Please comment on the published version.'),
+    'paper_published_doi':
+        ('This paper has been published under DOI {{ arxiv_doi }}'
+         '. Please comment on the published version.'),
+    'arxiv_timeout': 'Arxiv did not respond in time. Please try again later',
+    'arxiv_bad_request':
+        ('There was an error with requesting identifier ' +
+         '{{ identifier_with_vn_nr }}'
+         ' from Arxiv. Please check the identifier and try again.'),
+    'previous_submission_undergoing_refereeing':
+        ('There exists a preprint with this arXiv identifier '
+         'but an earlier version number, which is still undergoing '
+         'peer refereeing.'
+         'A resubmission can only be performed after request '
+         'from the Editor-in-charge. Please wait until the '
+         'closing of the previous refereeing round and '
+         'formulation of the Editorial Recommendation '
+         'before proceeding with a resubmission.'),
+    'preprint_already_submitted':
+        'This preprint version has already been submitted to SciPost.',
+    'previous_submissions_rejected':
+        ('This arXiv preprint has previously undergone refereeing '
+         'and has been rejected. Resubmission is only possible '
+         'if the manuscript has been substantially reworked into '
+         'a new arXiv submission with distinct identifier.')
+}
+
+arxiv_caller_errormessages_submissions = {
+    'paper_published_journal_ref': ('This paper has been published as {{ arxiv_journal_ref }}'
+                                    '. You cannot submit it to SciPost anymore.'),
+    'paper_published_doi': ('This paper has been published under DOI {{ arxiv_doi }}'
+                            '. You cannot submit it to SciPost anymore.')
+}
diff --git a/submissions/views.py b/submissions/views.py
index bf1690032..451a8f47f 100644
--- a/submissions/views.py
+++ b/submissions/views.py
@@ -33,6 +33,7 @@ from scipost.models import Contributor, title_dict, Remark, RegistrationInvitati
 
 from scipost.services import ArxivCaller
 from scipost.utils import Utils
+from strings import arxiv_caller_errormessages_submissions
 
 from comments.forms import CommentForm
 
@@ -186,39 +187,8 @@ class PrefillUsingIdentifierView(FormView):
                 return render(request, 'submissions/new_submission.html', context)
 
             else:
-                # Arxiv response is not valid
-                errormessages = {
-                    'preprint_does_not_exist':
-                        'A preprint associated to this identifier does not exist.',
-                    'paper_published_journal_ref':
-                        ('This paper has been published as ' + caller.arxiv_journal_ref +
-                         '. You cannot submit it to SciPost anymore.'),
-                    'paper_published_doi':
-                        ('This paper has been published under DOI ' + caller.arxiv_doi +
-                         '. You cannot submit it to SciPost anymore.'),
-                    'arxiv_timeout': 'Arxiv did not respond in time. Please try again later',
-                    'arxiv_bad_request':
-                        ('There was an error with requesting identifier ' +
-                         caller.identifier_with_vn_nr +
-                         ' from Arxiv. Please check the identifier and try again.'),
-                    'previous_submission_undergoing_refereeing':
-                        ('There exists a preprint with this arXiv identifier '
-                         'but an earlier version number, which is still undergoing '
-                         'peer refereeing.'
-                         'A resubmission can only be performed after request '
-                         'from the Editor-in-charge. Please wait until the '
-                         'closing of the previous refereeing round and '
-                         'formulation of the Editorial Recommendation '
-                         'before proceeding with a resubmission.'),
-                    'preprint_already_submitted': 'This preprint version has already been submitted to SciPost.',
-                    'previous_submissions_rejected':
-                        ('This arXiv preprint has previously undergone refereeing '
-                         'and has been rejected. Resubmission is only possible '
-                         'if the manuscript has been substantially reworked into '
-                         'a new arXiv submission with distinct identifier.')
-                }
-
-                identifierform.add_error(None, errormessages[caller.errorcode])
+                msg = caller.get_error_message(arxiv_caller_errormessages_submissions)
+                identifierform.add_error(None, msg)
                 return render(request, 'submissions/prefill_using_identifier.html',
                               {'form': identifierform})
         else:
-- 
GitLab