source: main/waeup.sirp/trunk/src/waeup/sirp/students/utils.py @ 7259

Last change on this file since 7259 was 7256, checked in by Henrik Bettermann, 13 years ago

pyflakes

  • Property svn:keywords set to Id
File size: 7.3 KB
Line 
1## $Id: utils.py 7256 2011-12-03 05:46:52Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""General helper functions for the student section.
19"""
20import grok
21from random import SystemRandom as r
22from datetime import datetime
23from reportlab.pdfgen import canvas
24from reportlab.lib.units import cm
25from reportlab.lib.pagesizes import A4
26from reportlab.lib.styles import getSampleStyleSheet
27from reportlab.platypus import (Frame, Paragraph, Image,
28    Table, Spacer)
29from reportlab.platypus.tables import TableStyle
30from zope.formlib.form import setUpEditWidgets
31from waeup.sirp.students.interfaces import IStudentsUtils
32
33SLIP_STYLE = TableStyle(
34    [('VALIGN',(0,0),(-1,-1),'TOP')]
35    )
36
37def generate_student_id(students,letter):
38    if letter == '?':
39        letter= r().choice('ABCDEFGHKLMNPQRSTUVWXY')
40    sid = u"%c%d" % (letter,r().randint(99999,1000000))
41    while sid in students.keys():
42        sid = u"%c%d" % (letter,r().randint(99999,1000000))
43    return sid
44
45def set_returning_data(student):
46    student['studycourse'].current_level += 100
47    student['studycourse'].current_session += 1
48    verdict = student['studycourse'].current_verdict
49    student['studycourse'].current_verdict = '0'
50    student['studycourse'].previous_verdict = verdict
51    return
52
53def set_up_widgets(view, ignore_request=False):
54    view.adapters = {}
55    view.widgets = setUpEditWidgets(
56        view.form_fields, view.prefix, view.context, view.request,
57        adapters=view.adapters, for_display=True,
58        ignore_request=ignore_request
59        )
60
61def render_student_data(student, studentview):
62    set_up_widgets(studentview, ignore_request=True)
63    data = []
64    style = getSampleStyleSheet()
65    for widget in studentview.widgets:
66        if widget.name == 'form.adm_code':
67            continue
68        f_label = '<font size=12>%s</font>:' % widget.label.strip()
69        f_label = Paragraph(f_label, style["Normal"])
70        f_text = '<font size=12>%s</font>' % widget()
71        f_text = Paragraph(f_text, style["Normal"])
72        data.append([f_label,f_text])
73    table = Table(data,style=SLIP_STYLE)
74    return table
75
76class StudentsUtils(grok.GlobalUtility):
77    """A collection of methods subject to customization.
78    """
79    grok.implements(IStudentsUtils)
80
81    def getPaymentDetails(self,category, student):
82        d = {}
83        d['p_item'] = u''
84        d['amount'] = 0
85        d['error'] = u''
86        d['p_session'] = student['studycourse'].current_session
87        session = str(d['p_session'])
88        try:
89            academic_session = grok.getSite()['configuration'][session]
90        except KeyError:
91            d['error'] = u'Session configuration object is not available.'
92            return d
93        d['surcharge_1'] = academic_session.surcharge_1
94        d['surcharge_2'] = academic_session.surcharge_2
95        d['surcharge_3'] = academic_session.surcharge_3
96        if category == 'schoolfee':
97            d['amount'] = academic_session.school_fee_base
98            d['p_item'] = student['studycourse'].certificate.code
99        elif category == 'clearance':
100            d['p_item'] = student['studycourse'].certificate.code
101            d['amount'] = academic_session.clearance_fee
102        elif category == 'bed_allocation':
103            d['p_item'] = self.getAccommodationDetails(student)['bt']
104            d['amount'] = academic_session.booking_fee
105        return d
106
107    def getAccommodationDetails(self, student):
108        d = {}
109        d['error'] = u''
110        site_confoguration = grok.getSite()['configuration']
111        d['booking_session'] = site_confoguration.accommodation_session
112        d['allowed_states'] = site_confoguration.accommodation_states
113        # Determine bed type
114        studycourse = student['studycourse']
115        entry_session = studycourse.entry_session
116        current_level = studycourse.current_level
117        end_level = studycourse.certificate.end_level
118        if entry_session == grok.getSite()['configuration'].accommodation_session:
119            bt = 'fr'
120        elif current_level >= end_level:
121            bt = 'fi'
122        else:
123            bt = 're'
124        if student.sex == 'f':
125            sex = 'female'
126        else:
127            sex = 'male'
128        special_handling = 'regular'
129        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
130        return d
131
132    # In the standard configuration we select the first bed found,
133    # but can also randomize the selection if we like.
134    def selectBed(self, available_beds):
135        return available_beds[0]
136
137    def renderPDF(self, view, subject='', filename='slip.pdf',
138        student=None, studentview=None):
139        # (0,0),(-1,-1) = whole table
140        # (0,0),(0,-1) = first column
141        # (-1,0),(-1,-1) = last column
142        # (0,0),(-1,0) = first row
143        # (0,-1),(-1,-1) = last row
144
145        pdf = canvas.Canvas(filename,pagesize=A4)
146        pdf.setTitle(view.label)
147        pdf.setSubject(subject)
148        pdf.setAuthor('%s (%s)' % (view.request.principal.title,
149            view.request.principal.id))
150        pdf.setCreator('WAeUP SIRP')
151        width, height = A4
152        style = getSampleStyleSheet()
153        pdf.line(1*cm,height-(1.8*cm),width-(1*cm),height-(1.8*cm))
154
155        story = []
156        frame_header = Frame(1*cm,1*cm,width-(1.7*cm),height-(1.7*cm))
157        header_title = getattr(grok.getSite(), 'name', u'Sample University')
158        story.append(Paragraph(header_title, style["Heading1"]))
159        frame_header.addFromList(story,pdf)
160
161        story = []
162        frame_body = Frame(1*cm,1*cm,width-(2*cm),height-(3.5*cm))
163        story.append(Paragraph(view.label, style["Heading2"]))
164        #story.append(HRFlowable())
165        if student:
166            story.append(Spacer(1, 18))
167            studenttable = render_student_data(student, studentview)
168            story.append(studenttable)
169        story.append(Spacer(1, 18))
170        set_up_widgets(view)
171        data = []
172        for widget in view.widgets:
173            f_label = '<font size=12>%s</font>:' % widget.label.strip()
174            f_label = Paragraph(f_label, style["Normal"])
175            f_text = '<font size=12>%s</font>' % widget()
176            f_text = Paragraph(f_text, style["Normal"])
177            data.append([f_label,f_text])
178        table = Table(data,style=SLIP_STYLE)
179        story.append(table)
180        frame_body.addFromList(story,pdf)
181
182        story = []
183        frame_footer = Frame(1*cm,0,width-(2*cm),1*cm)
184        timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
185        f_text = '<font size=10>%s</font>' % timestamp
186        story.append(Paragraph(f_text, style["Normal"]))
187        frame_footer.addFromList(story,pdf)
188
189        view.response.setHeader(
190            'Content-Type', 'application/pdf')
191        return pdf.getpdfdata()
Note: See TracBrowser for help on using the repository browser.