Passed
Pull Request — master (#41)
by
unknown
01:22
created

SubmissionValidationSummaryView.get_context_data()   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 10
rs 9.9
c 0
b 0
f 0
cc 2
nop 2
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Created on Tue Jul 24 15:49:23 2018
5
6
@author: Paolo Cozzi <[email protected]>
7
"""
8
9
import logging
10
import ast
11
import re
12
from django.core.exceptions import ObjectDoesNotExist
13
14
from django.contrib import messages
15
from django.contrib.auth.mixins import LoginRequiredMixin
16
from django.db.models import Q
17
from django.http import HttpResponseRedirect
18
from django.views.generic import (
19
    CreateView, DetailView, ListView, UpdateView, DeleteView)
20
from django.shortcuts import get_object_or_404, redirect
21
from django.urls import reverse_lazy, reverse
22
23
from common.constants import (
24
    WAITING, ERROR, SUBMITTED, NEED_REVISION, CRYOWEB_TYPE, CRB_ANIM_TYPE,
25
    VALIDATION_MESSAGES)
26
from common.helpers import get_deleted_objects
27
from common.views import OwnerMixin
28
from cryoweb.tasks import import_from_cryoweb
29
from image_app.models import Submission, Name, Animal, Sample
30
from crbanim.tasks import ImportCRBAnimTask
31
from validation.helpers import construct_validation_message
32
from validation.models import ValidationSummary
33
from animals.tasks import BatchUpdateAnimals
34
35
from .forms import SubmissionForm, ReloadForm
36
37
# Get an instance of a logger
38
logger = logging.getLogger(__name__)
39
40
41
class CreateSubmissionView(LoginRequiredMixin, CreateView):
42
    form_class = SubmissionForm
43
    model = Submission
44
45
    # template name is derived from model position and views type.
46
    # in this case, ir will be 'image_app/submission_form.html' so
47
    # i need to clearly specify it
48
    template_name = "submissions/submission_form.html"
49
50
    def form_invalid(self, form):
51
        messages.error(
52
            self.request,
53
            message="Please correct the errors below",
54
            extra_tags="alert alert-dismissible alert-danger")
55
56
        return super(CreateSubmissionView, self).form_invalid(form)
57
58
    # add user to this object
59
    def form_valid(self, form):
60
        self.object = form.save(commit=False)
61
        self.object.owner = self.request.user
62
63
        # I will have a different loading function accordingly with data type
64
        if self.object.datasource_type == CRYOWEB_TYPE:
65
            # update object and force status
66
            self.object.message = "waiting for data loading"
67
            self.object.status = WAITING
68
            self.object.save()
69
70
            # a valid submission start a task
71
            res = import_from_cryoweb.delay(self.object.pk)
72
            logger.info(
73
                "Start cryoweb importing process with task %s" % res.task_id)
74
75
        # I will have a different loading function accordingly with data type
76
        elif self.object.datasource_type == CRB_ANIM_TYPE:
77
            # update object and force status
78
            self.object.message = "waiting for data loading"
79
            self.object.status = WAITING
80
            self.object.save()
81
82
            # create a task
83
            my_task = ImportCRBAnimTask()
84
85
            # a valid submission start a task
86
            res = my_task.delay(self.object.pk)
87
            logger.info(
88
                "Start crbanim importing process with task %s" % res.task_id)
89
90
        else:
91
            message = "{datasource} import is not implemented".format(
92
                datasource=self.object.get_datasource_type_display())
93
94
            self.object.message = message
95
            self.object.status = ERROR
96
            self.object.save()
97
98
            logger.error(message)
99
100
        # a redirect to self.object.get_absolute_url()
101
        return HttpResponseRedirect(self.get_success_url())
102
103
104
class MessagesSubmissionMixin(object):
105
    """Display messages in SubmissionViews"""
106
107
    # https://stackoverflow.com/a/45696442
108
    def get_context_data(self, **kwargs):
109
        data = super().get_context_data(**kwargs)
110
111
        # get the submission message
112
        message = self.submission.message
113
114
        # check if data are loaded or not
115
        if self.submission.status in [WAITING, SUBMITTED]:
116
            messages.warning(
117
                request=self.request,
118
                message=message,
119
                extra_tags="alert alert-dismissible alert-warning")
120
121
        elif self.submission.status in [ERROR, NEED_REVISION]:
122
            messages.error(
123
                request=self.request,
124
                message=message,
125
                extra_tags="alert alert-dismissible alert-danger")
126
127
        elif message is not None and message != '':
128
            messages.info(
129
                request=self.request,
130
                message=message,
131
                extra_tags="alert alert-dismissible alert-info")
132
133
        return data
134
135
136
class DetailSubmissionView(MessagesSubmissionMixin, OwnerMixin, DetailView):
137
    model = Submission
138
    template_name = "submissions/submission_detail.html"
139
140
    def get_context_data(self, **kwargs):
141
        # pass self.object to a new submission attribute in order to call
142
        # MessagesSubmissionMixin.get_context_data()
143
        self.submission = self.object
144
145
        # Call the base implementation first to get a context
146
        context = super(DetailSubmissionView, self).get_context_data(**kwargs)
147
148
        # add submission report to context
149
        validation_summary = construct_validation_message(self.submission)
150
151
        # HINT: is this computational intensive?
152
        context["validation_summary"] = validation_summary
153
154
        return context
155
156
157
class SubmissionValidationSummaryView(OwnerMixin, DetailView):
158
    model = Submission
159
    template_name = "submissions/submission_validation_summary.html"
160
161
    def get_context_data(self, **kwargs):
162
        context = super().get_context_data(**kwargs)
163
        summary_type = self.kwargs['type']
164
        try:
165
            context['validation_summary'] = self.object.validationsummary_set\
166
                .get(type=summary_type)
167
        except ObjectDoesNotExist:
168
            context['validation_summary'] = None
169
        context['submission'] = Submission.objects.get(pk=self.kwargs['pk'])
170
        return context
171
172
173
class SubmissionValidationSummaryFixErrorsView(OwnerMixin, ListView):
174
    template_name = "submissions/submission_validation_summary_fix_errors.html"
175
176
    def get_queryset(self):
177
        ids = list()
178
        summary_type = self.kwargs['type']
179
        submission = Submission.objects.get(pk=self.kwargs['pk'])
180
        validation_summary = ValidationSummary.objects.get(
181
            submission=submission, type=summary_type)
182
        request_message = self.kwargs['msg']
183
        for message in validation_summary.messages:
184
            message = ast.literal_eval(message)
185
            if message['message'] == request_message:
186
                ids = message['ids']
187
        if summary_type == 'animal':
188
            return Animal.objects.filter(id__in=ids)
189
        elif summary_type == 'sample':
190
            return Sample.objects.filter(id__in=ids)
191
192
    def get_context_data(self, **kwargs):
193
        # Call the base implementation first to get a context
194
        context = super(
195
            SubmissionValidationSummaryFixErrorsView, self
196
        ).get_context_data(**kwargs)
197
198
        # add submission to context
199
        msg = self.kwargs['msg']
200
        context["message"] = msg
201
        context["type"] = self.kwargs['type']
202
203
        if re.search(VALIDATION_MESSAGES['coordinate_check'], msg):
204
            context['attributes_to_show'] = [
205
                'birth_location_latitude',
206
                'birth_location_longitude',
207
                'birth_location_accuracy'
208
            ]
209
            context['attributes_to_edit'] = ['birth_location']
210
        # TODO add checks for other messages
211
        else:
212
            context['attributes_to_show'] = []
213
            context['attributes_to_edit'] = []
214
        context['submission'] = Submission.objects.get(pk=self.kwargs['pk'])
215
216
        return context
217
218
219
# a detail view since I need to operate on a submission object
220
# HINT: rename to a more informative name?
221
class EditSubmissionView(MessagesSubmissionMixin, OwnerMixin, ListView):
222
    template_name = "submissions/submission_edit.html"
223
    paginate_by = 10
224
225
    def get_queryset(self):
226
        """Subsetting names relying submission id"""
227
        self.submission = get_object_or_404(
228
            Submission,
229
            pk=self.kwargs['pk'],
230
            owner=self.request.user)
231
232
        # unknown animals should be removed from a submission. They have no
233
        # data in animal table nor sample
234
        return Name.objects.select_related(
235
                "validationresult",
236
                "animal",
237
                "sample").filter(
238
            Q(submission=self.submission) & (
239
                Q(animal__isnull=False) | Q(sample__isnull=False))
240
            ).order_by('id')
241
242 View Code Duplication
    def dispatch(self, request, *args, **kwargs):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
243
        handler = super(EditSubmissionView, self).dispatch(
244
                request, *args, **kwargs)
245
246
        # here I've done get_queryset. Check for submission status
247
        if hasattr(self, "submission") and not self.submission.can_edit():
248
            message = "Cannot edit submission: current status is: %s" % (
249
                    self.submission.get_status_display())
250
251
            logger.warning(message)
252
            messages.warning(
253
                request=self.request,
254
                message=message,
255
                extra_tags="alert alert-dismissible alert-warning")
256
257
            return redirect(self.submission.get_absolute_url())
258
259
        return handler
260
261
    def get_context_data(self, **kwargs):
262
        # Call the base implementation first to get a context
263
        context = super(EditSubmissionView, self).get_context_data(**kwargs)
264
265
        # add submission to context
266
        context["submission"] = self.submission
267
268
        return context
269
270
271
class ListSubmissionsView(OwnerMixin, ListView):
272
    model = Submission
273
    template_name = "submissions/submission_list.html"
274
    ordering = ['-created_at']
275
    paginate_by = 10
276
277
278
class ReloadSubmissionView(OwnerMixin, UpdateView):
279
    form_class = ReloadForm
280
    model = Submission
281
    template_name = 'submissions/submission_reload.html'
282
283
    def form_invalid(self, form):
284
        messages.error(
285
            self.request,
286
            message="Please correct the errors below",
287
            extra_tags="alert alert-dismissible alert-danger")
288
289
        return super(ReloadSubmissionView, self).form_invalid(form)
290
291
    def form_valid(self, form):
292
        self.object = form.save(commit=False)
293
294
        # update object and force status
295
        self.object.message = "waiting for data loading"
296
        self.object.status = WAITING
297
        self.object.save()
298
299
        # HINT: can I change datasource type?
300
301
        # call the proper method
302
        if self.object.datasource_type == CRYOWEB_TYPE:
303
            # a valid submission start a task
304
            res = import_from_cryoweb.delay(self.object.pk)
305
            logger.info(
306
                "Start cryoweb reload process with task %s" % res.task_id)
307
308
        elif self.object.datasource_type == CRB_ANIM_TYPE:
309
            # a valid submission start a task
310
            my_task = ImportCRBAnimTask()
311
312
            # a valid submission start a task
313
            res = my_task.delay(self.object.pk)
314
            logger.info(
315
                "Start crbanim reload process with task %s" % res.task_id)
316
317
        else:
318
            # this is not an invalid form. Template is not implemented
319
            # it is a error in our application
320
            # TODO: call the proper method
321
            message = "{datasource} reload is not implemented".format(
322
                datasource=self.object.get_datasource_type_display())
323
324
            messages.error(
325
                self.request,
326
                message,
327
                extra_tags="alert alert-dismissible alert-danger")
328
329
            # set an error message to this submission
330
            self.object.message = message
331
            self.object.status = ERROR
332
            self.object.save()
333
334
        # a redirect to self.object.get_absolute_url()
335
        return HttpResponseRedirect(self.get_success_url())
336
337
338
class DeleteSubmissionView(OwnerMixin, DeleteView):
339
    model = Submission
340
    template_name = "submissions/submission_confirm_delete.html"
341
    success_url = reverse_lazy('image_app:dashboard')
342
343 View Code Duplication
    def dispatch(self, request, *args, **kwargs):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
344
        handler = super(DeleteSubmissionView, self).dispatch(
345
                request, *args, **kwargs)
346
347
        # here I've done get_queryset. Check for submission status
348
        if hasattr(self, "object") and not self.object.can_edit():
349
            message = "Cannot delete %s: submission status is: %s" % (
350
                    self.object, self.object.get_status_display())
351
352
            logger.warning(message)
353
            messages.warning(
354
                request=self.request,
355
                message=message,
356
                extra_tags="alert alert-dismissible alert-warning")
357
358
            return redirect(self.object.get_absolute_url())
359
360
        return handler
361
362
    # https://stackoverflow.com/a/39533619/4385116
363
    def get_context_data(self, **kwargs):
364
        # determining related objects
365
        # TODO: move this to a custom AJAX call
366
        context = super().get_context_data(**kwargs)
367
368
        deletable_objects, model_count, protected = get_deleted_objects(
369
            [self.object])
370
371
        # get only sample and animals from model_count
372
        info_deleted = {}
373
374
        items = ['animals', 'samples']
375
376
        for item in items:
377
            if item in model_count:
378
                info_deleted[item] = model_count[item]
379
380
        # add info to context
381
        context['info_deleted'] = dict(info_deleted).items()
382
383
        return context
384
385
    # https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/DeleteView/#delete
386
    def delete(self, request, *args, **kwargs):
387
        """
388
        Add a message after calling base delete method
389
        """
390
391
        httpresponseredirect = super().delete(request, *args, **kwargs)
392
393
        message = "Submission %s was successfully deleted" % self.object.title
394
        logger.info(message)
395
396
        messages.info(
397
            request=self.request,
398
            message=message,
399
            extra_tags="alert alert-dismissible alert-info")
400
401
        return httpresponseredirect
402
403
404
def fix_validation(request, pk, type):
405
    # Fetch all required ids from input names and use it as keys
406
    keys_to_fix = dict()
407
    for key_to_fix in request.POST:
408
        if 'to_edit' in key_to_fix:
409
            keys_to_fix[int(re.search('to_edit(.*)', key_to_fix).groups()[0])] \
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable int does not seem to be defined.
Loading history...
410
                = request.POST[key_to_fix]
411
412
    submission = Submission.objects.get(pk=pk)
413
    submission.message = "waiting for data updating"
414
    submission.status = WAITING
415
    submission.save()
416
417
    # Update validation summary
418
    summary_obj, created = ValidationSummary.objects.get_or_create(
419
        submission=submission, type=type)
420
    summary_obj.submission = submission
421
    summary_obj.pass_count = 0
422
    summary_obj.warning_count = 0
423
    summary_obj.error_count = 0
424
    summary_obj.issues_count = 0
425
    summary_obj.validation_known_count = 0
426
    summary_obj.messages = list()
427
    summary_obj.save()
428
429
    # create a task
430
    if type == 'animal':
431
        my_task = BatchUpdateAnimals()
432
    # TODO add task for samples
433
434
    # a valid submission start a task
435
    res = my_task.delay(pk, keys_to_fix)
0 ignored issues
show
introduced by
The variable my_task does not seem to be defined in case type == 'animal' on line 430 is False. Are you sure this can never be the case?
Loading history...
436
    logger.info(
437
        "Start crbanim importing process with task %s" % res.task_id)
438
    return HttpResponseRedirect(reverse('submissions:detail', args=(pk,)))
439