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

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

Turn all functions subject to customization into methods of a global utility component called StudentsUtils?. This is really an incredible improvement and eases customization a lot.

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