Completed
Pull Request — master (#41)
by
unknown
08:12
created

ReloadSubmissionView.form_invalid()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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