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

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

Adjust copyright statement and svn keyword in students.

  • Property svn:keywords set to Id
File size: 7.4 KB
Line 
1## $Id: utils.py 7191 2011-11-25 07:13:22Z 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 date, 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.interfaces import academic_sessions_vocab
32from waeup.sirp.students.interfaces import IStudentsUtils
33
34SLIP_STYLE = TableStyle(
35    [('VALIGN',(0,0),(-1,-1),'TOP')]
36    )
37
38def generate_student_id(students,letter):
39    if letter == '?':
40        letter= r().choice('ABCDEFGHKLMNPQRSTUVWXY')
41    sid = u"%c%d" % (letter,r().randint(99999,1000000))
42    while sid in students.keys():
43        sid = u"%c%d" % (letter,r().randint(99999,1000000))
44    return sid
45
46def set_returning_data(student):
47    student['studycourse'].current_level += 100
48    student['studycourse'].current_session += 1
49    verdict = student['studycourse'].current_verdict
50    student['studycourse'].current_verdict = '0'
51    student['studycourse'].previous_verdict = verdict
52    return
53
54def set_up_widgets(view, ignore_request=False):
55    view.adapters = {}
56    view.widgets = setUpEditWidgets(
57        view.form_fields, view.prefix, view.context, view.request,
58        adapters=view.adapters, for_display=True,
59        ignore_request=ignore_request
60        )
61
62def render_student_data(student, studentview):
63    set_up_widgets(studentview, ignore_request=True)
64    data = []
65    style = getSampleStyleSheet()
66    for widget in studentview.widgets:
67        if widget.name == 'form.adm_code':
68            continue
69        f_label = '<font size=12>%s</font>:' % widget.label.strip()
70        f_label = Paragraph(f_label, style["Normal"])
71        f_text = '<font size=12>%s</font>' % widget()
72        f_text = Paragraph(f_text, style["Normal"])
73        data.append([f_label,f_text])
74    table = Table(data,style=SLIP_STYLE)
75    return table
76
77class StudentsUtils(grok.GlobalUtility):
78    """A collection of methods subject to customization.
79    """
80    grok.implements(IStudentsUtils)
81
82    def getPaymentDetails(self,category, student):
83        d = {}
84        d['p_item'] = u''
85        d['amount'] = 0
86        d['error'] = u''
87        d['p_session'] = student['studycourse'].current_session
88        session = str(d['p_session'])
89        try:
90            academic_session = grok.getSite()['configuration'][session]
91        except KeyError:
92            d['error'] = u'Session configuration object is not available.'
93            return d
94        d['surcharge_1'] = academic_session.surcharge_1
95        d['surcharge_2'] = academic_session.surcharge_2
96        d['surcharge_3'] = academic_session.surcharge_3
97        if category == 'schoolfee':
98            d['amount'] = academic_session.school_fee_base
99            d['p_item'] = student['studycourse'].certificate.code
100        elif category == 'clearance':
101            d['p_item'] = student['studycourse'].certificate.code
102            d['amount'] = academic_session.clearance_fee
103        elif category == 'bed_allocation':
104            d['p_item'] = self.getAccommodationDetails(student)['bt']
105            d['amount'] = academic_session.booking_fee
106        return d
107
108    def getAccommodationDetails(self, student):
109        d = {}
110        d['error'] = u''
111        site_confoguration = grok.getSite()['configuration']
112        d['booking_session'] = site_confoguration.accommodation_session
113        d['allowed_states'] = site_confoguration.accommodation_states
114        session = str(d['booking_session'])
115        # Determine bed type
116        studycourse = student['studycourse']
117        entry_session = studycourse.entry_session
118        current_level = studycourse.current_level
119        end_level = studycourse.certificate.end_level
120        if entry_session == grok.getSite()['configuration'].accommodation_session:
121            bt = 'fr'
122        elif current_level >= end_level:
123            bt = 'fi'
124        else:
125            bt = 're'
126        if student.sex == 'f':
127            sex = 'female'
128        else:
129            sex = 'male'
130        special_handling = 'regular'
131        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
132        return d
133
134    # In the standard configuration we select the first bed found,
135    # but can also randomize the selection if we like.
136    def selectBed(self, available_beds):
137        return available_beds[0]
138
139    def renderPDF(self, view, subject='', filename='slip.pdf',
140        student=None, studentview=None):
141        # (0,0),(-1,-1) = whole table
142        # (0,0),(0,-1) = first column
143        # (-1,0),(-1,-1) = last column
144        # (0,0),(-1,0) = first row
145        # (0,-1),(-1,-1) = last row
146
147        pdf = canvas.Canvas(filename,pagesize=A4)
148        pdf.setTitle(view.label)
149        pdf.setSubject(subject)
150        pdf.setAuthor('%s (%s)' % (view.request.principal.title,
151            view.request.principal.id))
152        pdf.setCreator('WAeUP SIRP')
153        width, height = A4
154        style = getSampleStyleSheet()
155        pdf.line(1*cm,height-(1.8*cm),width-(1*cm),height-(1.8*cm))
156
157        story = []
158        frame_header = Frame(1*cm,1*cm,width-(1.7*cm),height-(1.7*cm))
159        header_title = getattr(grok.getSite(), 'name', u'Sample University')
160        story.append(Paragraph(header_title, style["Heading1"]))
161        frame_header.addFromList(story,pdf)
162
163        story = []
164        frame_body = Frame(1*cm,1*cm,width-(2*cm),height-(3.5*cm))
165        story.append(Paragraph(view.label, style["Heading2"]))
166        #story.append(HRFlowable())
167        if student:
168            story.append(Spacer(1, 18))
169            studenttable = render_student_data(student, studentview)
170            story.append(studenttable)
171        story.append(Spacer(1, 18))
172        set_up_widgets(view)
173        data = []
174        for widget in view.widgets:
175            f_label = '<font size=12>%s</font>:' % widget.label.strip()
176            f_label = Paragraph(f_label, style["Normal"])
177            f_text = '<font size=12>%s</font>' % widget()
178            f_text = Paragraph(f_text, style["Normal"])
179            data.append([f_label,f_text])
180        table = Table(data,style=SLIP_STYLE)
181        story.append(table)
182        frame_body.addFromList(story,pdf)
183
184        story = []
185        frame_footer = Frame(1*cm,0,width-(2*cm),1*cm)
186        timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
187        f_text = '<font size=10>%s</font>' % timestamp
188        story.append(Paragraph(f_text, style["Normal"]))
189        frame_footer.addFromList(story,pdf)
190
191        view.response.setHeader(
192            'Content-Type', 'application/pdf')
193        return pdf.getpdfdata()
Note: See TracBrowser for help on using the repository browser.