Star rating completed on client side.
"""This module contains the views for the project's proposal
funded by NME through ICT.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
import json
import os
import time
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from projrev.models import Project
from projrev.models import Proposal
from projrev.views.helpers import access
from projrev.views.helpers import forms as projrev_forms
@access.register('proposer')
@access.checkAccess
def getMicr(request):
"""View to get MICR Code from the user.
"""
if request.method == 'POST':
post_params = request.POST
submit = post_params.get('submit')
if submit == 'New Proposal':
return HttpResponseRedirect(
reverse('app.projrev.views.proposal.submit'))
else:
micr_code = request.POST.get('micr_code')
if micr_code:
try:
Project.objects.get(micr_code=micr_code)
except Project.DoesNotExist:
if (submit == 'Edit Proposal for MICR Code' or
submit == 'Withdraw Proposal for MICR Code'):
template = 'projrev/proposal/get_micr.html'
context = {
'error': True,
}
return render_to_response(template,
RequestContext(request, context))
else:
if submit == 'Edit Proposal for MICR Code':
return HttpResponseRedirect(
reverse('app.projrev.views.proposal.submit',
args=(micr_code, )))
elif submit == 'Withdraw Proposal for MICR Code':
return HttpResponseRedirect(
reverse('app.projrev.views.proposal.withdraw',
args=(micr_code, )))
else:
template = 'projrev/proposal/get_micr.html'
context = {}
return render_to_response(template, RequestContext(request, context))
@access.register('proposer')
@access.checkAccess
def submit(request, micr_code=None):
"""View for proposal submission.
"""
if request.method == 'POST':
return submitPost(request, micr_code)
else:
return submitGet(request, micr_code)
def submitPost(request, micr_code=None):
"""Handles POST request for the submitted proposal form.
"""
prop_form = projrev_forms.ProposalForm(request.POST, request.FILES)
project = None
proposal = None
if prop_form.is_valid():
cleaned_data = prop_form.cleaned_data
if micr_code:
project = Project.objects.get(micr_code=micr_code)
project.line_item = Project.getLineItem(cleaned_data['line_item'])
project.institution = cleaned_data['institution']
project.state = Project.getState(cleaned_data['state'])
project.district = Project.getDistrict(cleaned_data['district'])
else:
# Generate MICR code
cleaned_data['micr_code'] = '%s%s%d' % (
cleaned_data['district'], cleaned_data['line_item'],
int(time.time() * 1000) % 1000000000)
cleaned_data['line_item'] = Project.getLineItem(cleaned_data['line_item'])
cleaned_data['state'] = Project.getState(cleaned_data['state'])
cleaned_data['district'] = Project.getDistrict(cleaned_data['district'])
prop_form.cleaned_data = cleaned_data
# If the form is valid create a new project or update the project
# if it already exists from the form.
project = prop_form.save()
project.micr_code = cleaned_data['micr_code']
subject = "[Sakshath] MICR Code of the new proposal submitted"
message = """Hi,
We have received a new proposal for National Mission on education from your,
email address "%s", to the http://sakshath.ac.in portal. The MICR Code of the
submitted proposal is:
MICR Code: %s
Please remember this code for all future references.
--
Regards,
Saksath admin""" % (request.user.username, project.micr_code)
request.user.email_user(subject=subject, message=message)
project.status = 'new'
micr_code = project.micr_code
project.save()
if prop_form.cleaned_data['document']:
# Create a proposal for the project.
proposal = project.proposal_set.create(
document=prop_form.cleaned_data['document'],
submitted_by=request.user, rev_num = 0)
proposal.save()
return HttpResponseRedirect(
reverse('app.projrev.views.proposal.submit', args=(micr_code,)))
return submitGet(request, micr_code, prop_form)
def submitGet(request, micr_code=None, prop_form=None):
"""Handles GET request for the submission of proposal form.
"""
context = {}
project = None
if micr_code:
project = Project.objects.get(micr_code=micr_code)
if project:
initial_vals = {
'line_item': Project.getLineItemCode(project.line_item),
'state': Project.getStateCode(project.state),
'district': Project.getDistrictCode(project.district),
}
if not prop_form:
prop_form = projrev_forms.ProposalForm(
initial=initial_vals, instance=project)
proposal = project.proposal_set.all().order_by('-submitted_on')[0]
if proposal:
proposal_path = str(proposal.document)
proposal_name = proposal_path.split('/')[-1]
context['proposal_path'] = proposal_path
context['proposal_name'] = proposal_name
context['last_submitted'] = proposal.submitted_on
if 'HTTP_REFERER' in request.META:
referer = request.META['HTTP_REFERER'].split('/')
if referer[-1]:
ref = referer[-1]
else:
ref = referer[-2]
if ref == 'create':
context['created_now'] = True
context['micr_code'] = project.micr_code
reviews = project.review_set.all().order_by('-reviewed_on')
if reviews:
context['last_reviewed'] = reviews[0].reviewed_on
context['nr_reviews'] = len(reviews)
else:
if not prop_form:
prop_form = projrev_forms.ProposalForm()
context['form'] = prop_form
template = 'projrev/proposal/submit.html'
return render_to_response(template, RequestContext(request, context))
@access.register('proposer')
@access.checkAccess
def withdraw(request, micr_code=None):
"""View Method for withdrawal of proposal.
"""
if micr_code:
project = Project.objects.get(micr_code=micr_code)
if project:
project.status = 'invalid'
project.save()
context = {
'withdrawn': True,
}
template = 'projrev/proposal/withdraw.html'
return render_to_response(template, RequestContext(request, context))
@access.register('reviewer')
@access.checkAccess
def review(request, micr_code=None):
"""View for reviewing the proposal.
"""
if request.method == 'POST':
return reviewPost(request, micr_code)
else:
return reviewGet(request, micr_code)
def reviewPost(request, micr_code=None):
"""
"""
rev_form = projrev_forms.ReviewForm(request.POST)
if rev_form.is_valid():
cleaned_data = rev_form.cleaned_data
cleaned_data['project'] = Project.objects.get(micr_code=micr_code)
cleaned_data['reviewer'] = request.user
# If the form is valid create a new project or update the project
# if it already exists from the form.
review = rev_form.save()
return reviewGet(request, micr_code, rev_form)
def reviewGet(request, micr_code=None, rev_form=None):
"""
"""
context = {}
if not micr_code:
template = 'projrev/proposal/list.html'
context['projects'] = Project.objects.all().exclude(
status__exact='invalid').order_by('-last_updated_on')
context['row_url'] = '/proposal/review/'
return render_to_response(template, RequestContext(request, context))
if not rev_form:
rev_form = projrev_forms.ReviewForm()
project = Project.objects.get(micr_code=micr_code)
context['form'] = rev_form
context['project'] = project
proposal = project.proposal_set.all().order_by('-submitted_on')[0]
if proposal:
proposal_path = str(proposal.document)
proposal_name = proposal_path.split('/')[-1]
context['proposal_path'] = proposal_path
context['proposal_name'] = proposal_name
context['last_submitted'] = proposal.submitted_on
reviews = project.review_set.all().order_by('reviewed_on')
if reviews:
context['reviews'] = reviews
context['last_reviewed'] = reviews[len(reviews)-1].reviewed_on
context['nr_reviews'] = len(reviews)
template = 'projrev/proposal/review.html'
return render_to_response(template, RequestContext(request, context))
@access.register('reviewer')
@access.checkAccess
def rank(request, micr_code=None):
"""
"""
context = {}
if not micr_code:
template = 'projrev/proposal/list.html'
context['projects'] = Project.objects.all().exclude(
status__exact='invalid').order_by('-last_updated_on')
context['row_url'] = '/proposal/rank/'
return render_to_response(template, RequestContext(request, context))
project = Project.objects.get(micr_code=micr_code)
proposal = project.proposal_set.all().order_by('-submitted_on')[0]
if proposal:
proposal_path = str(proposal.document)
proposal_name = proposal_path.split('/')[-1]
context['proposal_path'] = proposal_path
context['proposal_name'] = proposal_name
context['last_submitted'] = proposal.submitted_on
# Get all the reviews and put them to context.
reviews = project.review_set.all().order_by('reviewed_on')
nr_reviews = len(reviews)
if reviews:
context['reviews'] = reviews
context['last_reviewed'] = reviews[len(reviews)-1].reviewed_on
context['nr_reviews'] = nr_reviews
# Calculate the review scores
review_score = [0] * 9
for review in reviews:
review_score[0] += review.attribute1
review_score[1] += review.attribute2
review_score[2] += review.attribute3
review_score[3] += review.attribute4
review_score[4] += review.attribute5
review_score[5] += review.attribute6
review_score[6] += review.attribute7
review_score[7] += review.attribute8
review_score[8] += review.attribute9
total_score = sum(review_score)
# Get the Average for each attribute
review_avg = [0] * 9
for i, rs in enumerate(review_score):
try:
review_avg[i] = "%.2f" % (float(rs) / nr_reviews)
except ZeroDivisionError:
review_avg[i] = 0
try:
total_avg = "%.2f" % (float(total_score) / nr_reviews)
except ZeroDivisionError:
total_avg = 0
context['project'] = project
context['review_score'] = review_score
context['total_score'] = total_score
context['review_avg'] = review_avg
context['total_avg'] = total_avg
template = 'projrev/proposal/rank.html'
return render_to_response(template, RequestContext(request, context))
def getDistrictsForState(request):
"""View function that sends the districts for the given state code via AJAXy.
"""
get_params = request.GET
if get_params:
st_code = get_params['_value']
dt_dict = Project.DISTRICT_CHOICES
# Get the Districts corresponding to the given State code.
dt_names = {}
count = 1
for dt_code in dt_dict:
if dt_code[:2] == st_code:
dt_names[dt_code] = dt_dict[dt_code]
count += 1
# Sort the List based on District Name.
dt_send = [{'': "---------" }]
dt_names_sorted = sorted(dt_names.items(), key=lambda (k,v): (v,k))
for dt_code, dt_name in dt_names_sorted:
dt_send.append({dt_code: dt_name})
return HttpResponse(json.dumps(dt_send))
return HttpResponse(None)