From c14995226c3f2530ab35b50d13ae1298f27f814e Mon Sep 17 00:00:00 2001
From: Geert Kapteijns <ghkapteijns@gmail.com>
Date: Sun, 7 May 2017 02:06:20 +0200
Subject: [PATCH] begin work on RequestPublishedArticleForm

---
 commentaries/forms.py                         |  21 +-
 .../commentaries/request_commentary.html      | 109 +-------
 .../commentaries/request_commentary_old.html  |  56 +++++
 .../request_published_article.html            |  27 ++
 commentaries/test_views.py                    |   3 +-
 commentaries/urls.py                          |   9 +-
 commentaries/views.py                         | 234 +++++++++++-------
 7 files changed, 256 insertions(+), 203 deletions(-)
 create mode 100644 commentaries/templates/commentaries/request_commentary_old.html
 create mode 100644 commentaries/templates/commentaries/request_published_article.html

diff --git a/commentaries/forms.py b/commentaries/forms.py
index 383eb9201..6364e224d 100644
--- a/commentaries/forms.py
+++ b/commentaries/forms.py
@@ -9,10 +9,6 @@ from .models import Commentary
 from scipost.models import Contributor
 
 
-# class DOIToQueryForm(forms.Form):
-#     doi = forms.CharField(widget=forms.TextInput(
-#         {'label': 'DOI', 'placeholder': 'ex.: 10.21468/00.000.000000'}))
-
 class DOIToQueryForm(forms.Form):
     VALID_DOI_REGEXP = r'^(?i)10.\d{4,9}/[-._;()/:A-Z0-9]+$'
     doi = forms.RegexField(regex=VALID_DOI_REGEXP, strip=False, widget=forms.TextInput(
@@ -56,6 +52,23 @@ class IdentifierToQueryForm(forms.Form):
         return cleaned_data
 
 
+class RequestPublishedArticleForm(forms.ModelForm):
+    class Meta:
+        model = Commentary
+        fields = [
+            'type', 'discipline', 'domain', 'subject_area', 'pub_title', 'author_list', 'metadata', 'journal', 'volume',
+            'pages', 'pub_date', 'pub_DOI', 'pub_abstract'
+        ]
+        widgets = {
+            'metadata': forms.HiddenInput(),
+            'type': forms.HiddenInput(),
+        }
+        placeholders = {
+            'pub_DOI': 'ex.: 10.21468/00.000.000000',
+            'pub_date': 'Format: YYYY-MM-DD',
+        }
+
+
 class RequestCommentaryForm(forms.ModelForm):
     """Create new valid Commetary by user request"""
     existing_commentary = None
diff --git a/commentaries/templates/commentaries/request_commentary.html b/commentaries/templates/commentaries/request_commentary.html
index dec478082..c89649093 100644
--- a/commentaries/templates/commentaries/request_commentary.html
+++ b/commentaries/templates/commentaries/request_commentary.html
@@ -8,112 +8,21 @@
 
 {% block content %}
 
-  <script>
-  $(document).ready(function(){
-
-    var allToggableRows = $('#requestForm .form-group').slice(1)
-    var type_selector = $('select#id_type')
-
-    var preprint = [5,6,7,8,10]
-    var published = [9]
-
-    function show(indices){
-      allToggableRows.each(function(index){
-        if($.inArray( index, indices) != -1){
-          $(this).hide()
-        }else{
-          $(this).show()
-        }
-
-      })
-    }
-
-    switch (type_selector.val()) {
-     case "":
-       allToggableRows.hide()
-       $("#DOIprefill").hide();
-       $("#arXivprefill").hide();
-       break;
-     case "published":
-       show(published)
-       $("#DOIprefill").show()
-       $("#arXivprefill").hide();
-       break;
-     case "preprint":
-       show(preprint)
-       $("#DOIprefill").hide()
-       $("#arXivprefill").show();
-       break;
-     default:
-       allToggableRows.hide()
-       $("#DOIprefill").hide();
-       $("#arXivprefill").hide();
-    }
-
-    type_selector.on('change', function() {
-      var selection = $(this).val();
-      switch(selection){
-        case "published":
-          show(published)
-          $("#DOIprefill").show()
-          $("#arXivprefill").hide();
-          break;
-        case "preprint":
-          show(preprint)
-          $("#DOIprefill").hide()
-          $("#arXivprefill").show();
-          break;
-        default:
-          $("#DOIprefill").hide()
-          $("#arXivprefill").hide();
-          allToggableRows.hide()
-      }
-    });
-  });
-</script>
-
 <div class="row">
     <div class="col-12">
         <div class="panel">
             <h1>Request Activation of a Commentary Page:</h1>
         </div>
     </div>
-</div>
-<div class="row">
-    <div class="col-md-6 offset-md-3">
-    {% if errormessage %}
-        <h3 style="color: red;">Error: {{ errormessage }}</h3>
-        {% if existing_commentary %}
-            <ul>{% include 'commentaries/_commentary_card_content.html' with object=existing_commentary %}</ul>
-        {% endif %}
-        <br/>
-    {% endif %}
-
-  <div id="DOIprefill">
-    <h3><em>For published papers, you can prefill the form (except for domain, subject area and abstract) using the DOI:</em></h3>
-    <p><em>(give the DOI as 10.[4 to 9 digits]/[string], without prefix, as per the placeholder)</em></p>
-    <form action="{% url 'commentaries:prefill_using_DOI' %}" method="post">
-      {% csrf_token %}
-      {{ doiform|bootstrap }}
-      <input class="btn btn-secondary" type="submit" value="Query DOI"/>
-    </form>
-  </div>
-  <div id="arXivprefill">
-    <h3><em>For preprints, you can prefill the form using the arXiv identifier:</em></h3>
-    <p><em>(give the identifier without prefix, as per the placeholder)</em></p>
-    <form action="{% url 'commentaries:prefill_using_identifier' %}" method="post">
-      {% csrf_token %}
-      {{ identifierform|bootstrap }}
-      <input class="btn btn-secondary" type="submit" value="Query arXiv"/>
-    </form>
-  </div>
-  <br/>
-  <form id="requestForm" action="{% url 'commentaries:request_commentary' %}" method="post">
-    {% csrf_token %}
-      {{ request_commentary_form|bootstrap }}
-    <input class="btn btn-primary" type="submit" value="Submit"/>
-  </form>
-
+    <div class="col-12">
+        <ul>
+            <li>
+                <a href="{% url 'commentaries:request_published_article' %}">Click here to submit a published article</a>
+            </li>
+            <li>
+                <a href="{% url 'commentaries:request_arxiv_preprint' %}">Click here to submit an arXiv preprint</a>
+            </li>
+        </ul>
     </div>
 </div>
 
diff --git a/commentaries/templates/commentaries/request_commentary_old.html b/commentaries/templates/commentaries/request_commentary_old.html
new file mode 100644
index 000000000..e5c38d7f6
--- /dev/null
+++ b/commentaries/templates/commentaries/request_commentary_old.html
@@ -0,0 +1,56 @@
+{% extends 'scipost/base.html' %}
+
+{% load bootstrap %}
+
+{% load scipost_extras %}
+
+{% block pagetitle %}: request Commentary{% endblock pagetitle %}
+
+{% block content %}
+
+<div class="row">
+    <div class="col-12">
+        <div class="panel">
+            <h1>Request Activation of a Commentary Page:</h1>
+        </div>
+    </div>
+</div>
+<div class="row">
+    <div class="col-md-6 offset-md-3">
+    {% if errormessage %}
+        <h3 style="color: red;">Error: {{ errormessage }}</h3>
+        {% if existing_commentary %}
+            <ul>{% include 'commentaries/_commentary_card_content.html' with object=existing_commentary %}</ul>
+        {% endif %}
+        <br/>
+    {% endif %}
+
+  <div id="DOIprefill">
+    <h3><em>For published papers, you can prefill the form (except for domain, subject area and abstract) using the DOI:</em></h3>
+    <p><em>(give the DOI as 10.[4 to 9 digits]/[string], without prefix, as per the placeholder)</em></p>
+    <form action="{% url 'commentaries:prefill_using_DOI' %}" method="post">
+      {% csrf_token %}
+      {{ doiform|bootstrap }}
+      <input class="btn btn-secondary" type="submit" value="Query DOI"/>
+    </form>
+  </div>
+  <div id="arXivprefill">
+    <h3><em>For preprints, you can prefill the form using the arXiv identifier:</em></h3>
+    <p><em>(give the identifier without prefix, as per the placeholder)</em></p>
+    <form action="{% url 'commentaries:prefill_using_identifier' %}" method="post">
+      {% csrf_token %}
+      {{ identifierform|bootstrap }}
+      <input class="btn btn-secondary" type="submit" value="Query arXiv"/>
+    </form>
+  </div>
+  <br/>
+  <form id="requestForm" action="{% url 'commentaries:request_commentary' %}" method="post">
+    {% csrf_token %}
+      {{ request_commentary_form|bootstrap }}
+    <input class="btn btn-primary" type="submit" value="Submit"/>
+  </form>
+
+    </div>
+</div>
+
+{% endblock content %}
diff --git a/commentaries/templates/commentaries/request_published_article.html b/commentaries/templates/commentaries/request_published_article.html
new file mode 100644
index 000000000..b03456af3
--- /dev/null
+++ b/commentaries/templates/commentaries/request_published_article.html
@@ -0,0 +1,27 @@
+{% extends 'scipost/base.html' %}
+{% load bootstrap %}
+{% load scipost_extras %}
+
+{% block pagetitle %}: request Commentary{% endblock pagetitle %}
+
+{% block content %}
+
+<div class="row">
+    {# <h3><em>For published papers, you can prefill the form (except for domain, subject area and abstract) using the DOI:</em></h3>#}
+    {# <p><em>(give the DOI as 10.[4 to 9 digits]/[string], without prefix, as per the placeholder)</em></p>#}
+    <form action="{% url 'commentaries:prefill_using_DOI' %}" method="post">
+      {% csrf_token %}
+      {{ doi_query_form|bootstrap }}
+      <input class="btn btn-secondary" type="submit" value="Query DOI"/>
+    </form>
+</div>
+
+<div class="row">
+    <form id="requestForm" action="{% url 'commentaries:request_published_article' %}" method="post">
+        {% csrf_token %}
+        {{ form|bootstrap }}
+        <input class="btn btn-primary" type="submit" value="Submit"/>
+    </form>
+</div>
+
+{% endblock content%}
diff --git a/commentaries/test_views.py b/commentaries/test_views.py
index 82ad9463e..ca2a6c8e4 100644
--- a/commentaries/test_views.py
+++ b/commentaries/test_views.py
@@ -47,7 +47,8 @@ class PrefillUsingDOITest(TestCase):
         request.user = UserFactory()
 
         response = prefill_using_DOI(request)
-        self.assertRedirects(response, reverse('commentaries:request_commentary'))
+        # Not sure what to test here
+        raise NotImplementedError
 
 
 class VetCommentaryRequestsTest(TestCase):
diff --git a/commentaries/urls.py b/commentaries/urls.py
index a1b5ba5ec..1f5afec94 100644
--- a/commentaries/urls.py
+++ b/commentaries/urls.py
@@ -21,10 +21,13 @@ urlpatterns = [
     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'^request_commentary$', views.request_commentary, name='request_commentary'),
+    url(r'^request_commentary/published_article$', views.RequestPublishedArticle.as_view(),
+        name='request_published_article'),
+    url(r'^request_commentary/arxiv_preprint$', views.request_arxiv_preprint, name='request_arxiv_preprint'),
     url(r'^prefill_using_DOI$', views.prefill_using_DOI, name='prefill_using_DOI'),
-    url(r'^prefill_using_identifier$', views.PrefillUsingIdentifierView.as_view(),
-        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]+)$',
diff --git a/commentaries/views.py b/commentaries/views.py
index ccd06ba20..aae2fc598 100644
--- a/commentaries/views.py
+++ b/commentaries/views.py
@@ -16,8 +16,8 @@ from django.utils.decorators import method_decorator
 from django.http import Http404
 
 from .models import Commentary
-from .forms import RequestCommentaryForm, DOIToQueryForm, IdentifierToQueryForm
-from .forms import VetCommentaryForm, CommentarySearchForm
+from .forms import RequestCommentaryForm, DOIToQueryForm, IdentifierToQueryForm, VetCommentaryForm, \
+    CommentarySearchForm, RequestPublishedArticleForm
 
 from comments.models import Comment
 from comments.forms import CommentForm
@@ -31,66 +31,110 @@ import strings
 # Commentaries
 ################
 
-class RequestCommentaryMixin(object):
-    def get_context_data(self, **kwargs):
-        '''Pass the DOI and identifier forms to the context.'''
-        if 'request_commentary_form' not in kwargs:
-            # Only intercept if not prefilled
-            kwargs['request_commentary_form'] = RequestCommentaryForm()
-        context = super(RequestCommentaryMixin, self).get_context_data(**kwargs)
-
-        context['existing_commentary'] = None
-        context['doiform'] = DOIToQueryForm()
-        context['identifierform'] = IdentifierToQueryForm()
-        return context
+# class RequestCommentaryMixin(object):
+#     def get_context_data(self, **kwargs):
+#         '''Pass the DOI and identifier forms to the context.'''
+#         if 'request_commentary_form' not in kwargs:
+#             # Only intercept if not prefilled
+#             kwargs['request_commentary_form'] = RequestCommentaryForm()
+#
+#         context = super(RequestCommentaryMixin, self).get_context_data(**kwargs)
+#
+#         context['existing_commentary'] = None
+#         context['doiform'] = DOIToQueryForm()
+#         context['identifierform'] = IdentifierToQueryForm()
+#         return context
+
+
+# @method_decorator(permission_required(
+#     'scipost.can_request_commentary_pages', raise_exception=True), name='dispatch')
+# class RequestCommentary(LoginRequiredMixin, RequestCommentaryMixin, CreateView):
+#     form_class = RequestCommentaryForm
+#     template_name = 'commentaries/request_commentary.html'
+#     success_url = reverse_lazy('scipost:personal_page')
+#
+#     def get_form_kwargs(self, *args, **kwargs):
+#         '''User should be included in the arguments to have a valid form.'''
+#         form_kwargs = super(RequestCommentary, self).get_form_kwargs(*args, **kwargs)
+#         form_kwargs['user'] = self.request.user
+#         return form_kwargs
+#
+#     def form_valid(self, form):
+#         form.instance.parse_links_into_urls()
+#         messages.success(self.request, strings.acknowledge_request_commentary)
+#         return super(RequestCommentary, self).form_valid(form)
 
+@permission_required('scipost.can_request_commentary_pages', raise_exception=True)
+def request_commentary(request):
+    return render(request, 'commentaries/request_commentary.html')
 
 @method_decorator(permission_required(
     'scipost.can_request_commentary_pages', raise_exception=True), name='dispatch')
-class RequestCommentary(LoginRequiredMixin, RequestCommentaryMixin, CreateView):
-    form_class = RequestCommentaryForm
-    template_name = 'commentaries/request_commentary.html'
+class RequestPublishedArticle(CreateView):
+    form_class = RequestPublishedArticleForm
+    template_name = 'commentaries/request_published_article.html'
     success_url = reverse_lazy('scipost:personal_page')
 
-    def get_form_kwargs(self, *args, **kwargs):
-        '''User should be included in the arguments to have a valid form.'''
-        form_kwargs = super(RequestCommentary, self).get_form_kwargs(*args, **kwargs)
-        form_kwargs['user'] = self.request.user
-        return form_kwargs
-
-    def form_valid(self, form):
-        form.instance.parse_links_into_urls()
-        messages.success(self.request, strings.acknowledge_request_commentary)
-        return super(RequestCommentary, self).form_valid(form)
-
+    def get_context_data(self, **kwargs):
+        context = super(RequestPublishedArticle, self).get_context_data(**kwargs)
+        context['doi_query_form'] = DOIToQueryForm()
+        return context
 
 @permission_required('scipost.can_request_commentary_pages', raise_exception=True)
 def prefill_using_DOI(request):
     if request.method == "POST":
-        doi_form = DOIToQueryForm(request.POST)
-        identifier_form = IdentifierToQueryForm()
+        doi_query_form = DOIToQueryForm(request.POST)
         # The form checks if doi is valid and commentary doesn't already exist.
-        if doi_form.is_valid():
-            doi = doi_form.cleaned_data['doi']
+        if doi_query_form.is_valid():
+            doi = doi_query_form.cleaned_data['doi']
             crossref_data = DOICaller(doi).data
             additional_form_data = {'type': 'published', 'pub_DOI': doi}
             total_form_data = {**crossref_data, **additional_form_data}
-            commentary_form = RequestCommentaryForm(initial=total_form_data)
-            context = {
-                'request_commentary_form': commentary_form,
-                'doiform': doi_form,
-                'identifierform': identifier_form,
-            }
-            return render(request, 'commentaries/request_commentary.html', context)
+            form = RequestPublishedArticleForm(initial=total_form_data)
         else:
-            context = {
-                'request_commentary_form': RequestCommentaryForm(),
-                'doiform': doi_form,
-                'identifierform': identifier_form
-            }
-            return render(request, 'commentaries/request_commentary.html', context)
+            form = RequestPublishedArticleForm()
+
+        context = {
+            'form': form,
+            'doi_query_form': doi_query_form,
+        }
+        return render(request, 'commentaries/request_published_article.html', context)
     else:
-        raise Http404('Only accessible by POST-request.')
+        raise Http404
+
+# @permission_required('scipost.can_request_commentary_pages', raise_exception=True)
+# def request_published_article(request):
+#     if request.method == "POST":
+#         doi_form = DOIToQueryForm(request.POST)
+#         identifier_form = IdentifierToQueryForm()
+#         # The form checks if doi is valid and commentary doesn't already exist.
+#         if doi_form.is_valid():
+#             doi = doi_form.cleaned_data['doi']
+#             crossref_data = DOICaller(doi).data
+#             additional_form_data = {'type': 'published', 'pub_DOI': doi}
+#             total_form_data = {**crossref_data, **additional_form_data}
+#             commentary_form = RequestCommentaryForm(initial=total_form_data)
+#             context = {
+#                 'request_commentary_form': commentary_form,
+#                 'doiform': doi_form,
+#                 'identifierform': identifier_form,
+#             }
+#             return render(request, 'commentaries/request_commentary.html', context)
+#         else:
+#             context = {
+#                 'request_commentary_form': RequestCommentaryForm(),
+#                 'doiform': doi_form,
+#                 'identifierform': identifier_form
+#             }
+#             return render(request, 'commentaries/request_commentary.html', context)
+#     elif request.method == "GET":
+#         context = { 'form': RequestCommentaryForm() }
+#         return render(request, 'commentaries/request_published_article.html', context)
+
+
+@permission_required('scipost.can_request_commentary_pages', raise_exception=True)
+def request_arxiv_preprint(request):
+    return 1
 
 
 
@@ -181,55 +225,55 @@ def prefill_using_DOI(request):
 #     return redirect(reverse('commentaries:request_commentary'))
 
 
-@method_decorator(permission_required(
-    'scipost.can_request_commentary_pages', raise_exception=True), name='dispatch')
-class PrefillUsingIdentifierView(RequestCommentaryMixin, FormView):
-    form_class = IdentifierToQueryForm
-    template_name = 'commentaries/request_commentary.html'
-
-    def form_invalid(self, identifierform):
-        for field, errors in identifierform.errors.items():
-            for error in errors:
-                messages.warning(self.request, error)
-        return render(self.request, 'commentaries/request_commentary.html',
-                      self.get_context_data(**{}))
-
-    def form_valid(self, identifierform):
-        '''Prefill using the ArxivCaller if the Identifier is valid'''
-        caller = ArxivCaller(Commentary, identifierform.cleaned_data['identifier'])
-        caller.process()
-
-        if caller.is_valid():
-            # Prefill the form
-            metadata = caller.metadata
-            pub_title = metadata['entries'][0]['title']
-            authorlist = metadata['entries'][0]['authors'][0]['name']
-            for author in metadata['entries'][0]['authors'][1:]:
-                authorlist += ', ' + author['name']
-            arxiv_link = metadata['entries'][0]['id']
-            abstract = metadata['entries'][0]['summary']
-
-            initialdata = {
-                'type': 'preprint',
-                'metadata': metadata,
-                'pub_title': pub_title,
-                'author_list': authorlist,
-                'arxiv_identifier': identifierform.cleaned_data['identifier'],
-                'arxiv_link': arxiv_link,
-                'pub_abstract': abstract
-            }
-            context = {
-                'title': pub_title,
-                'request_commentary_form': RequestCommentaryForm(initial=initialdata)
-            }
-            messages.success(self.request, 'Arxiv completed')
-            return render(self.request, 'commentaries/request_commentary.html',
-                          self.get_context_data(**context))
-        else:
-            msg = caller.get_error_message()
-            messages.error(self.request, msg)
-            return render(self.request, 'commentaries/request_commentary.html',
-                          self.get_context_data(**{}))
+# @method_decorator(permission_required(
+#     'scipost.can_request_commentary_pages', raise_exception=True), name='dispatch')
+# class PrefillUsingIdentifierView(RequestCommentaryMixin, FormView):
+#     form_class = IdentifierToQueryForm
+#     template_name = 'commentaries/request_commentary.html'
+#
+#     def form_invalid(self, identifierform):
+#         for field, errors in identifierform.errors.items():
+#             for error in errors:
+#                 messages.warning(self.request, error)
+#         return render(self.request, 'commentaries/request_commentary.html',
+#                       self.get_context_data(**{}))
+#
+#     def form_valid(self, identifierform):
+#         '''Prefill using the ArxivCaller if the Identifier is valid'''
+#         caller = ArxivCaller(Commentary, identifierform.cleaned_data['identifier'])
+#         caller.process()
+#
+#         if caller.is_valid():
+#             # Prefill the form
+#             metadata = caller.metadata
+#             pub_title = metadata['entries'][0]['title']
+#             authorlist = metadata['entries'][0]['authors'][0]['name']
+#             for author in metadata['entries'][0]['authors'][1:]:
+#                 authorlist += ', ' + author['name']
+#             arxiv_link = metadata['entries'][0]['id']
+#             abstract = metadata['entries'][0]['summary']
+#
+#             initialdata = {
+#                 'type': 'preprint',
+#                 'metadata': metadata,
+#                 'pub_title': pub_title,
+#                 'author_list': authorlist,
+#                 'arxiv_identifier': identifierform.cleaned_data['identifier'],
+#                 'arxiv_link': arxiv_link,
+#                 'pub_abstract': abstract
+#             }
+#             context = {
+#                 'title': pub_title,
+#                 'request_commentary_form': RequestCommentaryForm(initial=initialdata)
+#             }
+#             messages.success(self.request, 'Arxiv completed')
+#             return render(self.request, 'commentaries/request_commentary.html',
+#                           self.get_context_data(**context))
+#         else:
+#             msg = caller.get_error_message()
+#             messages.error(self.request, msg)
+#             return render(self.request, 'commentaries/request_commentary.html',
+#                           self.get_context_data(**{}))
 
 
 @permission_required('scipost.can_vet_commentary_requests', raise_exception=True)
-- 
GitLab