summaryrefslogtreecommitdiff
path: root/choice_seeker/allotter/views.py
blob: fb819fc87df11e82e7b045e82ee3aa82e99bd1cb (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
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required 
from django.shortcuts import render, redirect, get_object_or_404

from django.http import Http404
from django.http import HttpResponse
from django.http import HttpResponseRedirect 

from django.core.urlresolvers import reverse

from django.contrib.auth.models import User
from allotter.models import Profile, Option, Exam
from allotter.forms import UserLoginForm, UserDetailsForm

from itertools import chain

#Reportlab libraries
from reportlab.platypus import Table, TableStyle, SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.lib.units import inch
from reportlab.lib.enums import TA_JUSTIFY

import time

def user_login(request):
    """
        Verify the user credentials and log the user in.
    """

    user = request.user
    if user.is_authenticated():
        status = user.get_profile().application.submitted #Getting the submission status
        if status: #If already submitted, takes to Completion Page
            return HttpResponseRedirect(reverse('allotter.views.complete_allotment', args=(user.username,)))
        else: #Otherwise to Option Choosing Page   
            return HttpResponseRedirect(reverse('allotter.views.apply', args=(user.username,)))

    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data
            login(request, user)
            status = user.get_profile().application.submitted #Getting the submission status
            if status:
                return HttpResponseRedirect(reverse('allotter.views.complete_allotment', args=(user.username,)))
            else:  
                return HttpResponseRedirect(reverse('allotter.views.submit_details', args=(user.username,)))  
        else:
            context = {"form": form}
            return render(request, 'allotter/login.html', context)
    else:
        form = UserLoginForm()
        context = {"form": form}
        return render(request, 'allotter/login.html', context)
                                     

@login_required
def submit_details(request, reg_no):
    """
        Get the secondary email address, phone number and save it to the Profile.
    """
    user = request.user
    
    if request.method == "POST":
        form = UserDetailsForm(user, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            form.save()
            return redirect("/allotter/apply/")           
        else:
            return render(request, 'allotter/details.html', {'form':form})  
                
    else:
        form = UserDetailsForm(request.user)
        context = {"form": form}
        return render(request, 'allotter/details.html', context)              
       
def get_details(user, error_message = ""):
    """
       Retrieves the information about Test paper(s) and options available
       and returns them in a dictionary(context) for passing to the Template.
    """
    user_profile = user.get_profile()
    user_application = user_profile.application
    np = user_application.np #Number of Papers
    first_paper = user_application.first_paper #First Paper Name
    options_available_first = Option.objects.filter(exam__exam_name=first_paper).distinct() #Options for First paper
    oafl = len(options_available_first)  
    if np == 2: #If written two exams
        second_paper = user_application.second_paper
        options_available_second = Option.objects.filter(exam__exam_name=second_paper).distinct()
        oasl = len(options_available_second)
        context = {'user': user, 'first_paper': first_paper,
            'options_available_first' : options_available_first, 
            'second_paper': second_paper, 
            'options_available_second' : options_available_second,
            'np' : np, 'options_range': range(1, oafl + oasl + 1, 1), 
            'error_message': error_message}    
    else: #If written only one exam
        context = {'user': user, 'first_paper': first_paper,
            'options_available_first' : options_available_first,
            'options_range': range(1, oafl + 1, 1), 
            'np' : np, 'error_message' : error_message}     
    return context              
                                     
@login_required
def apply(request, reg_no):
    """
        Displays the application page for an authenticated user.
    """
    user = request.user
    if not(user.is_authenticated()):
        return redirect('/allotter/login/')
    
    context = get_details(user) 
              
    return render(request, 'allotter/apply.html', context)                         


def user_logout(request):
    ##Logouts the user.
    logout(request)
    return redirect ('/allotter/login/')

#TODO: Extensive Testing

@login_required                            
def submit_options(request, reg_no):
    """
        Gets the Options and their preference number through the POST object and
        stores them as list(sorted according to preferences). Options with None are 
        ignored. 
    """
    user = get_object_or_404(User, username=reg_no)
    user_profile = user.get_profile()
    user_application = user_profile.application
    np = user_application.np
    first_paper = user_application.first_paper #First Paper Name
    options_available_first = Option.objects.filter(exam__exam_name=first_paper).distinct() #Options for First paper
    
    if np == 2: #If qualified for second paper
        second_paper = user_application.second_paper #Second Paper Name
        options_available_second = Option.objects.filter(exam__exam_name=second_paper).distinct() #Options for second paper
        options_available_list = chain(options_available_first, options_available_second) #chaining the two lists
    else:
        options_available_list = options_available_first
        
    options_chosen_list = [] #Initializing empty list for storing options
    for option in options_available_list:   
        option_pref = request.POST[unicode(option.opt_code)]           
        options_chosen_list.append([option_pref, str(option.opt_code)]) #[preference, option code]
    
    options_chosen_list.sort() #Sorting by preference
    options_code_list = []
    for opt in options_chosen_list:
        if int(opt[0]): #ignoring the options for which None was marked
            options_code_list.append(opt[1])
         
    user_application.options_selected = options_code_list #Saving the data in model   
    user_application.submitted = True #Submission Status
    user_application.save()
    return HttpResponseRedirect(reverse('allotter.views.complete_allotment', args=(reg_no,)))

def complete_allotment(request, reg_no):
    """
        Passes the chosen options queryset to the Completion Page Template
    """
    user = get_object_or_404(User, username=reg_no)
    sec_email = user.get_profile().secondary_email
    options_chosen = get_chosen_options(user)
    context = {'username': reg_no, 'email': sec_email,  
                'options_chosen': options_chosen}
              
    return render(request, 'allotter/complete.html', context)
    
    
def get_chosen_options(user):
    """
        Reads the options submitted by the user in the Application page
    """
    user_profile = user.get_profile()
    user_application = user_profile.application
    np = user_application.np
    ocl = eval(user_application.options_selected)
    chosen_options = []
    for oc in ocl:
        chosen_options.append(Option.objects.get(opt_code=int(oc))) 
    return chosen_options
        
        
@login_required        
def generate_pdf(request, reg_no):
    """
        The Ugly code for generating the pdf using ReportLab.
    """
    
    user = get_object_or_404(User, username=reg_no)
    user_profile = user.get_profile()
    user_application = user_profile.application
    np = user_application.np
 
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=JAM2012_Allottment.pdf'
    
    elements = []
    doc = SimpleDocTemplate(response)
    
    formatted_time = time.ctime()
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    
    ptext = '<font size=15>JAM 2012 Allotment.</font>'         
    elements.append(Paragraph(ptext, styles["Justify"]))
    elements.append(Spacer(4, 20))
    
    ptext = '<font size=12>Registration Number: %s</font>' % reg_no 
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))
    
    ptext = '<font size=12>Number of Papers Eligible: %s</font>' % np
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))
    
    ptext = '<font size=12>No options were chosen.</font>' 
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))
    
    data = []   
    options = get_chosen_options(user) ##Put a check to show when the options chosen is empty
    
    if not(options):
        doc.build(elements) 
        return response 
        
    ptext = '<font size=12>Following are the options in order of preference</font>' 
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))    
        
    counter = 1
    for opt in options:
        data.append([counter, opt.opt_code, opt.opt_location, opt.opt_name])
        counter = counter + 1
            
    t = Table(data)
    t.setStyle(TableStyle([('GRID',(0,0),(3,len(options)),1,colors.black),
                                   ('TEXTCOLOR',(0,0),(0,-1),colors.green)]))
                                                                     
    elements.append(t)  
    
    ptext = '<font size=12>%s</font>' % formatted_time
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))
 
    doc.build(elements)
       
    return response