Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…13-Website into events
  • Loading branch information
webopsShaastra committed Dec 28, 2012
2 parents 0531866 + f512c75 commit 2888e0a
Show file tree
Hide file tree
Showing 10 changed files with 316 additions and 13 deletions.
12 changes: 12 additions & 0 deletions controlroom/ajax.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from django.contrib.sitemaps import ping_google
from operator import attrgetter
from datetime import datetime
from controlroom.generate_bill import *

@dajaxice_register
def save_individual_checkin(request,form):
Expand Down Expand Up @@ -100,3 +101,14 @@ def send_participants(request,form):
print msg
dajax.alert(msg)
return dajax.json

@dajaxice_register
def GenerateBill(request,s_id=''):
dajax = Dajax()
try:
pdf = generateParticipantPDF(s_id)
return HttpResponse(pdf)
except:
return dajax.json


3 changes: 2 additions & 1 deletion controlroom/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ class AddMultipleRoomsForm(forms.Form):
rooms = forms.FileField(required = True)

class ShaastraIDForm(forms.Form):
shaastraID = forms.CharField(help_text = 'Enter Shaastra ID of participant')
shaastraID = forms.CharField(required = False,help_text = 'Enter Shaastra ID')
email = forms.CharField(required = False,help_text = 'Enter Email ID')

class IndividualForm(ModelForm):
room = chosenforms.ChosenModelChoiceField(queryset=AvailableRooms.objects.filter(already_checkedin__lt=F('max_number')).order_by('hostel'))
Expand Down
149 changes: 149 additions & 0 deletions controlroom/generate_bill.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
from users.models import UserProfile, College, Team
from django.contrib.auth.models import User
from events.models import Event, EventSingularRegistration
from controlroom.models import *

from django.contrib.auth.decorators import login_required
from django.core.mail import EmailMultiAlternatives
from django.http import HttpResponseForbidden, HttpResponse

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.lib import colors
from reportlab.platypus import Table, TableStyle
from reportlab.pdfbase.pdfmetrics import getFont, getAscentDescent
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet

def PDFSetFont(pdf, font_name, font_size):
"""
Sets the font and returns the lineheight.
"""

pdf.setFont(font_name, font_size)
(ascent, descent) = getAscentDescent(font_name, font_size)
return ascent - descent # Returns line height

def initNewPDFPage(pdf, page_title, page_no, (pageWidth, pageHeight),):
"""
Paints the headers on every new page of the PDF document.
Also returns the coordinates (x, y) where the last painting operation happened.
"""

y = pageHeight

# Leave a margin of one cm at the top

y = pageHeight - cm

# Set font for 'SHAASTRA 2013'

lineheight = PDFSetFont(pdf, 'Times-Roman', 18)

# SHAASTRA 2013 in centre

pdf.drawCentredString(pageWidth / 2, y, 'SHAASTRA 2013')
y -= lineheight + cm

# Set font for Page Title

lineheight = PDFSetFont(pdf, 'Times-Roman', 16)

# Page Title in next line, centre aligned

pdf.drawCentredString(pageWidth / 2, y, page_title)

# Set font for Document Title

PDFSetFont(pdf, 'Times-Roman', 9)

# Page number in same line, right aligned

pdf.drawRightString(pageWidth - cm, y, '#%d' % page_no)

y -= lineheight + cm

return y

def paintParagraph(pdf, x, y, text):

styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name = 'paraStyle', fontSize = 12))

p = Paragraph(text, styles['paraStyle'], None) # None for bullet type

(A4Width, A4Height) = A4
availableWidth = A4Width - 2 * cm # Leaving margins of 1 cm on both sides
availableHeight = y
(paraWidth, paraHeight) = p.wrap(availableWidth, availableHeight) # find required space

p.drawOn(pdf, x, y - paraHeight)

y -= paraHeight + cm

return y

def printParticipantDetails(pdf, x, y, s_id):
try:
checkedin = IndividualCheckIn.objects.get(shaastra_ID=s_id)
except:
msg = "This participant has not been checked in!"

lineheight = PDFSetFont(pdf, 'Times-Roman', 12)

pdf.drawString(x, y, 'Shaastra ID: %s' % checkedin.shaastra_ID)

y -= lineheight + (cm * 0.8)

pdf.drawString(x, y, 'Name: %s %s' % (checkedin.first_name, checkedin.last_name))

y -= lineheight + (cm * 0.8)


pdf.drawString(x, y, 'Mobile No: %s' % checkedin.phone_no)

y -= lineheight + (cm * 0.8)

return y

def generateParticipantPDF(s_id):

userProfile = UserProfile.objects.get(shaastra_id = s_id)

response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = \
'filename=Accomodation Bill.pdf'

# Create the PDF object, using the response object as its "file."

pdf = canvas.Canvas(response, pagesize=A4)

# Define the title of the document as printed in the document header.

page_title = 'Accomodation Bill'

# Get the width and height of the page.

(A4Width, A4Height) = A4

# Page number

pageNo = 1

# Paint the headers and get the coordinates

y = initNewPDFPage(pdf, page_title, pageNo, A4)

# Setting x to be a cm from the left edge

x = cm

# Print Participant Details in PDF

y = printParticipantDetails(pdf, x, y, userProfile.shaastra_id)

pdf.showPage()
pdf.save()

return response
30 changes: 23 additions & 7 deletions controlroom/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,13 @@ def individual(request):
form = ShaastraIDForm(request.POST)
if form.is_valid():
inputs = form.cleaned_data
participant = UserProfile.objects.get(shaastra_id=inputs['shaastraID'])
if inputs['shaastraID']:
participant = UserProfile.objects.get(shaastra_id=inputs['shaastraID'])
else:
usr = User.objects.get(email = inputs['email'])
participant = UserProfile.objects.get(user = usr)
try:
checkedin = IndividualCheckIn.objects.get(shaastra_ID=inputs['shaastraID'])
checkedin = IndividualCheckIn.objects.get(shaastra_ID=participant.shaastra_id)
msg = "This participant is already checked-in!"
return render_to_response('controlroom/shaastraIDform.html', locals(),
context_instance=RequestContext(request))
Expand Down Expand Up @@ -141,9 +145,13 @@ def team(request):
if form.is_valid():
inputs = form.cleaned_data
try:
leader = UserProfile.objects.get(shaastra_id=inputs['shaastraID'])
try:
leader = UserProfile.objects.get(shaastra_id=inputs['shaastraID'])
except:
usr = User.objects.get(email = inputs['email'])
leader = UserProfile.objects.get(user = usr)
except:
msg = "This shaastra ID does not exist"
msg = "This participant does not exist"
return render_to_response('controlroom/shaastraIDform.html', locals(),
context_instance=RequestContext(request))
check = 0
Expand Down Expand Up @@ -209,15 +217,22 @@ def CheckOut(request):
form = ShaastraIDForm(request.POST)
if form.is_valid():
inputs = form.cleaned_data
participant = UserProfile.objects.get(shaastra_id=inputs['shaastraID'])
if inputs['shaastraID']:
participant = UserProfile.objects.get(shaastra_id=inputs['shaastraID'])
else:
usr = User.objects.get(email = inputs['email'])
participant = UserProfile.objects.get(user = usr)
s_id = participant.shaastra_id
checkedin = IndividualCheckIn.objects.get(shaastra_ID=s_id)
print s_id
try:
checkedin = IndividualCheckIn.objects.get(shaastra_ID=inputs['shaastraID'])
checkedin = IndividualCheckIn.objects.get(shaastra_ID=s_id)
if checkedin.check_out_date:
msg = "This participant is already checked-out!"
return render_to_response('controlroom/shaastraIDform.html', locals(),
context_instance=RequestContext(request))
else:
values = {'check_out_date': datetime.now}
values = {'check_out_date': datetime.now,'check_out_control_room':checkedin.check_in_control_room}
individual_form = IndividualForm(instance=checkedin,initial=values)
return render_to_response('controlroom/individual.html', locals(),
context_instance=RequestContext(request))
Expand Down Expand Up @@ -261,6 +276,7 @@ def Register(request):
college_roll=data['college_roll'],
shaastra_id= ("SHA" + str(x)),
)
userprofile.save()
msg = "Your Shaastra ID is " + shaastra_id
return render_to_response('controlroom/register.html', locals(),
context_instance=RequestContext(request))
Expand Down
4 changes: 3 additions & 1 deletion forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,6 @@ def clean_confirm_password(self):
raise forms.ValidationError(u'Passwords do not match')
return self.cleaned_data['confirm_password']


class FileForm(forms.Form):
event_id = forms.IntegerField()
files = forms.FileField(required = True)
60 changes: 59 additions & 1 deletion participantPdfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ def generateParticipantPDF(user):

if (not singularEventRegistrations) and (not userTeams):
# The user is not registered for any event.
return None
y -= cm * 0.5
pdf.drawString(x, y, 'You are not registered for any events this Shaastra')

Expand Down Expand Up @@ -281,6 +282,63 @@ def mailParticipantPDFs(request):

for participant in participants:
pdf = generateParticipantPDF(participant)
if pdf is None:
continue
mailPDF(participant, pdf)

return HttpResponse('Mails sent. Timestamp: %s' % str(datetime.datetime.now))
return HttpResponse('Mails sent. Timestamp: %s' % str(datetime.datetime.now()))

def savePDF(pdf, sID):

destination = open('/home/shaastra/hospi/participantPDFs/'+sID+'.pdf', 'wb+')
for chunk in pdf.chunks():
destination.write(chunk)
destination.close()
print 'File '+sID+'.pdf saved.'

@login_required
def generateParticipantPDFs(request):

if not request.user.is_superuser:
return HttpResponseForbidden('The participant mailer can only be accessed by superusers. You don\'t have enough permissions to continue.')

participants = []
userProfilesWithShaastraIds = UserProfile.objects.exclude(shaastra_id = '') #TODO Exclude non active users??
participantProfilesWithShaastraIds = userProfilesWithShaastraIds.exclude(is_core = True).filter(is_coord_of = None)
for profile in participantProfilesWithShaastraIds:
try:
u = profile.user
except:
continue
participants.append(u)

participants = [User.objects.get(id = 5787)] #TODO: Remove this line for finale

for participant in participants:
pdf = generateParticipantPDF(participant)
if pdf is None:
continue
savePDF(pdf, participant.get_profile().shaastra_id)

return HttpResponse('PDFs generated. Timestamp: %s' % str(datetime.datetime.now()))

def generatePDFs():

participants = []
userProfilesWithShaastraIds = UserProfile.objects.exclude(shaastra_id = '') #TODO Exclude non active users??
participantProfilesWithShaastraIds = userProfilesWithShaastraIds.exclude(is_core = True).filter(is_coord_of = None)
for profile in participantProfilesWithShaastraIds:
try:
u = profile.user
except:
continue
participants.append(u)

participants = [User.objects.get(id = 1351)] #TODO: Remove this line for finale

for participant in participants:
pdf = generateParticipantPDF(participant)
if pdf is None:
continue
savePDF(pdf, participant.get_profile().shaastra_id)

13 changes: 10 additions & 3 deletions templates/controlroom/individual.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@
Dajaxice.controlroom.save_individual_checkout(Dajax.process,{'form':data,'shaastraid':id});
return false;
}
function generate_bill(id)
{
Dajaxice.controlroom.GenerateBill(Dajax.process,{'s_id':id});
return false;
}
</script>
</head>
<body>
Expand All @@ -56,18 +61,20 @@ <h4>Check In/Check Out Form</h4><br>
{{ individual_form.as_table }}
</table>
</div>
<button class="btn btn-primary" onclick="checkin();" type ='button' value='Save'>Check In</button><br><hr>
<button class="btn btn-primary" onclick="checkout('{{participant.shaastra_id}}');" type ='button' value='Save'>Check Out</button>
{% if request.get_full_path == "/controlroom/individual/" %}
<button class="btn btn-primary" onclick="checkin();" type ='button' value='Save'>Check In</button><br><hr>
<a class="btn btn-large btn-inverse" href='{{site_url}}controlroom/individual/'>Back</a>
{% else %}
{% if request.get_full_path == "/controlroom/checkout/" %}
<button class="btn btn-primary" onclick="checkout('{{participant.shaastra_id}}');" type ='button' value='Save'>Check Out</button>
<a class="btn btn-large btn-inverse" href='{{site_url}}controlroom/checkout/'>Back</a>
{% else %}
<a class="btn btn-large btn-inverse" href='{{site_url}}controlroom/team/'>Back</a>
{% endif %}
{% endif %}
<a class="btn btn-large btn-inverse" href='{{site_url}}controlroom/home/'>Home</a>
<a class="btn btn-large btn-inverse" href='{{site_url}}controlroom/home/'>Home</a>
<a class="btn btn-large btn-inverse" onclick="generate_bill('{{participant.shaastra_id}}');" >Generate Bill</a>

</div>

</body>
Expand Down
13 changes: 13 additions & 0 deletions templates/create_accounts.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<html>
<head>
<title>Shaastra 2013 Control Room</title>
</head>
</html>
<h4><p>{{msg}}</p></h4>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="Upload"/></td>
</form>
</body>
</html>
1 change: 1 addition & 0 deletions urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
urlpatterns = patterns(
'',
url(r'^$', 'views.home', name='home'),
url(r'^create_accounts/', 'views.create', name='create'),
url(r'^spons', 'views.spons', name='spons'),
url(r'^user/', include('users.urls')),
url(r'^admin/', include('admin.urls')),
Expand Down
Loading

0 comments on commit 2888e0a

Please sign in to comment.