summaryrefslogtreecommitdiff
path: root/statistics_app/views.py
blob: 954af1745ac20d6e37575d8eea69b4ed9b95c847 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
from workshop_app.forms import (
    UserRegistrationForm, UserLoginForm,
    ProfileForm, CreateWorkshop,
    ProposeWorkshopDateForm
)
from workshop_app.models import (
    Profile, User,
    has_profile, Workshop,
    WorkshopType, RequestedWorkshop,
    BookedWorkshop, ProposeWorkshopDate,
    Testimonial
)
from teams.models import Team

from django.template.loader import get_template
from django.template import RequestContext
from datetime import datetime, date
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, redirect
from django.db import IntegrityError
from django.utils import timezone
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from os import listdir, path, sep
from zipfile import ZipFile
from django.contrib import messages
from operator import itemgetter
from pandas import DataFrame
import datetime as dt
import csv
try:
    from StringIO import StringIO as string_io
except ImportError:
    from io import BytesIO as string_io


# Create your views here.
def check_workshop_type(x):
    try:
        y = datetime.strftime(x.proposed_workshop_date, '%d-%m-%Y')
    except BaseException:
        y = datetime.strftime(x.requested_workshop_date, '%d-%m-%Y')
    return y


def is_instructor(user):
    '''Check if the user is having instructor rights'''
    return True if user.groups.filter(name='instructor').count() > 0 else False


def is_email_checked(user):
    if hasattr(user, 'profile'):
        return True if user.profile.is_email_verified else False
    else:
        return False


def pie_chart():
    '''This function gives Data for drawring Pie Chart'''

    # Count Total Number of workshops for each type
    workshop_titles = WorkshopType.objects.all()
    workshoptype_dict = {}
    for title in workshop_titles:
        workshoptype_dict[title] = 0

    for title in workshoptype_dict.keys():
        workshoptype_dict[title] += RequestedWorkshop.objects.filter(
            requested_workshop_title=title,
            status='ACCEPTED').count()
        workshoptype_dict[title] += ProposeWorkshopDate.objects.filter(
            proposed_workshop_title=title,
            status='ACCEPTED').count()

    # For Pie Chart
    workshoptype_num = [count for count in workshoptype_dict.values()]
    workshoptype_title = [str(title) for title in workshoptype_dict.keys()]

    workshoptype_count = [workshoptype_title, workshoptype_num]
    del workshoptype_title, workshoptype_num

    return workshoptype_count


def india_map():
   '''This function returns count of workshops based on states in India.'''

   states = [
        ['Code', 'State', 'Number'],
        ["IN-AP", "Andhra Pradesh", 0],
        ["IN-AR", "Arunachal Pradesh", 0],
        ["IN-AS", "Assam", 0],
        ["IN-BR", "Bihar", 0],
        ["IN-CT", "Chhattisgarh", 0],
        ["IN-GA", "Goa", 0],
        ["IN-GJ", "Gujarat", 0],
        ["IN-HR", "Haryana", 0],
        ["IN-HP", "Himachal Pradesh", 0],
        ["IN-JK", "Jammu and Kashmir", 0],
        ["IN-JH", "Jharkhand", 0],
        ["IN-KA", "Karnataka", 0],
        ["IN-KL", "Kerala", 0],
        ["IN-MP", "Madhya Pradesh", 0],
        ["IN-MH", "Maharashtra", 0],
        ["IN-MN", "Manipur", 0],
        ["IN-ML", "Meghalaya", 0],
        ["IN-MZ", "Mizoram", 0],
        ["IN-NL", "Nagaland", 0],
        ["IN-OR", "Odisha", 0],
        ["IN-PB", "Punjab", 0],
        ["IN-RJ", "Rajasthan", 0],
        ["IN-SK", "Sikkim", 0],
        ["IN-TN", "Tamil Nadu", 0],
        ["IN-TG", "Telangana", 0],
        ["IN-TR", "Tripura", 0],
        ["IN-UT", "Uttarakhand", 0],
        ["IN-UP", "Uttar Pradesh", 0],
        ["IN-WB", "West Bengal", 0],
        ["IN-AN", "Andaman and Nicobar Islands", 0],
        ["IN-CH", "Chandigarh", 0],
        ["IN-DN", "Dadra and Nagar Haveli", 0],
        ["IN-DD", "Daman and Diu", 0],
        ["IN-DL", "Delhi", 0],
        ["IN-LD", "Lakshadweep", 0],
        ["IN-PY", "Puducherry", 0]
    ]
   workshop_state = []
   requestedWorkshops = RequestedWorkshop.objects.filter(status='ACCEPTED')
   proposedWorkshops = ProposeWorkshopDate.objects.filter(status='ACCEPTED')
   for workshop in requestedWorkshops:
       for s in states:
           if s[0] == workshop.requested_workshop_coordinator.profile.state:
               s[2] += 1

   for workshop in proposedWorkshops:
       for s in states:
           if s[0] == workshop.proposed_workshop_coordinator.profile.state:
               s[2] += 1

   return states



def monthly_accepted_chart():
    '''This function returns workshops accepted for each month
    in the current year'''
    today = datetime.now()
    upto = today + dt.timedelta(days=15)

    workshop_count = [0] * 12
    for x in range(12):
        workshop_count[x] += RequestedWorkshop.objects.filter(
            requested_workshop_date__year=str(today.year),
            requested_workshop_date__month=str(x + 1),
            status='ACCEPTED').count()
        workshop_count[x] += ProposeWorkshopDate.objects.filter(
            proposed_workshop_date__year=str(today.year),
            proposed_workshop_date__month=str(x + 1),
            status='ACCEPTED').count()

    return workshop_count



def monthly_avg():
    '''This function returns monthly mean of workshops from the
    beginning to current year'''
    current_year = datetime.today().year
    start_year = 2017
    total_monthly_workshop = {}
    for i in range(start_year, current_year+1):
        total_monthly_workshop[i] = []

    years = total_monthly_workshop.keys()

    for i in years:
        for j in range(12):
            data = RequestedWorkshop.objects.filter(
                requested_workshop_date__year=str(i),
                requested_workshop_date__month=str(j+1),
                status='ACCEPTED').count()

            data += ProposeWorkshopDate.objects.filter(
                proposed_workshop_date__year=str(i),
                proposed_workshop_date__month=str(j+1),
                status='ACCEPTED').count()
            total_monthly_workshop[i].append(data)

    df = DataFrame.from_dict(total_monthly_workshop)
    monthly_workshop_mean = df.mean(axis=1)

    return list(monthly_workshop_mean)



@login_required
def workshop_stats(request):
    user = request.user
    today = datetime.now()
    upto = today + dt.timedelta(days=15)


    #For Monthly Chart
    workshop_count = monthly_accepted_chart()

    #For Monthly Workshop Mean
    workshop_mean = monthly_avg()

    # For Pie Chart
    workshoptype_count = pie_chart()

    # For India Map
    states = india_map()
    # For Data Downloading and Viewing
    if request.method == 'POST':
        try:
            from_dates = request.POST.get('from')
            to_dates = request.POST.get('to')

            # Fetches Accepted workshops which were proposed by Coordinators
            proposed_workshops = ProposeWorkshopDate.objects.filter(
                proposed_workshop_date__range=(from_dates, to_dates),
                status='ACCEPTED'
            )

            # Fetches Accepted workshops which were Accepted by
            # Instructors based on their Availability
            requested_workshops = RequestedWorkshop.objects.filter(
                requested_workshop_date__range=(from_dates, to_dates),
                status='ACCEPTED'
            )

            upcoming_workshops = []

            for workshop in proposed_workshops:
                upcoming_workshops.append(workshop)

            for workshop in requested_workshops:
                upcoming_workshops.append(workshop)

            upcoming_workshops = sorted(upcoming_workshops,
                                        key=lambda x: check_workshop_type(x))

            download = request.POST.get('Download')
            if download:
                response = HttpResponse(content_type='text/csv')

                response['Content-Disposition'] = 'attachment;\
                                filename="records_from_{0}_to_{1}.csv"'.format(
                    from_dates, to_dates
                )

                writer = csv.writer(response)
                header = [
                    'coordinator name',
                    'instructor name',
                    'workshop',
                    'date',
                    'status',
                    'institute name',
                    'state'
                ]

                writer.writerow(header)

                for workshop in upcoming_workshops:
                    try:
                        row = [
                       workshop.proposed_workshop_coordinator,
                       workshop.proposed_workshop_instructor,
                       workshop.proposed_workshop_title,
                       workshop.proposed_workshop_date,
                       workshop.status,
                       workshop.proposed_workshop_coordinator.profile.institute,
                       str(workshop.proposed_workshop_coordinator.profile.state)
                        ]

                    except BaseException:
                        row = [
                        workshop.requested_workshop_coordinator,
                        workshop.requested_workshop_instructor,
                        workshop.requested_workshop_title,
                        workshop.requested_workshop_date,
                        workshop.status,
                        workshop.requested_workshop_coordinator.profile.institute,
                        str(workshop.requested_workshop_coordinator.profile.state)
                        ]

                    writer.writerow(row)
                return response
            else:
                return render(request,
                              'statistics_app/workshop_stats.html',
                              {"upcoming_workshops": upcoming_workshops,
                               "show_workshop_stats": settings.SHOW_WORKSHOP_STATS,
                               "workshop_count": workshop_count,
                               "workshop_mean": workshop_mean,
                               "workshoptype_count": workshoptype_count,
                               "india_map": states})
        except BaseException:
            messages.info(request, 'Please enter Valid Dates')

    if is_instructor(user) and is_email_checked(user):
        try:
            # Fetches Accepted workshops which were proposed by Coordinators
            proposed_workshops = ProposeWorkshopDate.objects.filter(
                proposed_workshop_date__range=(today, upto),
                status='ACCEPTED'
            )

            # Fetches Accepted workshops which were Accepted by
            # Instructors based on their Availability
            requested_workshops = RequestedWorkshop.objects.filter(
                requested_workshop_date__range=(today, upto),
                status='ACCEPTED'
            )

            upcoming_workshops = []
            for workshop in proposed_workshops:
                upcoming_workshops.append(workshop)

            for workshop in requested_workshops:
                upcoming_workshops.append(workshop)

            upcoming_workshops = sorted(upcoming_workshops,
                                        key=lambda x: check_workshop_type(x))

        except BaseException:
            upcoming_workshops = []

        paginator = Paginator(upcoming_workshops, 12)

        page = request.GET.get('page')
        try:
            upcoming_workshops = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            upcoming_workshops = paginator.page(1)
        except EmptyPage:
            # If page is out of range(e.g 999999), deliver last page.
            upcoming_workshops = paginator.page(paginator.num_pages)

        return render(request, 'statistics_app/workshop_stats.html',
                      {
                          "upcoming_workshops": upcoming_workshops,
                          "show_workshop_stats": settings.SHOW_WORKSHOP_STATS,
                          "workshop_count": workshop_count,
                          "workshop_mean": workshop_mean,
                          "workshoptype_count": workshoptype_count,
                          "india_map": states
                      })
    else:
       return redirect('/statistics/public_stats/')


def workshop_public_stats(request):
    user = request.user
    today = datetime.now()
    upto = today + dt.timedelta(days=15)

    #For Pie Chart
    workshoptype_count = pie_chart()

    # For India Map
    states = india_map()

    # Select By WorkshopType
    workshoptype_list = list(WorkshopType.objects.all())
    workshoptype_list.append('all')

    # For Data Viewing
    if request.method == 'POST':
        workshop_list = []

        try:
            from_dates = request.POST.get('from')
            to_dates = request.POST.get('to')
            selected_state = request.POST.get('states')
            selected_workshoptype = request.POST.get('workshoptype_name')
            if selected_state == 'all':
                # If dates not passed
                if len(from_dates) == 0 and len(to_dates) == 0:
                    from_dates = '2017-01-01'
                    to_dates = upto
                # If SelectedWorkshopType is 'All'
                if len(selected_workshoptype) == 0:
                    # Fetches Accepted workshops which were proposed by
                    # Coordinators
                    proposed_workshops = ProposeWorkshopDate.objects.filter(
                        proposed_workshop_date__range=(from_dates, to_dates),
                        status='ACCEPTED'
                    )

                    # Fetches Accepted workshops which were Accepted by
                    # Instructors based on their Availability
                    requested_workshops = RequestedWorkshop.objects.filter(
                        requested_workshop_date__range=(from_dates, to_dates),
                        status='ACCEPTED'
                    )

                else:
                    # Fetches Accepted workshops which were proposed by
                    # Coordinators
                    proposed_workshops = ProposeWorkshopDate.objects.filter(
                        proposed_workshop_date__range=(from_dates, to_dates),
                        status='ACCEPTED', proposed_workshop_title_id=int(selected_workshoptype)
                    )

                    # Fetches Accepted workshops which were Accepted by
                    # Instructors based on their Availability
                    requested_workshops = RequestedWorkshop.objects.filter(
                        requested_workshop_date__range=(from_dates, to_dates),
                        status='ACCEPTED', requested_workshop_title_id=int(selected_workshoptype)
                    )

                for workshop in proposed_workshops:
                    workshop_list.append(workshop)

                for workshop in requested_workshops:
                    workshop_list.append(workshop)

            else:
                # If dates not passed
                if len(from_dates) == 0 and len(to_dates) == 0:
                    from_dates = '2017-01-01'
                    to_dates = upto

                # Get list of coordinators
                coordinators_state_wise = Profile.objects.filter(
                    state=selected_state)

                if len(selected_workshoptype) == 0:
                    # Traverse through list of coordinators and append
                    # workshop_list
                    for coordinator in coordinators_state_wise:
                        # Fetches Accepted workshops which were proposed by
                        # Coordinators
                        proposed_workshops = ProposeWorkshopDate.objects.filter(
                            proposed_workshop_date__range=(
                                from_dates,
                                to_dates),
                            status='ACCEPTED',
                            proposed_workshop_coordinator=coordinator.user_id)

                        # Fetches Accepted workshops which were Accepted by
                        # Instructors based on their Availability
                        requested_workshops = RequestedWorkshop.objects.filter(
                            requested_workshop_date__range=(
                                from_dates,
                                to_dates),
                            status='ACCEPTED',
                            requested_workshop_coordinator=coordinator.user_id)

                        for workshop in proposed_workshops:
                            workshop_list.append(workshop)

                        for workshop in requested_workshops:
                            workshop_list.append(workshop)

                else:
                   # Traverse through list of coordinators and append
                    # workshop_list
                    for coordinator in coordinators_state_wise:
                        # Fetches Accepted workshops which were proposed by
                        # Coordinators
                        proposed_workshops = ProposeWorkshopDate.objects.filter(
                            proposed_workshop_date__range=(
                                from_dates,
                                to_dates),
                            status='ACCEPTED', proposed_workshop_title_id=int(selected_workshoptype),
                            proposed_workshop_coordinator=coordinator.user_id)

                        # Fetches Accepted workshops which were Accepted by
                        # Instructors based on their Availability
                        requested_workshops = RequestedWorkshop.objects.filter(
                            requested_workshop_date__range=(
                                from_dates,
                                to_dates),
                            status='ACCEPTED', requested_workshop_title_id=int(selected_workshoptype),
                            requested_workshop_coordinator=coordinator.user_id)

                        for workshop in proposed_workshops:
                            workshop_list.append(workshop)

                        for workshop in requested_workshops:
                            workshop_list.append(workshop)

            return render(request,
                          'statistics_app/workshop_public_stats.html',
                          {
                              "workshoptype_list": workshoptype_list[::-1],
                              "workshop_list": workshop_list,
                              "workshoptype_count": workshoptype_count,
                              "india_map": states})

        except BaseException:
            messages.info(request, 'Please enter Valid Dates')

    else:
        '''Default Data'''
        workshop_list = []
        
        proposed_workshops = ProposeWorkshopDate.objects.filter(
                        status='ACCEPTED')

        # Fetches Accepted workshops which were Accepted by
        # Instructors based on their Availability
        requested_workshops = RequestedWorkshop.objects.filter(    
                    status='ACCEPTED')

        for workshop in proposed_workshops:
            workshop_list.append(workshop)

        for workshop in requested_workshops:
            workshop_list.append(workshop)


    return render(request,
                  'statistics_app/workshop_public_stats.html',
                  {
                      "workshoptype_list": workshoptype_list[::-1],
                      "workshoptype_count": workshoptype_count,
                      "workshop_list": workshop_list,
                      "india_map": states})


@login_required
def profile_stats(request):
    user = request.user
    if is_instructor(user) and is_email_checked(user):
        profiles = Profile.objects.all()

        rworkshops = RequestedWorkshop.objects.filter(status='ACCEPTED')
        pworkshops = ProposeWorkshopDate.objects.filter(status='ACCEPTED')

        iprofile = Profile.objects.filter(position='instructor')
        cprofile = Profile.objects.filter(position='coordinator')

        instructor_profile = []
        coordinator_profile = []

        for p in iprofile:
            instructor_profile.append({"profile": p,
                                        "count": 0
                                        })
            

        for p in cprofile:
            coordinator_profile.append({"profile": p,
                                        "count": 0
                                        })

        for p in instructor_profile:
            p['count'] += RequestedWorkshop.objects.filter(
                        requested_workshop_instructor_id=p['profile'].user.id,
                        status='ACCEPTED').count()

            p['count'] += ProposeWorkshopDate.objects.filter(
                        proposed_workshop_instructor_id=p['profile'].user.id,
                        status='ACCEPTED').count()

        for p in coordinator_profile:
            p['count'] += RequestedWorkshop.objects.filter(
                        requested_workshop_coordinator_id=p['profile'].user.id,
                        status='ACCEPTED').count()

            p['count'] += ProposeWorkshopDate.objects.filter(
                        proposed_workshop_coordinator_id=p['profile'].user.id,
                        status='ACCEPTED').count()

        #Sorting
        coordinator_profile = sorted(coordinator_profile, 
                            key=lambda k:k['count'], reverse=True)
        instructor_profile = sorted(instructor_profile, 
                            key=lambda k:k['count'], reverse=True)

        return render(request, "statistics_app/profile_stats.html",
            {
                "instructor_data": instructor_profile,
                "coordinator_data": coordinator_profile,
            })
    else:
        logout(request)
        return render(request, "workshop_app/logout.html")

@login_required
def team_stats(request, team_id):
    user = request.user
    team = Team.objects.get(team_id)
    if user not in team.members.all():
        if user.groups.filter(name='instructor').count() > 0:
            return redirect('/manage/')
        return redirect('/book/')

    member_workshop_data = {}
    for member in team.members.all():
        workshop_count = ProposeWorkshopDate.objects.filter(proposed_workshop_instructor=member.id).count()
        if member_workshop_data.get('data'):
            member_workshop_data['data'].append(workshop_count)
        else:
            member_workshop_data['data'] = [workshop_count]
        if member_workshop_data.get('labels'):
            member_workshop_data['labels'].append(member.user.username)
        else:
            member_workshop_data['labels'] = [member.user.username]
    return render(request, 'statistics_app/team_stats.html', {'workshop_data': member_workshop_data})