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

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

Use the viewlet manager 'FileManager?' to render either images or placeholders of uploaded files.

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