app/projrev/views/proposal.py
author Madhusudan.C.S <madhusudancs@gmail.com>
Thu, 13 Aug 2009 04:01:15 +0530
changeset 47 09c3b7aaa535
parent 46 e27c75dedbfb
permissions -rw-r--r--
Full Comments window decoration.

"""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.contrib.auth.models import User
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.models import Review
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
      if cleaned_data['district']:
        cleaned_data['micr_code'] = '%s%s%d' % (
            cleaned_data['district'], cleaned_data['line_item'], 
            int(time.time() * 1000) % 1000000000)
      else:
        cleaned_data['micr_code'] = '%s%s%s%d' % (
            cleaned_data['state'], 'NN', 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']

      send_mails(request, project)

    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)

    proposals = project.proposal_set.all()
    if proposals:
      proposal = proposals.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, review_id=None):
  """View for reviewing the proposal.
  """

  if request.method == 'POST':
    return reviewPost(request, micr_code, review_id)
  else:
    return reviewGet(request, micr_code, review_id)

def reviewPost(request, micr_code=None, review_id=None):
  """
  """
  is_new = request.GET.get('new')
  if review_id and is_new != '0':
    redirect = False
    review_instance = Review.objects.get(id=review_id)
    rev_form = projrev_forms.ReviewForm(request.POST, instance=review_instance)
  else:
    redirect = True
    rev_form = projrev_forms.ReviewForm(request.POST)

  if rev_form.is_valid():
    cleaned_data = rev_form.cleaned_data

    project = Project.objects.get(micr_code=micr_code)
    proposal = project.proposal_set.all().order_by('-submitted_on')[0]

    cleaned_data['project'] = project
    cleaned_data['proposal'] = proposal
    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()

    if redirect:
      return HttpResponseRedirect(reverse('app.projrev.views.proposal.review', args=(micr_code, review.id)))

  return reviewGet(request, micr_code, review_id, rev_form)

def reviewGet(request, micr_code=None, review_id=None, rev_form=None):
  """
  """

  context = {}

  if not micr_code:
    template = 'projrev/proposal/review_list.html'
    context['projects'] = []
    projects = Project.objects.all().exclude(
        status__exact='invalid').order_by('-last_updated_on')

    for project in projects:
      user_reviews = project.review_set.all().filter(
          reviewer__id__exact=request.user.id).order_by('-reviewed_on')

      proposals = project.proposal_set.all().order_by('-submitted_on')

      if user_reviews and proposals:
        info = {
            'project': project,
            }
        proposal = proposals[0]
        new_user_reviews = user_reviews.filter(proposal__id__exact=proposal.id)
        if new_user_reviews:
          info['user_review'] = new_user_reviews[0]
        else:
          info['not_this_proposal'] = True
          info['user_review'] = user_reviews[0]

        context['projects'].append(info)
      elif proposals:
        info = {
            'project': project,
            }
        proposal = proposals[0]
        context['projects'].append(info)

    context['row_url'] = '/proposal/review/'

    return render_to_response(template, RequestContext(request, context))

  project = Project.objects.get(micr_code=micr_code)

  proposals = project.proposal_set.all().order_by('-submitted_on')

  if proposals:
    proposal = proposals[0]

    user_review = Review.objects.all().filter(
        id__exact=review_id).order_by('-reviewed_on')

    if user_review:
      user_review = user_review[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 not rev_form:
    if user_review:
      rev_form = projrev_forms.ReviewForm(instance=user_review)
      context['prev_data'] = rev_form.initial
    else:
      rev_form = projrev_forms.ReviewForm()
  else:
    context['prev_data'] = rev_form.data

  context['form'] = rev_form
  context['project'] = project

  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)

  proposals = project.proposal_set.all().order_by('-submitted_on')
  if proposals:
    proposal = proposals[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)

def getNewDistrictsForState(request):
  """Get initial district for state.
  """

  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)

@access.register('reviewer')
@access.checkAccess
def listMyReviews(request):
  """View function to list all reviews given by a user.
  """
  context = {}

  # Get all the reviews and put them to context.
  reviews = Review.objects.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
  
  template = 'projrev/proposal/myreviews.html'

  return render_to_response(template, RequestContext(request, context))

def send_mails(request, project):
  """Send mails to the user and all the reviewers after the project is created.
  """
  pass

  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)

  subject = '[Sakshath] A new proposal has been submitted for review'

  message_template = """Dear %(user)s,

  A new project proposal has been uploaded on the site for reviewing. The details are as follows:

*Title:* %(title)s
*Institution:* %(institution)s
*Address:* %(address)s
*City:* %(city)s
*State:* %(state)s
*Phone Number:* %(ph_no)s
*Email ID:* %(email)s

To review the proposal please logon to: <a href="">some website</a>
"""

  reviewers = User.objects.all().filter(is_staff__exact='1')

  for reviewer in reviewers:
    message = message_template % {
        'user': reviewer.username,
        'title': project.title,
        'institution': project.institution,
        'address': project.address,
        'city': project.city,
        'state': project.state,
        'ph_no': project.phone_num,
        'email': request.user.email,
        }

    reviewer.email_user(subject=subject, message=message)