Skip to content

Commit

Permalink
Merge pull request #149 from brain-image-library/feature/submitbutton
Browse files Browse the repository at this point in the history
WIP Developing submit collection to be validated page
  • Loading branch information
ltuite96 authored Mar 15, 2021
2 parents 3344f62 + 3d5350a commit 1a1eec2
Show file tree
Hide file tree
Showing 9 changed files with 252 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ __pycache__/
*.py[cod]
*.swp
*venv
bil_site/settings.py
site.cfg
tags
.~lock*.xls#
Expand Down
12 changes: 11 additions & 1 deletion bil_site/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,14 @@

MESSAGE_TAGS = {
messages.ERROR: 'danger'
}
}

#Email Settings
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_HOST_USER = 'ltuite96@psc.edu'
EMAIL_HOST_PASSWORD = 'qxcwnowpqqxwtsmc'
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#EMAIL_USE_SSL = False

6 changes: 5 additions & 1 deletion ingest/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ def save(self, *args, **kwargs):
obj.user = self.user
obj.save()
return obj

class collection_send(forms.ModelForm):
class Meta:
model = Collection
fields = collection_fields


class CollectionForm(forms.ModelForm):

Expand Down
39 changes: 39 additions & 0 deletions ingest/static/ingest/sendemail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
function collection_send() {
const csrftoken = Cookies.get('csrftoken');
let output_rows = []
$('tbody>tr').each(function(i, e){
let $e = $(e);
// $e is the tr element
let row_is_checked = $e.find('#collection_is_checked').is(':checked');
// row_is_checked is a boolean of whether that row is checked or not
let bil_uuid = $e.find('#bilUuid')
if(row_is_checked)
output_rows.push({
"bil_uuid": bil_uuid.text()
}
)
});
fetch(`${window.origin}/ingest/collection_send/`, {
method: "POST",
credentials: "include",
body: JSON.stringify(output_rows),
cache: "no-cache",
headers: new Headers({
"X-CSRFToken": csrftoken,
"content-type": "application/json"
})
})
.then(function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status code: ${response.status}');
return;
}
response.json().then(function(data) {
console.log(data);
window.location.replace(data['url']);
});
})
.catch(function(error) {
console.log("Fetch error: " + error);
});
}
56 changes: 56 additions & 0 deletions ingest/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,63 @@ class Meta:
exclude = ['celery_task_id_submission', 'celery_task_id_validation', 'user']
template_name = 'ingest/bootstrap_ingest.html'

class CollectionRequestTable(tables.Table):
""" The table used in the collection list. """

# We use a collection's id as a link to the corresponding collection
# detail.
id = tables.LinkColumn(
'ingest:collection_detail',
verbose_name="",
args=[A('pk')],
# commenting out below line because i think it is interfering with template on ingest/template/submit_collection
text=format_html('<input type="checkbox" name = "submit_for_validation" id = "submit_for_validation" class="form-check-input"></checkbox>'))
#text=format_html('<span class="glyphicon glyphicon-cog"></span>'),
#attrs={'a': {'class': "btn btn-info", 'role': "button"}})
description = tables.Column()

def render_project_description(self, value):
""" Ellipsize the project description if it's too long. """
limit_len = 32
value = value if len(value) < limit_len else value[:limit_len] + "…"
return value

def render_locked(self, value):
if value:
value = format_html('<i class="fa fa-lock"></i>')
else:
value = format_html('<i class="fa fa-unlock"></i>')
return value

def render_submission_status(self, value):
""" Show the status as an icon. """
if value == "Not submitted":
value = format_html('<i class="fa fa-minus" style="color:blue"></i>')
elif value == "Success":
value = format_html('<i class="fa fa-check" style="color:green"></i>')
elif value == "Pending":
value = format_html('<i class="fa fa-clock" style="color:yellow"></i>')
elif value == "Failed":
value = format_html('<i class="fa fa-exclamation-circle" style="color:red"></i>')
return value

def render_validation_status(self, value):
""" Show the status as an icon. """
if value == "Not submitted":
value = format_html('<button type="button" class="btn btn-primary">Not Submitted</button>')
#value = format_html('<i class="fa fa-minus" style="color:blue"></i>')
elif value == "Success":
value = format_html('<i class="fa fa-check" style="color:green"></i>')
elif value == "Pending":
value = format_html('<i class="fa fa-clock" style="color:yellow"></i>')
elif value == "Failed":
value = format_html('<i class="fa fa-exclamation-circle" style="color:red"></i>')
return value

class Meta:
model = Collection
exclude = ['celery_task_id_submission', 'celery_task_id_validation', 'user']
template_name = 'ingest/bootstrap_ingest.html'

class ImageMetadataTable(tables.Table):
""" The table used in the image metadata list. """
Expand Down
3 changes: 3 additions & 0 deletions ingest/templates/ingest/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Submit <span class="caret"> </span></a>
<ul class="dropdown-menu">
<li><a href="{% url 'ingest:submit_request_collection_list' %}">Submit Validation Request</a></li>
</ul>
</li>

<!-- This is old stuff -- delete it
Expand Down
56 changes: 56 additions & 0 deletions ingest/templates/ingest/submit_request_collection_list.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<head>
<script src="/static/ingest/sendemail.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>
</head>
{% extends 'ingest/wide.html' %}
{% load bootstrap4 %}
{% block wide %}
<h1>Submit Request to Publicize Collection</h1>
<p>Select checkboxes for each collection to request validation and publication. This will submit a ticket to BIL support and be processed</p>
<form id="rowform">
{% csrf_token %}
<table id="CollectionTable" class="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Description</th>
<th>Organization Lab</th>
<th>Lab Name</th>
<th>Project Funder ID</th>
<th>Project Funder</th>
<th>BIL Uuid</th>
<th>Data Path</th>
<th>Locked</th>
<th>Submission Status</th>
<th>Validation Status</th>
</tr>
</thead>
<tbody>
{% for collection in collections %}
<tr>
<td><input type="checkbox" id="collection_is_checked"></td>
<td>{{collection.name}}</td>
<td>{{collection.description}}</td>
<td>{{collection.organization_name}}</td>
<td>{{collection.lab_name}}</td>
<td>{{collection.project_funder_id}}</td>
<td>{{collection.project_funder}}</td>
<td id="bilUuid">{{collection.bil_uuid}}</td>
<td>{{collection.data_path}}</td>
<td>{{collection.locked}}</td>
<td>{{collection.submission_status}}</td>
<td>{{collection.validation_status}}</td>
</tr>
{% endfor %}
</table>
</form>
<button class="btn btn-primary" onclick="collection_send();">Submit Validation Request</button>
<hr>

<a href="{% url 'ingest:index' %}">
<button class="cancel btn btn btn-primary" value="ignore" formnovalidate="">Cancel</button>
</a>

{% endblock %}

4 changes: 3 additions & 1 deletion ingest/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,7 @@
path('collection_submission_results/<int:pk>', views.collection_submission_results, name='collection_submission_results'),
re_path(r'^collection_create/$', views.collection_create, name='collection_create'),
re_path(r'^collection_list/$', views.CollectionList.as_view(), name='collection_list'),
re_path(r'^submit_validate_collection_list/$', views.SubmitValidateCollectionList.as_view(), name='submit_validate_collection_list')
re_path(r'^submit_validate_collection_list/$', views.SubmitValidateCollectionList.as_view(), name='submit_validate_collection_list'),
re_path(r'^submit_request_collection_list/$', views.SubmitRequestCollectionList.as_view(), name ='submit_request_collection_list'),
re_path(r'^collection_send/$', views.collection_send, name = 'collection_send')
]
81 changes: 78 additions & 3 deletions ingest/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.urls import reverse
from django.views.generic import DetailView
from django.views.generic.edit import UpdateView, DeleteView
from django.core.cache import cache
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist

from django.core.mail import send_mail
from django.http import HttpResponse
from django.http import JsonResponse

from django_filters.views import FilterView
from django_tables2.views import SingleTableMixin
Expand All @@ -28,17 +31,18 @@
from .forms import ImageMetadataForm
from .forms import DescriptiveMetadataForm
from .forms import UploadForm
from .forms import collection_send
from .models import UUID
from .models import Collection
from .models import ImageMetadata
from .models import DescriptiveMetadata
from .tables import CollectionTable
from .tables import ImageMetadataTable
from .tables import DescriptiveMetadataTable

from .tables import CollectionRequestTable
import uuid
import datetime

import json

def logout(request):
messages.success(request, "You've successfully logged out")
Expand Down Expand Up @@ -261,6 +265,34 @@ class ImageMetadataDelete(LoginRequiredMixin, DeleteView):
# and deleting COLLECTIONS.


@login_required
def collection_send(request):
content = json.loads(request.body)
print(content)
items = []
user_name = request.user
for item in content:
items.append(item['bil_uuid'])

if request.method == "POST":
subject = '[BIL Validations] New Validation Request'
sender = 'ltuite96@psc.edu'
message = F'The following collections have been requested to be validated {items} by {user_name}@psc.edu'
recipient = ['ltuite96@psc.edu']

send_mail(
subject,
message,
sender,
recipient
)
print(message)
print(user_name)
#messages.success(request, 'Request succesfully sent')
return HttpResponse(json.dumps({'url': reverse('ingest:index')}))
#return HttpResponse(status=200)
#success_url = reverse_lazy('ingest:collection_list')

@login_required
def collection_create(request):
""" Create a collection. """
Expand Down Expand Up @@ -372,6 +404,49 @@ def get_filterset_kwargs(self, filterset_class):
kwargs["data"] = {"submit_status": "NOT_SUBMITTED"}
return kwargs

class SubmitRequestCollectionList(LoginRequiredMixin, SingleTableMixin, FilterView):
""" A list of all a user's collections. """

table_class = CollectionRequestTable
model = Collection
template_name = 'ingest/submit_request_collection_list.html'
filterset_class = CollectionFilter

def get_queryset(self, **kwargs):
return Collection.objects.filter(user=self.request.user)

def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['collections'] = Collection.objects.filter(user=self.request.user)
return context

def get_filterset_kwargs(self, filterset_class):
""" Sets the default collection filter status. """
kwargs = super().get_filterset_kwargs(filterset_class)
if kwargs["data"] is None:
kwargs["data"] = {"submit_status": "NOT_SUBMITTED"}
return kwargs
success_url = reverse_lazy('ingest:collection_list')
#def send_email_request(request):
# checked_ids = []
# if request.method == "POST":
# for i in rows:
# if submit-for-validation == True:
# checked_id = request.collection_id
# checked_id.append(checked_id)
# subject = '[BIL Validations] New Validation Request'
# sender = 'ltuite96@psc.edu'
# message = F'The following collections have been requested of validaton {checked_id}'
# recipient = 'ltuite96@psc.edu'

# send_mail(
# subject,
# message,
# sender,
# recipient
# )
# return print('message was sent i hope')
class CollectionList(LoginRequiredMixin, SingleTableMixin, FilterView):
""" A list of all a user's collections. """

Expand Down

0 comments on commit 1a1eec2

Please sign in to comment.