source: main/waeup.kofa/trunk/src/waeup/kofa/students/utils.py @ 8185

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

Part 2: Consider time zone when creating datetime strings for histories, filenames etc.

  • Property svn:keywords set to Id
File size: 14.3 KB
Line 
1## $Id: utils.py 8183 2012-04-16 21:07:28Z 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 and utilities for the student section.
19"""
20import grok
21from random import SystemRandom as r
22from datetime import datetime
23from zope.i18n import translate
24from zope.component import getUtility
25from reportlab.pdfgen import canvas
26from reportlab.lib import colors
27from reportlab.lib.units import cm
28from reportlab.lib.enums import TA_RIGHT
29from reportlab.lib.pagesizes import A4
30from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
31from reportlab.platypus import (Frame, Paragraph, Image, PageBreak, Table,
32                                Spacer)
33from reportlab.platypus.tables import TableStyle
34from reportlab.platypus.flowables import PageBreak
35from zope.component import getUtility
36from zope.formlib.form import setUpEditWidgets
37
38from waeup.kofa.interfaces import IExtFileStore, IKofaUtils
39from waeup.kofa.interfaces import MessageFactory as _
40from waeup.kofa.students.interfaces import IStudentsUtils
41
42SLIP_STYLE = [
43    ('VALIGN',(0,0),(-1,-1),'TOP'),
44    #('FONT', (0,0), (-1,-1), 'Helvetica', 11),
45    ]
46
47CONTENT_STYLE = [
48    ('VALIGN',(0,0),(-1,-1),'TOP'),
49    #('FONT', (0,0), (-1,-1), 'Helvetica', 8),
50    #('TEXTCOLOR',(0,0),(-1,0),colors.white),
51    ('BACKGROUND',(0,0),(-1,0),colors.black),
52    ]
53
54FONT_SIZE = 10
55FONT_COLOR = 'black'
56
57def formatted_label(color=FONT_COLOR, size=FONT_SIZE):
58    tag1 ='<font color=%s size=%d>' % (color, size)
59    return tag1 + '%s:</font>'
60
61def trans(text, lang):
62    # shortcut
63    return translate(text, 'waeup.kofa', target_language=lang)
64
65def formatted_text(text, color=FONT_COLOR, size=FONT_SIZE):
66    """Turn `text`, `color` and `size` into an HTML snippet.
67
68    The snippet is suitable for use with reportlab and generating PDFs.
69    Wraps the `text` into a ``<font>`` tag with passed attributes.
70
71    Also non-strings are converted. Raw strings are expected to be
72    utf-8 encoded (usually the case for widgets etc.).
73
74    Finally, a br tag is added if widgets contain div tags
75    which are not supported by reportlab.
76
77    The returned snippet is unicode type.
78    """
79    try:
80        # In unit tests IKofaUtils has not been registered
81        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
82    except:
83        portal_language = 'en'
84    if not isinstance(text, unicode):
85        if isinstance(text, basestring):
86            text = text.decode('utf-8')
87        else:
88            text = unicode(text)
89    # Mainly for boolean values we need our customized
90    # localisation of the zope domain
91    text = translate(text, 'zope', target_language=portal_language)
92    text = text.replace('</div>', '<br /></div>')
93    tag1 = u'<font color="%s" size="%d">' % (color, size)
94    return tag1 + u'%s</font>' % text
95
96def generate_student_id(students,letter):
97    if letter == '?':
98        letter= r().choice('ABCDEFGHKLMNPQRSTUVWXY')
99    sid = u"%c%d" % (letter,r().randint(99999,1000000))
100    while sid in students.keys():
101        sid = u"%c%d" % (letter,r().randint(99999,1000000))
102    return sid
103
104def set_up_widgets(view, ignore_request=False):
105    view.adapters = {}
106    view.widgets = setUpEditWidgets(
107        view.form_fields, view.prefix, view.context, view.request,
108        adapters=view.adapters, for_display=True,
109        ignore_request=ignore_request
110        )
111
112def render_student_data(studentview):
113    """Render student table for an existing frame.
114    """
115    width, height = A4
116    set_up_widgets(studentview, ignore_request=True)
117    data_left = []
118    data_right = []
119    style = getSampleStyleSheet()
120    img = getUtility(IExtFileStore).getFileByContext(
121        studentview.context, attr='passport.jpg')
122    if img is None:
123        from waeup.kofa.browser import DEFAULT_PASSPORT_IMAGE_PATH
124        img = open(DEFAULT_PASSPORT_IMAGE_PATH, 'rb')
125    doc_img = Image(img.name, width=4*cm, height=4*cm, kind='bound')
126    data_left.append([doc_img])
127    #data.append([Spacer(1, 12)])
128    portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
129    for widget in studentview.widgets:
130        if widget.name == 'form.adm_code':
131            continue
132        f_label = formatted_label(size=12) % translate(
133            widget.label.strip(), 'waeup.kofa',
134            target_language=portal_language)
135        f_label = Paragraph(f_label, style["Normal"])
136        f_text = formatted_text(widget(), size=12)
137        f_text = Paragraph(f_text, style["Normal"])
138        data_right.append([f_label,f_text])
139    table_left = Table(data_left,style=SLIP_STYLE)
140    table_right = Table(data_right,style=SLIP_STYLE, colWidths=[5*cm, 6*cm])
141    table = Table([[table_left, table_right],],style=SLIP_STYLE)
142    return table
143
144def render_table_data(tableheader,tabledata):
145    """Render children table for an existing frame.
146    """
147    data = []
148    #data.append([Spacer(1, 12)])
149    line = []
150    style = getSampleStyleSheet()
151    for element in tableheader:
152        field = formatted_text(element[0], color='white')
153        field = Paragraph(field, style["Normal"])
154        line.append(field)
155    data.append(line)
156    for ticket in tabledata:
157        line = []
158        for element in tableheader:
159              field = formatted_text(getattr(ticket,element[1],u' '))
160              field = Paragraph(field, style["Normal"])
161              line.append(field)
162        data.append(line)
163    table = Table(data,colWidths=[
164        element[2]*cm for element in tableheader], style=CONTENT_STYLE)
165    return table
166
167def docs_as_flowables(view, lang='en'):
168    """Create reportlab flowables out of scanned docs.
169    """
170    # XXX: fix circular import problem
171    from waeup.kofa.students.viewlets import FileManager
172    from waeup.kofa.browser import DEFAULT_IMAGE_PATH
173    from waeup.kofa.browser.pdf import NORMAL_STYLE, ENTRY1_STYLE
174    style = getSampleStyleSheet()
175    data = []
176
177    # Collect viewlets
178    fm = FileManager(view.context, view.request, view)
179    fm.update()
180    if fm.viewlets:
181        sc_translation = trans(_('Scanned Documents'), lang)
182        data.append(Paragraph(sc_translation, style["Heading3"]))
183        # Insert list of scanned documents
184        table_data = []
185        for viewlet in fm.viewlets:
186            f_label = Paragraph(trans(viewlet.label, lang), ENTRY1_STYLE)
187            img_path = getattr(getUtility(IExtFileStore).getFileByContext(
188                view.context, attr=viewlet.download_name), 'name', None)
189            f_text = Paragraph(trans(_('(not provided)'),lang), ENTRY1_STYLE)
190            if img_path is None:
191                pass
192            elif not img_path.endswith('.jpg'):
193                # reportlab requires jpg images, I think.
194                f_text = Paragraph('%s (Not displayable)' % (
195                    viewlet.title,), ENTRY1_STYLE)
196            else:
197                f_text = Image(img_path, width=2*cm, height=1*cm, kind='bound')
198            table_data.append([f_label, f_text])
199        if table_data:
200            # safety belt; empty tables lead to problems.
201            data.append(Table(table_data, style=SLIP_STYLE))
202    return data
203
204def insert_footer(pdf,width,style,text=None, number_of_pages=1):
205      """Render the whole footer frame.
206      """
207      story = []
208      frame_footer = Frame(1*cm,0,width-(2*cm),1*cm)
209      tz = getUtility(IKofaUtils).tzinfo
210      timestamp = datetime.now(tz).strftime("%d/%m/%Y %H:%M:%S")
211      left_text = '<font size=10>%s</font>' % timestamp
212      story.append(Paragraph(left_text, style["Normal"]))
213      frame_footer.addFromList(story,pdf)
214      story = []
215      frame_footer = Frame(1*cm,0,width-(2*cm),1*cm)
216      portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
217      right_text = translate(_('<font size=10>${a} Page ${b} of ${c}</font>',
218          mapping = {'a':text, 'b':pdf.getPageNumber(), 'c':number_of_pages}),
219          'waeup.kofa', target_language=portal_language)
220      story.append(Paragraph(right_text, style["Right"]))
221      frame_footer.addFromList(story,pdf)
222
223class StudentsUtils(grok.GlobalUtility):
224    """A collection of methods subject to customization.
225    """
226    grok.implements(IStudentsUtils)
227
228    def setReturningData(self, student):
229        """ This method defines what happens after school fee payment
230        depending on the student's senate verdict.
231
232        In the base configuration current level is always increased
233        by 100 no matter which verdict has been assigned.
234        """
235        student['studycourse'].current_level += 100
236        student['studycourse'].current_session += 1
237        verdict = student['studycourse'].current_verdict
238        student['studycourse'].current_verdict = '0'
239        student['studycourse'].previous_verdict = verdict
240        return
241
242    def getPaymentDetails(self, category, student):
243        """Get the payment dates of a student for the payment category
244        specified.
245        """
246        d = {}
247        d['p_item'] = u''
248        d['amount'] = 0.0
249        d['error'] = u''
250        d['p_session'] = student['studycourse'].current_session
251        session = str(d['p_session'])
252        try:
253            academic_session = grok.getSite()['configuration'][session]
254        except KeyError:
255            d['error'] = u'Session configuration object is not available.'
256            return d
257        d['surcharge_1'] = academic_session.surcharge_1
258        d['surcharge_2'] = academic_session.surcharge_2
259        d['surcharge_3'] = academic_session.surcharge_3
260        if category == 'schoolfee':
261            d['amount'] = academic_session.school_fee_base
262            d['p_item'] = student['studycourse'].certificate.code
263        elif category == 'clearance':
264            d['p_item'] = student['studycourse'].certificate.code
265            d['amount'] = academic_session.clearance_fee
266            d['surcharge_1'] = 0.0 # no portal fee
267        elif category == 'bed_allocation':
268            d['p_item'] = self.getAccommodationDetails(student)['bt']
269            d['amount'] = academic_session.booking_fee
270            d['surcharge_1'] = 0.0 # no portal fee
271        return d
272
273    def getAccommodationDetails(self, student):
274        """Determine the accommodation dates of a student.
275        """
276        d = {}
277        d['error'] = u''
278        site_configuration = grok.getSite()['configuration']
279        d['booking_session'] = site_configuration.accommodation_session
280        d['allowed_states'] = site_configuration.accommodation_states
281        # Determine bed type
282        studycourse = student['studycourse']
283        certificate = getattr(studycourse,'certificate',None)
284        entry_session = studycourse.entry_session
285        current_level = studycourse.current_level
286        if not (entry_session and current_level and certificate):
287            return
288        end_level = certificate.end_level
289        if entry_session == grok.getSite()[
290            'configuration'].accommodation_session:
291            bt = 'fr'
292        elif current_level >= end_level:
293            bt = 'fi'
294        else:
295            bt = 're'
296        if student.sex == 'f':
297            sex = 'female'
298        else:
299            sex = 'male'
300        special_handling = 'regular'
301        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
302        return d
303
304    def selectBed(self, available_beds):
305        """Select a bed from a list of available beds.
306
307        In the base configuration we select the first bed found,
308        but can also randomize the selection if we like.
309        """
310        return available_beds[0]
311
312    def renderPDF(self, view, filename='slip.pdf',
313        student=None, studentview=None, tableheader=None, tabledata=None):
314        """Render pdf slips for various pages.
315        """
316        # XXX: we have to fix the import problems here.
317        from waeup.kofa.browser.interfaces import IPDFCreator
318        from waeup.kofa.browser.pdf import NORMAL_STYLE, ENTRY1_STYLE
319        style = getSampleStyleSheet()
320        creator = getUtility(IPDFCreator)
321        data = []
322        doc_title = view.label
323        author = '%s (%s)' % (view.request.principal.title,
324                              view.request.principal.id)
325        footer_text = view.label
326        if getattr(student, 'student_id', None) is not None:
327            footer_text = "%s - %s - " % (student.student_id, footer_text)
328
329        # Insert student data table
330        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
331        if student is not None:
332            bd_translation = trans(_('Base Data'), portal_language)
333            data.append(Paragraph(bd_translation, style["Heading3"]))
334            data.append(render_student_data(studentview))
335
336        # Insert widgets
337        data.append(Paragraph(view.title, style["Heading3"]))
338        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
339        separators = getattr(self, 'SEPARATORS_DICT', {})
340        table = creator.getWidgetsTable(
341            view.form_fields, view.context, None, lang=portal_language,
342            separators=separators)
343        data.append(table)
344
345        # Insert scanned docs
346        data.extend(docs_as_flowables(view, portal_language))
347
348        # Insert content table (optionally on second page)
349        if tabledata and tableheader:
350            #data.append(PageBreak())
351            data.append(Spacer(1, 20))
352            data.append(Paragraph(view.content_title, style["Heading3"]))
353            contenttable = render_table_data(tableheader,tabledata)
354            data.append(contenttable)
355
356        view.response.setHeader(
357            'Content-Type', 'application/pdf')
358        try:
359            pdf_stream = creator.create_pdf(
360                data, None, doc_title, author=author, footer=footer_text)
361        except IOError:
362            view.flash('Error in image file.')
363            return view.redirect(view.url(view.context))
364        return pdf_stream
365
366    VERDICTS_DICT = {
367        '0': _('(not yet)'),
368        'A': 'Successful student',
369        'B': 'Student with carryover courses',
370        'C': 'Student on probation',
371        }
372
373    SEPARATORS_DICT = {
374        }
Note: See TracBrowser for help on using the repository browser.