app/projrev/views/proposal.py
author Madhusudan.C.S <madhusudancs@gmail.com>
Thu, 06 Aug 2009 18:38:54 +0530
changeset 5 88ae12bc6280
parent 4 8d9da911ed7d
child 6 17cab73c49eb
permissions -rw-r--r--
Access check helper file added.

"""This module contains the views for the project's proposal 
funded by NME through ICT.
"""


__authors__ = [
  '"Madhusudan.C.S" <madhusudancs@gmail.com>',
]


import os
import time

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404

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

rights = {}
rights['getMicr'] = 'proposer'


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, 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, context)

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

    # Generate MICR code
    cleaned_data['micr_code'] = '%s%s%s%d' % (
        cleaned_data['state'], 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.status = 'new'
    project.micr_code = cleaned_data['micr_code']
    micr_code = cleaned_data['micr_code']

    project.save()

    # Create a proposal for the project.
    proposal = project.proposal_set.create(
        document=prop_form.cleaned_data['document'], rev_num = 0)

    proposal.save()

    return HttpResponseRedirect(
        reverse('app.projrev.views.proposal.submit', args=(micr_code,)))

  return HttpResponseRedirect('')

def submitGet(request, micr_code=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),
        }
    prop_form = projrev_forms.ProposalForm(
        initial=initial_vals, instance=project)

    proposal_path = str(project.proposal_set.all()[0].document)

    proposal_name = proposal_path.split('/')[-1]

    context['proposal_path'] = proposal_path
    context['proposal_name'] = proposal_name

    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
  else:
    prop_form = projrev_forms.ProposalForm()

  context['form'] = prop_form

  template = 'projrev/proposal/submit.html'

  return render_to_response(template, context)

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, context)

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)

    # 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):
  """
  """

  if not micr_code:
    template = 'projrev/proposal/list.html'
    context = {
        'projects': Project.objects.all(),
        'row_url': '/proposal/review/',
        }

    return render_to_response(template, context)

  if not rev_form:
    rev_form = projrev_forms.ReviewForm()

  proposal_path = str(Project.objects.get(
          micr_code=micr_code).proposal_set.all()[0].document)

  proposal_name = proposal_path.split('/')[-1]

  context = {
      'form': rev_form,
      'project': Project.objects.get(micr_code=micr_code),
      'proposal_path': proposal_path,
      'proposal_name': proposal_name,
      }

  template = 'projrev/proposal/review.html'

  return render_to_response(template, context)

def rank(request, micr_code=None):
  """
  """

  if request.method == 'POST':
    return rankPost(request, micr_code)
  else:
    return rankGet(request, micr_code)

def rankPost(request, micr_code=None):
  """
  """

  return rankGet(request, micr_code)

def rankGet(request, micr_code=None):
  """
  """

  if not micr_code:
    template = 'projrev/proposal/list.html'
    context = {
        'projects': Project.objects.all(),
        'row_url': '/proposal/rank/',
        }

    return render_to_response(template, context)

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

  proposal_path = str(projects.proposal_set.all()[0].document)

  proposal_name = proposal_path.split('/')[-1]

  reviews = projects.review_set.all()

  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)

  context = {
      'project': projects,
      'proposal_path': proposal_path,
      'proposal_name': proposal_name,
      'review_score': review_score,
      'total_score': total_score,
      }

  template = 'projrev/proposal/rank.html'

  return render_to_response(template, context)