Passed
Pull Request — master (#41)
by
unknown
05:45
created

submissions.views.FixValidation.post()   B

Complexity

Conditions 5

Size

Total Lines 44
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

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