source: main/waeup.uniben/trunk/src/waeup/uniben/students/utils.py @ 9463

Last change on this file since 9463 was 9459, checked in by Henrik Bettermann, 12 years ago

Customize renderPDF.

  • Property svn:keywords set to Id
File size: 11.4 KB
Line 
1## $Id: utils.py 9459 2012-10-29 13:13:18Z 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##
18import grok
19from time import time
20from zope.component import createObject, getUtility
21from reportlab.lib.styles import getSampleStyleSheet
22from reportlab.platypus import Paragraph, Image, Table, Spacer
23from waeup.kofa.interfaces import IKofaUtils, CLEARED, RETURNING, PAID
24from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
25from waeup.kofa.accesscodes import create_accesscode
26from waeup.uniben.interfaces import MessageFactory as _
27from waeup.kofa.students.utils import (trans, render_student_data,
28    render_table_data, get_signature_table)
29
30class CustomStudentsUtils(NigeriaStudentsUtils):
31    """A collection of customized methods.
32
33    """
34
35    def getReturningData(self, student):
36        """ This method defines what happens after school fee payment
37        of returning students depending on the student's senate verdict.
38        """
39        prev_level = student['studycourse'].current_level
40        cur_verdict = student['studycourse'].current_verdict
41        if cur_verdict in ('A','B','L','M','N','Z',):
42            # Successful student
43            new_level = divmod(int(prev_level),100)[0]*100 + 100
44        elif cur_verdict == 'C':
45            # Student on probation
46            new_level = int(prev_level) + 10
47        else:
48            # Student is somehow in an undefined state.
49            # Level has to be set manually.
50            new_level = prev_level
51        new_session = student['studycourse'].current_session + 1
52        return new_session, new_level
53
54    def setPaymentDetails(self, category, student,
55            previous_session, previous_level):
56        """Create Payment object and set the payment data of a student for
57        the payment category specified.
58
59        """
60        details = {}
61        p_item = u''
62        amount = 0.0
63        error = u''
64        if previous_session:
65            p_session = previous_session
66            p_level = previous_level
67            p_current = False
68        else:
69            p_session = student['studycourse'].current_session
70            p_level = student['studycourse'].current_level
71            p_current = True
72        session = str(p_session)
73        try:
74            academic_session = grok.getSite()['configuration'][session]
75        except KeyError:
76            return _(u'Session configuration object is not available.'), None
77        # Determine fee.
78        if category == 'transfer':
79            amount = academic_session.transfer_fee
80        elif category == 'gown':
81            amount = academic_session.gown_fee
82        elif category == 'bed_allocation':
83            amount = academic_session.booking_fee
84        elif category == 'hostel_maintenance':
85            amount = academic_session.maint_fee
86        elif category == 'clearance':
87            try:
88                p_item = student['studycourse'].certificate.code
89            except (AttributeError, TypeError):
90                return _('Study course data are incomplete.'), None
91            if p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
92                'MBBSMED', 'MBBSNDU'):
93                amount = 65000.0
94            elif p_item in ('BEDCET', 'BIOEDCET', 'CHMEDCET', 'ISEDCET',
95                'MTHEDCET', 'PHYEDCET', 'ITECET', 'AGREDCET', 'HEEDCET'):
96                amount = 22500.0
97            else:
98                amount = 45000.0
99        elif category == 'schoolfee':
100            try:
101                certificate = student['studycourse'].certificate
102                p_item = certificate.code
103            except (AttributeError, TypeError):
104                return _('Study course data are incomplete.'), None
105            if previous_session:
106                if previous_session < student['studycourse'].entry_session:
107                    return _('The previous session must not fall below '
108                             'your entry session.'), None
109                if previous_session > student['studycourse'].current_session - 1:
110                    return _('This is not a previous session.'), None
111                if previous_session == student['studycourse'].entry_session:
112                    if student.is_foreigner:
113                        amount = getattr(certificate, 'school_fee_3', 0.0)
114                    else:
115                        amount = getattr(certificate, 'school_fee_1', 0.0)
116                else:
117                    if student.is_foreigner:
118                        amount = getattr(certificate, 'school_fee_4', 0.0)
119                    else:
120                        amount = getattr(certificate, 'school_fee_2', 0.0)
121            else:
122                if student.state == CLEARED:
123                    if student.is_foreigner:
124                        amount = getattr(certificate, 'school_fee_3', 0.0)
125                    else:
126                        amount = getattr(certificate, 'school_fee_1', 0.0)
127                elif student.state == RETURNING:
128                    # In case of returning school fee payment the payment session
129                    # and level contain the values of the session the student
130                    # has paid for.
131                    p_session, p_level = self.getReturningData(student)
132                    if student.is_foreigner:
133                        amount = getattr(certificate, 'school_fee_4', 0.0)
134                    else:
135                        amount = getattr(certificate, 'school_fee_2', 0.0)
136                    try:
137                        academic_session = grok.getSite()[
138                            'configuration'][str(p_session)]
139                    except KeyError:
140                        return _(u'Session configuration object is not available.'), None
141                elif student.state == PAID  and student.is_postgrad and \
142                    not student.is_special_postgrad:
143                    # Regular returning postgraduate students also pay
144                    # for the next session but their level always remains the same.
145                    p_session += 1
146                    if student.is_foreigner:
147                        amount = getattr(certificate, 'school_fee_4', 0.0)
148                    else:
149                        amount = getattr(certificate, 'school_fee_2', 0.0)
150                    try:
151                        academic_session = grok.getSite()[
152                            'configuration'][str(p_session)]
153                    except KeyError:
154                        return _(u'Session configuration object is not available.'), None
155            # Give 50% school fee discount to staff members.
156            if student.is_staff:
157                amount /= 2
158        if amount in (0.0, None):
159            return _('Amount could not be determined.' +
160                     ' Would you like to pay for a previous session?'), None
161        # Add session specific penalty fee.
162        if category == 'schoolfee' and student.is_postgrad:
163            amount += academic_session.penalty_pg
164        elif category == 'schoolfee':
165            amount += academic_session.penalty_ug
166        # Create ticket.
167        for key in student['payments'].keys():
168            ticket = student['payments'][key]
169            if ticket.p_state == 'paid' and\
170               ticket.p_category == category and \
171               ticket.p_item == p_item and \
172               ticket.p_session == p_session:
173                  return _('This type of payment has already been made.' +
174                           ' Would you like to pay for a previous session?'), None
175        payment = createObject(u'waeup.StudentOnlinePayment')
176        timestamp = ("%d" % int(time()*10000))[1:]
177        payment.p_id = "p%s" % timestamp
178        payment.p_category = category
179        payment.p_item = p_item
180        payment.p_session = p_session
181        payment.p_level = p_level
182        payment.p_current = p_current
183        payment.amount_auth = amount
184        return None, payment
185
186    def renderPDF(self, view, filename='slip.pdf', student=None,
187                  studentview=None, tableheader=None, tabledata=None,
188                  note=None, signatures=None):
189        """Render pdf slips for various pages.
190        """
191        # XXX: we have to fix the import problems here.
192        from waeup.kofa.browser.interfaces import IPDFCreator
193        from waeup.kofa.browser.pdf import NORMAL_STYLE, ENTRY1_STYLE
194        style = getSampleStyleSheet()
195        creator = getUtility(IPDFCreator)
196        data = []
197        doc_title = view.label
198        author = '%s (%s)' % (view.request.principal.title,
199                              view.request.principal.id)
200        footer_text = view.label
201        if getattr(student, 'student_id', None) is not None:
202            footer_text = "%s - %s - " % (student.student_id, footer_text)
203
204        # Insert student data table
205        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
206        if student is not None:
207            bd_translation = trans(_('Base Data'), portal_language)
208            data.append(Paragraph(bd_translation, style["Heading3"]))
209            data.append(render_student_data(studentview))
210
211        # Insert widgets
212        if view.form_fields:
213            data.append(Paragraph(view.title, style["Heading3"]))
214            portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
215            separators = getattr(self, 'SEPARATORS_DICT', {})
216            table = creator.getWidgetsTable(
217                view.form_fields, view.context, None, lang=portal_language,
218                separators=separators)
219            data.append(table)
220
221        # Insert scanned docs
222        #data.extend(docs_as_flowables(view, portal_language))
223
224       # Insert content table (optionally on second page)
225        if tabledata and tableheader:
226            #data.append(PageBreak())
227            data.append(Spacer(1, 20))
228            data.append(Paragraph(view.content_title, style["Heading3"]))
229            contenttable = render_table_data(tableheader,tabledata)
230            data.append(contenttable)
231
232        # Insert signatures
233        if signatures:
234            data.append(Spacer(1, 20))
235            signaturetable = get_signature_table(signatures)
236            data.append(signaturetable)
237
238        # Insert history
239        if filename.startswith('clearance') or filename.startswith('course'):
240            data.append(Spacer(1, 20))
241            hist_translation = trans(_('Workflow History'), portal_language)
242            data.append(Paragraph(hist_translation, style["Heading3"]))
243            data.extend(creator.fromStringList(student.history.messages))
244
245        view.response.setHeader(
246            'Content-Type', 'application/pdf')
247        try:
248            pdf_stream = creator.create_pdf(
249                data, None, doc_title, author=author, footer=footer_text,
250                note=note)
251        except IOError:
252            view.flash('Error in image file.')
253            return view.redirect(view.url(view.context))
254        return pdf_stream
255
256    # Uniben prefix
257    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.