get_tutor_college_poc_csv()   F
last analyzed

Complexity

Conditions 11

Size

Total Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 45
rs 3.1764
cc 11

How to fix   Complexity   

Complexity

Complex classes like get_tutor_college_poc_csv() 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
import datetime
2
import csv
3
from django.contrib.auth.decorators import login_required
4
from django.shortcuts import render
5
from django.http import HttpResponse
6
from django.contrib.auth.models import User
7
from wye.base.constants import WorkshopStatus
8
from wye.workshops.models import Workshop
9
from wye.profiles.models import Profile
10
11
12
@login_required
13
def index(request):
14
    context_dict = {}
15
    if not request.user.is_staff:
16
        template_name = '403.html'
17
        return render(request, template_name, context_dict)
18
19
    workshops = Workshop.objects.filter(is_active=True)
20
    context_dict['workshops'] = {
21
        'completed': workshops.filter(status=WorkshopStatus.COMPLETED).count(),
22
        'drafted': workshops.filter(status=WorkshopStatus.DRAFT).count(),
23
        'hold': workshops.filter(status=WorkshopStatus.HOLD).count(),
24
        'feedback_pending': workshops.filter(
25
            status=WorkshopStatus.FEEDBACK_PENDING).count(),
26
    }
27
    workshop_finished = workshops.filter(
28
        status__in=[WorkshopStatus.COMPLETED,
29
                    WorkshopStatus.FEEDBACK_PENDING])
30
    tutors_dict = {}
31
    tutors = [
32
        user for w in workshop_finished for user in w.presenter.all()]
33
    for tutor in tutors:
34
        tutors_dict[tutor.id] = [
35
            tutor.username,
36
            tutor.first_name,
37
            tutor.last_name,
38
            tutor.profile.get_workshop_completed_count]
39
    context_dict['tutors'] = tutors_dict
40
    org_dict = {}
41
    orgs = [
42
        w.requester for w in workshop_finished]
43
    for org in orgs:
44
        if org.id in org_dict:
45
            count = org_dict[org.id][1] + 1
46
        else:
47
            count = 1
48
        org_dict[org.id] = [org.name, count, org.location.name]
49
50
    context_dict['orgs'] = org_dict
51
    template_name = 'reports/index.html'
52
    years = [('all', 'All')]
53
    for y in range(2016, int(datetime.datetime.today().strftime('%Y')) + 1):
54
        years.append((y, y))
55
    context_dict['years'] = years
56
    return render(request, template_name, context_dict)
57
58
59
@login_required
60
def get_tutor_college_poc_csv(request):
61
    # if not request.user.is_staff:
62
    #     template_name = '403.html'
63
    #     return render(request, template_name, {})
64
    usertype = request.POST['usertype']
65
    year = request.POST['years']
66
    workshops = Workshop.objects.filter(is_active=True)
67
    if year != 'all':
68
        workshops = workshops.filter(expected_date__year=year)
69
70
    response = HttpResponse(content_type='text/csv')
71
    response['Content-Disposition'] = 'attachment; filename="workshops.csv"'
72
    writer = csv.writer(response)
73
    csv_titles = ['Worshop Id', 'Workshop Date', 'Location', 'College']
74
    if usertype == 'tutor':
75
        csv_titles.extend(['Presenter Name', 'Presenter Email'])
76
    elif usertype == 'poc':
77
        csv_titles.extend(['College POC Name', 'College POC Email'])
78
    else:
79
        csv_titles.extend(['Presenter Name', 'Presenter Email'])
80
        csv_titles.extend(['College POC Name', 'College POC Email'])
81
    writer.writerow(csv_titles)
82
83
    for obj in workshops:
84
        row = [
85
            obj.id, obj.expected_date,
86
            obj.location.name, obj.requester.name]
87
        if usertype == 'tutor':
88
            for u in obj.presenter.all():
89
                row.append("{} {}".format(u.first_name, u.last_name))
90
                row.append("{}".format(u.email))
91
        elif usertype == 'poc':
92
            for u in obj.requester.user.all():
93
                row.append("{} {}".format(u.first_name, u.last_name))
94
                row.append("{}".format(u.email))
95
        else:
96
            for u in obj.presenter.all():
97
                row.append("{} {}".format(u.first_name, u.last_name))
98
                row.append("{}".format(u.email))
99
            for u in obj.requester.user.all():
100
                row.append("{} {}".format(u.first_name, u.last_name))
101
                row.append("{}".format(u.email))
102
        writer.writerow(row)
103
    return response
104
105
106
@login_required
107
def get_all_user_info(request):
108
    users = User.objects.all()
109
    response = HttpResponse(content_type='text/csv')
110
    response['Content-Disposition'] = 'attachment; filename="all_users.csv"'
111
    writer = csv.writer(response)
112
    csv_titles = [
113
        'User Id', 'First Name', 'Last Name', 'Email', 'Is Active',
114
        'Is Presenter', 'Is POC', 'Is Regional Lead', 'Is Organiser']
115
    writer.writerow(csv_titles)
116
    for obj in users:
117
        try:
118
            row = [
119
                obj.id,
120
                obj.first_name,
121
                obj.last_name,
122
                obj.email,
123
                obj.is_active,
124
                Profile.is_presenter(obj),
125
                Profile.is_coordinator(obj),
126
                Profile.is_regional_lead(obj),
127
                Profile.is_organiser(obj)]
128
129
            writer.writerow(row)
130
        except Exception:
131
            pass
132
    return response
133