Completed
Pull Request — master (#41)
by
unknown
06:07
created

submissions.views   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 448
Duplicated Lines 8.04 %

Importance

Changes 0
Metric Value
wmc 41
eloc 278
dl 36
loc 448
rs 9.1199
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
B MessagesSubmissionMixin.get_context_data() 0 26 5
A CreateSubmissionView.form_invalid() 0 7 1
A DetailSubmissionView.get_context_data() 0 15 1
A CreateSubmissionView.form_valid() 0 47 3
A DeleteSubmissionView.delete() 0 16 1
A EditSubmissionView.dispatch() 18 18 3
A EditSubmissionView.get_context_data() 0 8 1
A DeleteSubmissionView.get_context_data() 0 21 3
B FixValidation.post() 0 38 5
A SubmissionValidationSummaryView.get_context_data() 0 21 4
A SubmissionValidationSummaryFixErrorsView.get_queryset() 0 14 3
A SubmissionValidationSummaryFixErrorsView.get_context_data() 0 19 3
A ReloadSubmissionView.form_valid() 0 37 3
A ReloadSubmissionView.form_invalid() 0 7 1
A DeleteSubmissionView.dispatch() 18 18 3
A EditSubmissionView.get_queryset() 0 16 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like submissions.views often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
            validation_summary = self.object.validationsummary_set\
175
                .get(type=summary_type)
176
            context['validation_summary'] = validation_summary
177
            editable = list()
178
            for message in validation_summary.messages:
179
                message = ast.literal_eval(message)
180
                if uid2biosample(message['offending_column']) in \
181
                        [val for sublist in VALIDATION_MESSAGES_ATTRIBUTES for
182
                         val in sublist]:
183
                    editable.append(True)
184
                else:
185
                    editable.append(False)
186
            context['editable'] = editable
187
        except ObjectDoesNotExist:
188
            context['validation_summary'] = None
189
        context['submission'] = Submission.objects.get(pk=self.kwargs['pk'])
190
        return context
191
192
193
class SubmissionValidationSummaryFixErrorsView(OwnerMixin, ListView):
194
    template_name = "submissions/submission_validation_summary_fix_errors.html"
195
196
    def get_queryset(self):
197
        self.summary_type = self.kwargs['type']
198
        self.submission = Submission.objects.get(pk=self.kwargs['pk'])
199
        self.validation_summary = ValidationSummary.objects.get(
200
            submission=self.submission, type=self.summary_type)
201
        self.message = ast.literal_eval(self.validation_summary.messages[
202
                                            int(self.kwargs['message_counter'])
203
                                        ])
204
        self.offending_column = uid2biosample(
205
            self.message['offending_column'])
206
        if self.summary_type == 'animal':
207
            return Animal.objects.filter(id__in=self.message['ids'])
208
        elif self.summary_type == 'sample':
209
            return Sample.objects.filter(id__in=self.message['ids'])
210
211
    def get_context_data(self, **kwargs):
212
        # Call the base implementation first to get a context
213
        context = super(
214
            SubmissionValidationSummaryFixErrorsView, self
215
        ).get_context_data(**kwargs)
216
217
        # add submission to context
218
        context["message"] = self.message
219
        context["type"] = self.summary_type
220
        context['attribute_to_edit'] = self.offending_column
221
        for attributes in VALIDATION_MESSAGES_ATTRIBUTES:
222
            if self.offending_column in attributes:
223
                context['attributes_to_show'] = [
224
                    attr for attr in attributes if attr != self.offending_column
225
                ]
226
        context['submission'] = self.submission
227
        context['error_type'] = 'coordinate_check'
228
229
        return context
230
231
232
# a detail view since I need to operate on a submission object
233
# HINT: rename to a more informative name?
234
class EditSubmissionView(MessagesSubmissionMixin, OwnerMixin, ListView):
235
    template_name = "submissions/submission_edit.html"
236
    paginate_by = 10
237
238
    def get_queryset(self):
239
        """Subsetting names relying submission id"""
240
        self.submission = get_object_or_404(
241
            Submission,
242
            pk=self.kwargs['pk'],
243
            owner=self.request.user)
244
245
        # unknown animals should be removed from a submission. They have no
246
        # data in animal table nor sample
247
        return Name.objects.select_related(
248
                "validationresult",
249
                "animal",
250
                "sample").filter(
251
            Q(submission=self.submission) & (
252
                Q(animal__isnull=False) | Q(sample__isnull=False))
253
            ).order_by('id')
254
255 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...
256
        handler = super(EditSubmissionView, self).dispatch(
257
                request, *args, **kwargs)
258
259
        # here I've done get_queryset. Check for submission status
260
        if hasattr(self, "submission") and not self.submission.can_edit():
261
            message = "Cannot edit submission: current status is: %s" % (
262
                    self.submission.get_status_display())
263
264
            logger.warning(message)
265
            messages.warning(
266
                request=self.request,
267
                message=message,
268
                extra_tags="alert alert-dismissible alert-warning")
269
270
            return redirect(self.submission.get_absolute_url())
271
272
        return handler
273
274
    def get_context_data(self, **kwargs):
275
        # Call the base implementation first to get a context
276
        context = super(EditSubmissionView, self).get_context_data(**kwargs)
277
278
        # add submission to context
279
        context["submission"] = self.submission
280
281
        return context
282
283
284
class ListSubmissionsView(OwnerMixin, ListView):
285
    model = Submission
286
    template_name = "submissions/submission_list.html"
287
    ordering = ['-created_at']
288
    paginate_by = 10
289
290
291
class ReloadSubmissionView(OwnerMixin, UpdateView):
292
    form_class = ReloadForm
293
    model = Submission
294
    template_name = 'submissions/submission_reload.html'
295
296
    def form_invalid(self, form):
297
        messages.error(
298
            self.request,
299
            message="Please correct the errors below",
300
            extra_tags="alert alert-dismissible alert-danger")
301
302
        return super(ReloadSubmissionView, self).form_invalid(form)
303
304
    def form_valid(self, form):
305
        self.object = form.save(commit=False)
306
307
        # update object and force status
308
        self.object.message = "waiting for data loading"
309
        self.object.status = WAITING
310
        self.object.save()
311
312
        # HINT: can I change datasource type?
313
314
        # call the proper method
315
        if self.object.datasource_type == CRYOWEB_TYPE:
316
            # a valid submission start a task
317
            res = import_from_cryoweb.delay(self.object.pk)
318
            logger.info(
319
                "Start cryoweb reload process with task %s" % res.task_id)
320
321
        elif self.object.datasource_type == CRB_ANIM_TYPE:
322
            # a valid submission start a task
323
            my_task = ImportCRBAnimTask()
324
325
            # a valid submission start a task
326
            res = my_task.delay(self.object.pk)
327
            logger.info(
328
                "Start crbanim reload process with task %s" % res.task_id)
329
330
        else:
331
            # a valid submission start a task
332
            my_task = ImportTemplateTask()
333
334
            # a valid submission start a task
335
            res = my_task.delay(self.object.pk)
336
            logger.info(
337
                "Start template reload process with task %s" % res.task_id)
338
339
        # a redirect to self.object.get_absolute_url()
340
        return HttpResponseRedirect(self.get_success_url())
341
342
343
class DeleteSubmissionView(OwnerMixin, DeleteView):
344
    model = Submission
345
    template_name = "submissions/submission_confirm_delete.html"
346
    success_url = reverse_lazy('image_app:dashboard')
347
348 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...
349
        handler = super(DeleteSubmissionView, self).dispatch(
350
                request, *args, **kwargs)
351
352
        # here I've done get_queryset. Check for submission status
353
        if hasattr(self, "object") and not self.object.can_edit():
354
            message = "Cannot delete %s: submission status is: %s" % (
355
                    self.object, self.object.get_status_display())
356
357
            logger.warning(message)
358
            messages.warning(
359
                request=self.request,
360
                message=message,
361
                extra_tags="alert alert-dismissible alert-warning")
362
363
            return redirect(self.object.get_absolute_url())
364
365
        return handler
366
367
    # https://stackoverflow.com/a/39533619/4385116
368
    def get_context_data(self, **kwargs):
369
        # determining related objects
370
        # TODO: move this to a custom AJAX call
371
        context = super().get_context_data(**kwargs)
372
373
        deletable_objects, model_count, protected = get_deleted_objects(
374
            [self.object])
375
376
        # get only sample and animals from model_count
377
        info_deleted = {}
378
379
        items = ['animals', 'samples']
380
381
        for item in items:
382
            if item in model_count:
383
                info_deleted[item] = model_count[item]
384
385
        # add info to context
386
        context['info_deleted'] = dict(info_deleted).items()
387
388
        return context
389
390
    # https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/DeleteView/#delete
391
    def delete(self, request, *args, **kwargs):
392
        """
393
        Add a message after calling base delete method
394
        """
395
396
        httpresponseredirect = super().delete(request, *args, **kwargs)
397
398
        message = "Submission %s was successfully deleted" % self.object.title
399
        logger.info(message)
400
401
        messages.info(
402
            request=self.request,
403
            message=message,
404
            extra_tags="alert alert-dismissible alert-info")
405
406
        return httpresponseredirect
407
408
409
class FixValidation(View, OwnerMixin):
410
    def post(self, request, **kwargs):
411
        # Fetch all required ids from input names and use it as keys
412
        keys_to_fix = dict()
413
        for key_to_fix in request.POST:
414
            if 'to_edit' in key_to_fix:
415
                keys_to_fix[
416
                    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...
417
                    = request.POST[key_to_fix]
418
419
        pk = self.kwargs['pk']
420
        record_type = self.kwargs['record_type']
421
        attribute_to_edit = self.kwargs['attribute_to_edit']
422
423
        submission = Submission.objects.get(pk=pk)
424
        submission.message = "waiting for data updating"
425
        submission.status = WAITING
426
        submission.save()
427
428
        # Update validation summary
429
        summary_obj, created = ValidationSummary.objects.get_or_create(
430
            submission=submission, type=record_type)
431
        summary_obj.submission = submission
432
        summary_obj.reset()
433
434
        # create a task
435
        if record_type == 'animal':
436
            my_task = BatchUpdateAnimals()
437
        elif record_type == 'sample':
438
            my_task = BatchUpdateSamples()
439
        else:
440
            return HttpResponseRedirect(
441
                reverse('submissions:detail', args=(pk,)))
442
443
        # a valid submission start a task
444
        res = my_task.delay(pk, keys_to_fix, attribute_to_edit)
445
        logger.info(
446
            "Start fix validation process with task %s" % res.task_id)
447
        return HttpResponseRedirect(reverse('submissions:detail', args=(pk,)))
448