Completed
Pull Request — master (#434)
by Vijay
31s
created

workshop_list()   F

Complexity

Conditions 12

Size

Total Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 63
cc 12
rs 2.8097

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like workshop_list() 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
from django.contrib.auth.decorators import login_required
2
from django.views.decorators.csrf import csrf_exempt
3
from django.core.urlresolvers import reverse, reverse_lazy
4
# from django.db.models import Q
5
from django.contrib.sites.models import Site
6
from django.http import HttpResponseRedirect, JsonResponse
7
from django.shortcuts import get_object_or_404
8
from django.shortcuts import redirect, render
9
from django.template import loader
10
from django.views import generic
11
12
from braces import views
13
from wye.base.emailer_html import send_email_to_list
14
from wye.organisations.models import Organisation
15
from wye.profiles.models import Profile
16
# from wye.regions.models import RegionalLead
17
from wye.base.constants import WorkshopStatus
18
19
from wye.social.sites.twitter import send_tweet
20
from wye.base.views import verify_user_profile
21
from .forms import (
22
    WorkshopForm,
23
    WorkshopEditForm,
24
    WorkshopFeedbackForm,
25
    WorkshopListForm,
26
    WorkshopVolunteer)
27
from .mixins import (
28
    WorkshopEmailMixin,
29
    WorkshopAccessMixin
30
)
31
from .models import Workshop, WorkshopFeedBack
32
33
34
@login_required
35
@verify_user_profile
36
def workshop_list(request):
37
    template_name = 'workshops/workshop_list.html'
38
    user_profile, created = Profile.objects.get_or_create(
39
        user__id=request.user.id)
40
    if not user_profile.is_profile_filled:
41
        return redirect('profiles:profile-edit', slug=request.user.username)
42
    context_dict = {}
43
    workshop_list = Workshop.objects.filter(
44
        is_active=True).order_by('-expected_date')
45
    workshop_list = workshop_list.filter(
46
        requester__location__state__id__in=[
47
            x.id for x in request.user.profile.interested_states.all()]
48
    )
49
50
    location_list = request.GET.getlist("location")
51
    if location_list:
52
        workshop_list = workshop_list.filter(
53
            requester__location__id__in=location_list
54
        )
55
56
    presenter_list = request.GET.getlist("presenter")
57
    if presenter_list:
58
        workshop_list = workshop_list.filter(
59
            presenter__id__in=presenter_list
60
        )
61
62
    workshop_level_list = request.GET.getlist("level")
63
    if workshop_level_list:
64
        workshop_list = workshop_list.filter(
65
            workshop_level__in=workshop_level_list
66
        )
67
68
    workshop_section_list = request.GET.getlist("section")
69
    if workshop_section_list:
70
        workshop_list = workshop_list.filter(
71
            workshop_section__id__in=workshop_section_list
72
        )
73
74
    status_list = request.GET.getlist("status")
75
    if status_list:
76
        workshop_list = workshop_list.filter(
77
            status__in=status_list
78
        )
79
80
    context_dict['workshop_list'] = workshop_list
81
    context_dict['user'] = request.user
82
    # need to improve the part
83
    context_dict['is_not_tutor'] = False
84
    context_dict['is_admin'] = False
85
    if request.user.is_superuser:
86
        context_dict['is_admin'] = True
87
    # as user can be tutor and regional lead hence we need to verify like
88
    # this
89
    if (Profile.is_regional_lead(request.user) or
90
            Profile.is_organiser(request.user) or
91
            Profile.is_admin(request.user)):
92
        context_dict['is_not_tutor'] = True
93
94
    context_dict['form'] = WorkshopListForm(user=request.user)
95
96
    return render(request, template_name, context_dict)
97
98
99
def workshop_details(request, pk):
100
    template_name = 'workshops/workshop_detail.html'
101
    workshop_obj = get_object_or_404(Workshop, id=pk)
102
    show_contact_flag = False
103
    display_edit_button = False
104
    user = request.user
105
    user_is_presenter = [u for u in workshop_obj.presenter.all() if user == u]
106
    user_is_requester = [
107
        u for u in workshop_obj.requester.user.all() if user == u]
108
    if (user_is_presenter or user_is_requester or
109
            user.is_superuser or (
110
                (not user.is_anonymous()) and Profile.is_coordinator(user))):
111
        show_contact_flag = True
112
    if (user_is_presenter):
113
        display_edit_button = True
114
115
    form = WorkshopVolunteer(initial={'number_of_volunteers': workshop_obj.number_of_volunteers or 0})
116
117
    context_dict = {
118
        'workshop': workshop_obj,
119
        'show_contact_flag': show_contact_flag,
120
        'display_edit_button': display_edit_button,
121
        'form': form
122
    }
123
    return render(request, template_name, context_dict)
124
125
126
@login_required
127
@verify_user_profile
128
def workshop_create(request):
129
    template_name = 'workshops/workshop_create.html'
130
    context_dict = {}
131
    if not Organisation.list_user_organisations(request.user).exists():
132
        msg = """
133
                To request workshop you need to create organisaiton.\n\n
134
                Please use organisation tab above to create your organisation
135
            """
136
        return render(request, 'error.html', {'message': msg})
137
    if request.method == 'GET':
138
        form = WorkshopForm(user=request.user)
139
        context_dict['form'] = form
140
        return render(request, template_name, context_dict)
141
    form = WorkshopForm(user=request.user, data=request.POST)
142
    if not form.is_valid():
143
        context_dict['form'] = form
144
        context_dict['errors'] = form.errors
145
        return render(request, template_name, context_dict)
146
    workshop = form.save()
147
    domain = Site.objects.get_current().domain
148
    if workshop and workshop.id:
149
        context = {
150
            'workshop': workshop,
151
            'date': workshop.expected_date,
152
            'workshop_url': domain + '/workshop/{}/'.format(workshop.id)
153
        }
154
        # Collage POC and admin email
155
        poc_admin_user = Profile.get_user_with_type(
156
            user_type=['Collage POC', 'admin']
157
        ).values_list('email', flat=True)
158
159
        org_user_emails = workshop.requester.user.filter(
160
            is_active=True).values_list('email', flat=True)
161
        # all presenter if any
162
        all_presenter_email = workshop.presenter.values_list(
163
            'email', flat=True)
164
        # List of tutor who have shown interest in that location
165
        region_interested_member = Profile.objects.filter(
166
            interested_locations=workshop.requester.location,
167
            usertype__slug='tutor'
168
        ).values_list('user__email', flat=True)
169
        all_email = []
170
        all_email.extend(org_user_emails)
171
        all_email.extend(all_presenter_email)
172
        all_email.extend(poc_admin_user)
173
        all_email.extend(region_interested_member)
174
        all_email = set(all_email)
175
        send_tweet(context)
176
177
        subject = '[PythonExpress] Workshop request status.'
178
        email_body = loader.get_template(
179
            'email_messages/workshop/create_workshop/message.html').render(context)
180
        text_body = loader.get_template(
181
            'email_messages/workshop/create_workshop/message.txt').render(context)
182
        send_email_to_list(
183
            subject,
184
            body=email_body,
185
            users_list=all_email,
186
            text_body=text_body)
187
        success_url = reverse_lazy('workshops:workshop_list')
188
    return HttpResponseRedirect(success_url)
189
190
191
class WorkshopUpdate(views.LoginRequiredMixin, WorkshopAccessMixin,
192
                     generic.UpdateView):
193
    model = Workshop
194
    form_class = WorkshopEditForm
195
    template_name = 'workshops/workshop_update.html'
196
197
    def get_success_url(self):
198
        # pk = self.kwargs.get(self.pk_url_kwarg, None)
199
        self.success_url = reverse("workshops:workshop_list")
200
        return super(WorkshopUpdate, self).get_success_url()
201
202
    def get_initial(self):
203
        return {
204
            "requester": self.object.requester.name,
205
        }
206
207
    def get_form_kwargs(self):
208
        kwargs = super(WorkshopUpdate, self).get_form_kwargs()
209
        kwargs['request'] = self.request
210
        return kwargs
211
212
213
class WorkshopToggleActive(views.LoginRequiredMixin, views.CsrfExemptMixin,
214
                           views.JSONResponseMixin, WorkshopAccessMixin,
215
                           generic.UpdateView):
216
    model = Workshop
217
    fields = ('is_active', 'id')
218
219
    def post(self, request, *args, **kwargs):
220
        self.object = self.get_object()
221
        response = self.object.toggle_active(request.user, **kwargs)
222
        return self.render_json_response(response)
223
224
225
class WorkshopAction(views.CsrfExemptMixin, views.LoginRequiredMixin,
226
                     views.JSONResponseMixin, WorkshopEmailMixin,
227
                     generic.UpdateView):
228
229
    model = Workshop
230
    email_dir = 'email_messages/workshop/assign_me/'
231
232
    def post(self, request, *args, **kwargs):
233
        self.object = self.get_object()
234
        response = self.object.manage_action(request.user, **kwargs)
235
236
        if response['status'] and response.get('notify') is not None:
237
            self.send_mail(request.user, response['assigned'])
238
            del response['notify']
239
        return self.render_json_response(response)
240
241
    def send_mail(self, user, assigned):
242
        """Send email to presenter and org users."""
243
244
        workshop = self.object
245
        context = {
246
            'presenter': True,
247
            'assigned': assigned,
248
            'date': workshop.expected_date,
249
            'presenter_name': user.username,
250
            'workshop_organization': workshop.requester,
251
            'workshop_url': self.request.build_absolute_uri(reverse(
252
                'workshops:workshop_detail', args=[workshop.pk]
253
            ))
254
        }
255
        # email to presenter and group
256
        self.send_mail_to_presenter(user, context)
257
        context['presenter'] = False
258
        self.send_mail_to_group(context, exclude_emails=[user.email])
259
260
261
# class WorkshopFeedbackView(views.LoginRequiredMixin,
262
#                            generic.FormView):
263
#     form_class = WorkshopFeedbackForm
264
#     template_name = "workshops/workshop_feedback.html"
265
#     success_url = reverse_lazy('workshops:workshop_list')
266
267
#     def form_valid(self, form):
268
#         workshop_id = self.kwargs.get('pk')
269
#         form.save(self.request.user, workshop_id)
270
#         return super(WorkshopFeedbackView, self).form_valid(form)
271
272
#     def get_context_data(self, *args, **kwargs):
273
#         context = super(WorkshopFeedbackView, self).get_context_data(
274
#             *args, **kwargs)
275
#         context['workshop'] = Workshop.objects.get(pk=self.kwargs.get('pk'))
276
#         return context
277
278
279
@login_required
280
def workshop_feedback_view(request, pk):
281
    context_dict = {}
282
    template_name = "workshops/workshop_feedback.html"
283
    context_dict['workshop'] = Workshop.objects.get(pk=pk)
284
    if request.method == 'POST':
285
        form = WorkshopFeedbackForm(
286
            data=request.POST, user=request.user, id=pk)
287
        if form.is_valid():
288
            WorkshopFeedBack.save_feedback(
289
                request.user, pk, **request.POST)
290
            success_url = reverse_lazy('workshops:workshop_list')
291
            return HttpResponseRedirect(success_url)
292
        context_dict['form'] = form
293
        context_dict['user'] = request.user
294
        return render(request, template_name, context_dict)
295
    else:
296
        context_dict['form'] = WorkshopFeedbackForm(
297
            user=request.user, id=pk)
298
    context_dict['user'] = request.user
299
    return render(request, template_name, context_dict)
300
301
302
def upcoming_workshops(request):
303
    template_name = 'upcoming.html'
304
    workshop_list = Workshop.objects.filter(is_active=True).filter(
305
        status__in=[WorkshopStatus.REQUESTED,
306
                    WorkshopStatus.ACCEPTED]).order_by('expected_date')
307
    context_dict = {}
308
    context_dict['workshop_list'] = workshop_list
309
310
    return render(request, template_name, context_dict)
311
312
313
@csrf_exempt
314
@login_required
315
def workshop_update_volunteer(request, pk):
316
    if request.GET:
317
        return JsonResponse({"items": range(1, 6)})
318
319
    if request.POST:
320
        volunteers = request.POST.get('number_of_volunteers')
321
        tutor_reimbursement_flag = request.POST.get('tutor_reimbursement_flag')
322
        comments = request.POST.get('comments')
323
        if volunteers.strip() not in ('', None):
324
            workshop_volunteer = Workshop.objects.filter(pk=pk)
325
            workshop_volunteer.update(number_of_volunteers=volunteers)
326
        if tutor_reimbursement_flag:
327
            workshop_volunteer.update(
328
                tutor_reimbursement_flag=tutor_reimbursement_flag)
329
        if comments:
330
            workshop_volunteer.update(comments=comments)
331
        return JsonResponse({
332
                "status": True,
333
                "msg": "Updated successfully"})
334
    return JsonResponse({"status": False, "msg": "Somthing went wrong"})
335
336
337
@csrf_exempt
338
@login_required
339
def workshop_accept_as_volunteer(request, pk):
340
    if request.method == 'POST':
341
        workshop = Workshop.objects.get(pk=pk)
342
        user = request.user
343
344
        if workshop.number_of_volunteers == 0:
345
            return JsonResponse({
346
                "status": False,
347
                "msg": "Volunteer not request for this workshop."})
348
        elif workshop.number_of_volunteers - workshop.volunteer.count() >= 1:
349
            # Check if already registered
350
            if user in workshop.volunteer.all():
351
                return JsonResponse({
352
                    "status": False,
353
                    "msg": "You are already registered as volunteer."})
354
            else:
355
                workshop.volunteer.add(user)
356
                return JsonResponse({
357
                    "status": True,
358
                    "msg": "Registered successfully."})
359
        else:
360
            return JsonResponse({
361
                "status": False,
362
                "msg": "Unable to register you, as requirement already fulfilled"})
363
    return JsonResponse({"status": False, "msg": "Something went wrong"})
364
365
366
@csrf_exempt
367
@login_required
368
def workshop_opt_out_as_volunteer(request, pk):
369
    if request.method == 'POST':
370
        workshop = Workshop.objects.get(pk=pk)
371
        user = request.user
372
373
        if user in workshop.volunteer.all():
374
            # remove volunteer
375
            workshop.volunteer.remove(user)
376
377
            workshop.save()
378
            return JsonResponse({
379
                "status": True,
380
                "msg": "Opt-out successfully."})
381
        else:
382
            return JsonResponse({
383
                "status": False,
384
                "msg": "You are not registered as volunteer."})
385
    return JsonResponse({"status": False, "msg": "Something went wrong"})
386