source: main/waeup.fceokene/trunk/src/waeup/fceokene/students/utils.py @ 18262

Last change on this file since 18262 was 18262, checked in by Henrik Bettermann, 7 months ago

Customize attendance sheet.

  • Property svn:keywords set to Id
File size: 29.8 KB
RevLine 
[7419]1## $Id: utils.py 18262 2026-05-05 13:18:37Z 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##
[7151]18import grok
[9190]19import random
[18262]20import textwrap
[8599]21from time import time
[18262]22from zope.i18n import translate
[9950]23from zope.component import createObject, getUtility
[18262]24from reportlab.lib.styles import getSampleStyleSheet
25from reportlab.platypus import Paragraph, Image, Table, Spacer
[13800]26from waeup.kofa.interfaces import (
27    CLEARED, RETURNING, PAID, ADMITTED, CLEARANCE, REQUESTED)
[8834]28from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
[8247]29from waeup.kofa.accesscodes import create_accesscode
[18262]30from waeup.kofa.interfaces import CLEARED, RETURNING, academic_sessions_vocab
[8460]31from waeup.fceokene.interfaces import MessageFactory as _
[9950]32from waeup.kofa.browser.interfaces import IPDFCreator
[18262]33from waeup.kofa.students.utils import trans, CONTENT_STYLE
34from waeup.kofa.browser.pdf import (
35    ENTRY1_STYLE, format_html, NOTE_STYLE, HEADING_STYLE,
36    get_signature_tables, get_qrcode)
[6902]37
[11919]38# Very special school fee configuration, should be moved to
39# a seperate file.
40
41ARTS = ('CRS','ISS','HIS','MUS','ECO','GEO','POL','SOS','CCA','ECU',
42        'THA','GED','GSE','PES','SPC','ENG','FRE','ARB','HAU','IGB',
43        'YOR','NCRS','NISS','NHIS','NMUS','NECO','NGEO','NPOL',
44        'NCCA','NECU','NTHA','NGED','NGSE','NPES','NSPC','NENG',
45        'NFRE','NARB','NHAU','NIGB','NYOR','NSOS')
46
[15594]47GATEWAY_AMT = 0.0
[15283]48
[8834]49class CustomStudentsUtils(NigeriaStudentsUtils):
[7151]50    """A collection of customized methods.
51
52    """
53
[15706]54    def selectBed(self, available_beds):
[13459]55        """Randomly select a bed from the list of available beds.
[9190]56        """
57        return random.choice(available_beds)
58
[8270]59    def getReturningData(self, student):
60        """ This method defines what happens after school fee payment
[8319]61        of returning students depending on the student's senate verdict.
[8270]62        """
[8319]63        prev_level = student['studycourse'].current_level
64        cur_verdict = student['studycourse'].current_verdict
65        if cur_verdict in ('A','B','L','M','N','Z',):
66            # Successful student
67            new_level = divmod(int(prev_level),100)[0]*100 + 100
[9923]68        elif cur_verdict in ('C','O'):
[8319]69            # Student on probation
70            new_level = int(prev_level) + 10
71        else:
72            # Student is somehow in an undefined state.
73            # Level has to be set manually.
74            new_level = prev_level
[9923]75        if cur_verdict == 'O':
76            new_session = student['studycourse'].current_session
77        else:
78            new_session = student['studycourse'].current_session + 1
[8270]79        return new_session, new_level
80
[16899]81    #def _nce3PaymentMade(self, student, p_level):
82    #    if len(student['payments']):
83    #        for ticket in student['payments'].values():
84    #            if ticket.p_state in ('paid', 'scholarship', 'waived') and \
85    #                ticket.p_level == p_level and \
86    #                ticket.p_category == 'schoolfee':
87    #                return True
88    #    return False
[16008]89
[9153]90    def setPaymentDetails(self, category, student,
[15678]91            previous_session=None, previous_level=None, combi=[]):
[8599]92        """Create Payment object and set the payment data of a student for
93        the payment category specified.
94
95        """
[8306]96        details = {}
[8599]97        p_item = u''
98        amount = 0.0
99        error = u''
[9153]100        if previous_session:
101            return _('Previous session payment not yet implemented.'), None
[8599]102        p_session = student['studycourse'].current_session
103        p_level = student['studycourse'].current_level
[9153]104        p_current = True
[9525]105        academic_session = self._getSessionConfiguration(p_session)
106        if academic_session == None:
[8599]107            return _(u'Session configuration object is not available.'), None
[9525]108        # Determine fee.
[7151]109        if category == 'transfer':
[8599]110            amount = academic_session.transfer_fee
[7151]111        elif category == 'gown':
[8599]112            amount = academic_session.gown_fee
[7151]113        elif category == 'bed_allocation':
[17183]114            acco_details = self.getAccommodationDetails(student)
115            p_session = acco_details['booking_session']
116            p_item = acco_details['bt']
[8599]117            amount = academic_session.booking_fee
[7151]118        elif category == 'hostel_maintenance':
[17183]119            amount = 0.0
120            booking_session = grok.getSite()['hostels'].accommodation_session
121            bedticket = student['accommodation'].get(str(booking_session), None)
[9611]122            if bedticket is not None and bedticket.bed is not None:
[17183]123                p_session = booking_session
[9611]124                p_item = bedticket.bed_coordinates
[17629]125                if bedticket.bed.__parent__.maint_fee > 0:
126                    amount = bedticket.bed.__parent__.maint_fee
127                #if student['studycourse'].current_session < 2022:
128                #    amount = 6100.0
129                #else:
130                #    amount = 10090.0
[9611]131            else:
[13616]132                return _(u'No bed space allocated.'), None
133            if student.current_mode.endswith('_sw') \
134                or student.current_mode == 'pd_ft':
135                amount *= 0.625
[7151]136        elif category == 'clearance':
[9143]137            amount = academic_session.clearance_fee
[8599]138            try:
139                p_item = student['studycourse'].certificate.code
140            except (AttributeError, TypeError):
141                return _('Study course data are incomplete.'), None
[13800]142            if student.state not in (ADMITTED, CLEARANCE, REQUESTED, CLEARED):
143                return _(u'Acceptance Fee payments not allowed.'), None
[16899]144        #elif category == 'third_semester' and student.current_mode == 'nce_ft' \
145        #    and p_level in (300, 310, 320, 400, 410, 420):
146        #    #if not self._nce3PaymentMade(student, p_level):
147        #    #    return _(u'Make NCE 3 school fee payment first.'), None
148        #    no_additional_courses = 0
149        #    courses_level = student['studycourse'].get(str(p_level))
150        #    if courses_level and len(courses_level)> 6:
151        #        no_additional_courses = len(courses_level)-6
152        #        amount = 2000.0 * no_additional_courses
[18057]153        elif category == 'reg2sandwich':
154            amount = 40000.0
[16461]155        elif category.startswith('schoolfee'):
[17493]156            increment_2022 = 0
[16461]157            if category == 'schoolfee_pde1':
[16462]158                if not student.current_mode.startswith('pd'):
159                    return _('You are not a PDE student.'), None
[16461]160                if student.state != CLEARED:
161                        return _('You are not a fresh student.'), None
[17734]162            if category == 'schoolfee_ug_new':
163                if not student.current_mode.startswith('ug'):
164                    return _('You are not a UG student.'), None
165                if student.state != CLEARED:
166                        return _('You are not a fresh student.'), None
167            if category == 'schoolfee_ug_ret':
168                if not student.current_mode.startswith('ug'):
169                    return _('You are not a UG student.'), None
170                if student.state != RETURNING:
171                        return _('You are not a returning student.'), None
[16899]172            if category == 'schoolfee_third':
173                if not student.current_mode == 'nce_ft' \
174                    or not p_level in (300, 310, 320, 400, 410, 420):
175                    return _('You are not an NCE 3 student.'), None
[12602]176            p_item =  student.certcode
177            if not p_item:
[8599]178                return _('Study course data are incomplete.'), None
[10012]179            if student.state not in (CLEARED, RETURNING):
180                return _('Wrong state.'), None
[10661]181            # PDE repeater
182            if student.current_verdict == 'OPDE':
[18052]183                amount = 30000
[13274]184            # PDE new
185            elif student.current_mode == 'pd_ft' and student.state == CLEARED:
[18052]186                amount = 90000
[16461]187                if category == 'schoolfee_pde1':
188                    amount = 40000
[10660]189            # PDE
190            elif student.current_mode == 'pd_ft':
[13275]191                amount = 35300
[12602]192
193            #Short Duration ICT Programs
194            elif p_item in ('CCO','DPMTS','DTPGD') and \
195                 student.state == CLEARED:
196                amount = 15000
197            elif p_item in ('ADTPGD','ADPMTS') and \
198                 student.state == CLEARED:
199                amount = 16000
200            elif p_item in ('ADPMTSI','ADTPGDI','DPMTSI','DTPGDI') and \
201                 student.state == CLEARED:
202                amount = 25000
203            elif p_item in ('ADPMTSA','ADTPGDA') and \
204               student.state == CLEARED:
205                amount = 35000
206
[18233]207            # new degree programme
208            elif student.faccode == 'SUP':
209                amount = 85500
210
[10012]211            # UG
212            elif student.current_mode == 'ug_ft':
[17734]213                if category == 'schoolfee_ug_new':
214                    # conditions checked above
[17983]215                    amount = 80000
[17734]216                elif category == 'schoolfee_ug_ret':
217                    # conditions checked above
[17983]218                    amount = 60000
[17734]219                elif student.state == CLEARED:
[17983]220                    amount = 140000
[13779]221                # Introducing repeater fee for 'ug_ft' for 1st time
222                # on 15/03/2016
[17734]223                #elif student.current_verdict == 'O':
224                #    amount = 96700
[10876]225                else:
[17983]226                    amount = 110000
227
[10012]228            # NCE
[9143]229            elif not student.current_mode.endswith('_sw'):
[17113]230                # in 2022 NCE school fees have encreased
231                increment_2022 = 11000
[9143]232                # PRENCE
233                if student.current_level == 10 and student.state == CLEARED:
234                    if student.depcode in ARTS:
[14933]235                        amount = 24500
[9143]236                    else:
[14933]237                        amount = 25000
[10012]238                # NCE I fresh
[9143]239                elif student.current_level == 100 and student.state == CLEARED:
240                    if student.depcode in ARTS:
[15283]241                        amount = 28000
[9143]242                    else:
[15283]243                        amount = 28500
[14931]244                    # SIWES Fee
[16542]245                    if student.depcode in ('AGE', 'BED', 'FAA', 'HEC', 'CSC', 'MUS') \
[17087]246                       or student.certcode in ('NCECHECSC',
247                                               'NCEBIOCSC',
248                                               'NCEPHYCSC',
249                                               'NCEPHECSC',
250                                               'NCETHAMUS',
251                                               'NCEANFMUS',
252                                               'NCEHISMUS',
253                                               'NCEIGBMUS',
254                                               'NCESPCCSC',
255                                               ):
[14931]256                        amount += 3000
[10012]257                # NCE II
[9143]258                elif student.current_level in (100, 110, 120) and \
259                    student.state == RETURNING:
260                    if student.depcode in ARTS:
[15283]261                        amount = 24500
[9143]262                    else:
[15283]263                        amount = 25000
[16899]264                # NCE III third semester
265                elif category == 'schoolfee_third':
[18052]266                    amount = 18000
[17706]267                    increment_2022 = 0
[10012]268                # NCE III
[9143]269                elif student.current_level in (200, 210, 220):
270                    if student.depcode in ARTS:
[14931]271                        amount = 15375
[9143]272                    else:
[14931]273                        amount = 15875
[17113]274                    increment_2022 = 20125
[10012]275                # NCE III repeater
[9143]276                elif student.current_level in (300, 310, 320) and \
277                    student.current_verdict == 'O':
278                    if student.depcode in ARTS:
[14931]279                        amount = 13475
[9143]280                    else:
[14931]281                        amount = 13975
[17499]282                    increment_2022 = 11000
[10012]283                # NCE III spillover
[9143]284                elif student.current_level in (300, 310, 320) and \
285                    student.current_verdict == 'B':
286                    if student.depcode in ARTS:
[14931]287                        amount = 13475
[9143]288                    else:
[14931]289                        amount = 13975
[17113]290                    increment_2022 = 20125
[10012]291                # NCE III second spillover
[9143]292                elif student.current_level in (400, 410, 420) and \
293                    student.current_verdict == 'B':
294                    if student.depcode in ARTS:
[14931]295                        amount = 13475
[9143]296                    else:
[14931]297                        amount = 13975
[17113]298                    increment_2022 = 20125
[9143]299            else:
[14265]300                # NCE I fresh sw
[9143]301                if student.current_level == 100 and student.state == CLEARED:
302                    if student.depcode in ARTS:
[14193]303                        amount = 23100
[9143]304                    else:
[14193]305                        amount = 23600
[14265]306                # NCE II fresh sw
307                elif student.current_level == 200 and student.state == CLEARED:
308                    if student.depcode in ARTS:
309                        amount = 19000
310                    else:
311                        amount = 19500
[10012]312                # NCE II sw
[9143]313                elif student.current_level in (100, 110, 120) and \
314                    student.state == RETURNING:
315                    if student.depcode in ARTS:
[11850]316                        amount = 19000
[9143]317                    else:
[11882]318                        amount = 19500
[10012]319                # NCE III sw
[9143]320                elif student.current_level in (200, 210, 220):
321                    if student.depcode in ARTS:
[11850]322                        amount = 21000
[9143]323                    else:
[14193]324                        amount = 21500
[10012]325                # NCE IV sw
[9143]326                elif student.current_level in (300, 310, 320):
327                    if student.depcode in ARTS:
[11850]328                        amount = 19000
[9143]329                    else:
[11850]330                        amount = 19500
[10012]331                # NCE V sw
[9143]332                elif student.current_level in (400, 410, 420):
333                    if student.depcode in ARTS:
[11850]334                        amount = 19000
[9143]335                    else:
[11850]336                        amount = 19500
[10012]337                # NCE V spillover sw
[9143]338                elif student.current_level in (500, 510, 520) and \
339                    student.current_verdict == 'B':
340                    if student.depcode in ARTS:
[11850]341                        amount = 17500
[9143]342                    else:
[11850]343                        amount = 18000
[10012]344                # NCE V second spillover sw
[9143]345                elif student.current_level in (600, 610, 620) and \
346                    student.current_verdict == 'B':
347                    if student.depcode in ARTS:
[16921]348                        amount = 17500
[9143]349                    else:
[16921]350                        amount = 18000
[10009]351            # NCE student payment can be disabled by
352            # setting the base school fee to -1
353            if academic_session.school_fee_base == -1 and \
354                student.current_mode.startswith('nce'):
[10010]355                return _(u'School fee payment is disabled.'), None
[9297]356            if student.state == RETURNING:
[9525]357                # Override p_session and p_level
[9297]358                p_session, p_level = self.getReturningData(student)
[9525]359                academic_session = self._getSessionConfiguration(p_session)
360                if academic_session == None:
361                    return _(u'Session configuration object is not available.'), None
[17501]362            if amount and p_session > 2021:
[17493]363                    amount += increment_2022
[17087]364        else:
365            fee_name = category + '_fee'
366            amount = getattr(academic_session, fee_name, 0.0)
367           
[8599]368        if amount in (0.0, None):
369            return _(u'Amount could not be determined.'), None
[14566]370
371        # Add session and level specific penalty fee.
[13881]372        if category == 'schoolfee' and student.current_mode in (
[14617]373            'ug_ft', 'de_ft') and student.state != CLEARED:
[13881]374            amount += academic_session.penalty_ug_ft
375        elif category == 'schoolfee' and student.current_mode in (
[14556]376            'nce_ft',) and student['studycourse'].previous_verdict != 'O':
[14566]377            # NCE I fresh
378            if student.current_level == 100 and student.state == CLEARED:
379                amount += academic_session.penalty_nce1_ft
380            # NCE II
381            elif student.current_level in (100, 110, 120) and \
382                student.state == RETURNING:
383                amount += academic_session.penalty_nce2_ft
384            # NCE III (except repeaters and spillovers)
385            elif student.current_level in (200, 210, 220):
386                amount += academic_session.penalty_nce3_ft
[14618]387        elif category == 'schoolfee' and student.current_mode in ('nce_sw',
388            'nce_pt') and student['studycourse'].previous_verdict != 'O':
[14566]389            # NCE I fresh
390            if student.current_level == 100 and student.state == CLEARED:
391                amount += academic_session.penalty_nce1_pt
392            # NCE II
393            elif student.current_level in (100, 110, 120) and \
394                student.state == RETURNING:
395                amount += academic_session.penalty_nce2_pt
396            # NCE III (except repeaters and spillovers)
397            elif student.current_level in (200, 210, 220):
398                amount += academic_session.penalty_nce3_pt
[13881]399        elif category == 'schoolfee' and student.current_mode in ('prence',):
400            amount += academic_session.penalty_prence
[11649]401        if self.samePaymentMade(student, category, p_item, p_session):
402            return _('This type of payment has already been made.'), None
[11457]403        if self._isPaymentDisabled(p_session, category, student):
[13800]404            return _('This category of payments has been disabled.'), None
[8713]405        payment = createObject(u'waeup.StudentOnlinePayment')
[8953]406        timestamp = ("%d" % int(time()*10000))[1:]
[8599]407        payment.p_id = "p%s" % timestamp
408        payment.p_category = category
409        payment.p_item = p_item
410        payment.p_session = p_session
411        payment.p_level = p_level
[9153]412        payment.p_current = p_current
[10388]413        payment.amount_auth = float(amount) + GATEWAY_AMT
[8599]414        return None, payment
[7621]415
[9207]416    def getAccommodationDetails(self, student):
417        """Determine the accommodation data of a student.
418        """
419        d = {}
420        d['error'] = u''
421        hostels = grok.getSite()['hostels']
422        d['booking_session'] = hostels.accommodation_session
423        d['allowed_states'] = hostels.accommodation_states
424        d['startdate'] = hostels.startdate
425        d['enddate'] = hostels.enddate
426        d['expired'] = hostels.expired
427        # Determine bed type
428        studycourse = student['studycourse']
429        certificate = getattr(studycourse,'certificate',None)
430        current_level = studycourse.current_level
431        if None in (current_level, certificate):
432            return d
433        end_level = certificate.end_level
434        if current_level == 10:
435            bt = 'pr'
436        elif current_level == 100:
437            bt = 'fr'
438        elif current_level >= 300:
439            bt = 'fi'
440        else:
441            bt = 're'
442        if student.sex == 'f':
443            sex = 'female'
444        else:
445            sex = 'male'
446        special_handling = 'regular'
[13614]447        if certificate.study_mode == 'ug_ft':
448            special_handling = 'ugft'
[9207]449        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
450        return d
451
[14617]452    #def warnCreditsOOR(self, studylevel, course=None):
453    #    """Return message if credits are out of range.
454    #    """
455    #    # adding a course ticket
456    #    if course:
457    #        if course.semester == 1:
458    #            if studylevel.total_credits_s1 + course.credits > 24:
459    #                return _('Maximum credits in 1st semester exceeded.')
460    #        if course.semester == 2:
461    #            if studylevel.total_credits_s2 + course.credits > 24:
462    #                return _('Maximum credits in 2nd semester exceeded.')
463    #    # registering course list
464    #    else:
465    #        if studylevel.total_credits_s1 > 24:
466    #            return _('Maximum credits in 1st semester exceeded.')
467    #        if studylevel.total_credits_s1 < 18:
468    #            return _('Minimum credits in 1st semester not reached.')
469    #        if studylevel.total_credits_s2 > 24:
470    #            return _('Maximum credits in 2nd semester exceeded.')
471    #        if studylevel.total_credits_s2 < 18:
472    #            return _('Minimum credits in 2nd semester not reached.')
473    #    return
474
[14586]475    def warnCreditsOOR(self, studylevel, course=None):
[14591]476        """Return message if credits are out of range.
[9903]477        """
[14591]478        # adding a course ticket
479        if course:
[14617]480            if studylevel.total_credits + course.credits > 52:
481                return _('Maximum credits exceeded.')
[14591]482        # registering course list
483        else:
[14617]484            if studylevel.total_credits > 52:
485                return _('Maximum credits exceeded.')
[14618]486            if studylevel.__parent__.previous_verdict == 'O':
487                return
[14591]488            if studylevel.total_credits_s1 < 18:
489                return _('Minimum credits in 1st semester not reached.')
490            if studylevel.total_credits_s2 < 18:
491                return _('Minimum credits in 2nd semester not reached.')
[14586]492        return
[9903]493
[9950]494    def getPDFCreator(self, context):
495        """Get a pdf creator suitable for `context`.
496
497        The default implementation always returns the default creator.
498        """
499        mode = getattr(context, 'current_mode', None)
[18234]500        faccode = getattr(context, 'faccode', None)
501        if (mode and faccode) and mode.startswith('ug') and faccode != 'SUP':
[9950]502            return getUtility(IPDFCreator, name='ibadan_pdfcreator')
503        return getUtility(IPDFCreator)
504
[9982]505    def _admissionText(self, student, portal_language):
[18227]506        if student.current_mode.startswith('ug') and student.faccode != 'SUP':
[9982]507            text = trans(_(
[17576]508                'With reference to your application for admission into '
509                'Bachelor Degree Programme of the University of Ibadan, '
[18228]510                'you have been provisionally admitted into Federal College '
511                'of Education Okene as follows: '),
[9982]512                portal_language)
[18227]513        #elif student.current_mode.startswith('ug'):
514        #    text = trans(_(
515        #        'With reference to your application for admission into '
516        #        'Bachelor Degree Programme, '
517        #        'you have been provisionally admitted to a full-time '
518        #        'Bachelor of Arts in Education Degree Programme as follows: '),
519        #        portal_language)
[9982]520        else:
521            inst_name = grok.getSite()['configuration'].name
522            text = trans(_(
[17576]523                'You have been provisionally admitted into Federal College '
524                'of Education Okene as follows: '
[17577]525                ),
[9982]526                portal_language)
527        return text
528
[9989]529    def getBedCoordinates(self, bedticket):
530        """Return bed coordinates.
531
532        Bed coordinates are invisible in FCEOkene.
533        """
534        return _('(see payment slip)')
535
[13030]536    def _isPaymentDisabled(self, p_session, category, student):
537        academic_session = self._getSessionConfiguration(p_session)
538        if category == 'schoolfee':
539            if 'sf_all' in academic_session.payment_disabled:
540                return True
541            if 'sf_nce1' in academic_session.payment_disabled and \
542                student.current_level == 100 and student.state == CLEARED and \
543                student.current_mode == 'nce_ft':
544                return True
[16554]545        if category == 'clearance':
546            if 'cl_except_ug' in academic_session.payment_disabled and \
547                student.current_mode != 'ug_ft':
548                return True
[13030]549        return False
550
[10019]551    SEPARATORS_DICT = {
552        'form.fst_sit_fname': _(u'First Sitting Record'),
553        'form.scd_sit_fname': _(u'Second Sitting Record'),
554        #'form.alr_fname': _(u'Advanced Level Record'),
555        'form.hq_type': _(u'Advanced Level Record'),
556        'form.hq2_type': _(u'Second Higher Education Record'),
557        'form.nysc_year': _(u'NYSC Information'),
558        'form.employer': _(u'Employment History'),
559        'form.former_matric': _(u'Former Student'),
560        }
561
[10023]562    SKIP_UPLOAD_VIEWLETS = (
563        'higherqualificationresultupload',
564        'secondHigherqualificationresultupload',
565        'certificateupload',
566        'secondcertificateupload',
567        'thirdcertificateupload',
568        'resultstatementupload',
569        'secondrefereeletterupload',
570        'thirdrefereeletterupload',)
571
[17178]572    ACCOMMODATION_SPAN = 1
573
[8460]574    # FCEOkene prefix
[10520]575    STUDENT_ID_PREFIX = u'K'
[18262]576
577    def renderPDFCourseticketsOverview(
578            self, view, name, session, data, lecturers, orientation,
579            title_length, note,
580            signatures=(),
581            sigs_in_footer=(),):
582        """Render pdf slip of course tickets for a lecturer.
583        """
584        filename = '%s_%s_%s_%s.pdf' % (
585            name, view.context.code, session, view.request.principal.id)
586        try:
587            session = academic_sessions_vocab.getTerm(session).title
588        except LookupError:
589            session = _('void')
590        creator = getUtility(IPDFCreator, name=orientation)
591        style = getSampleStyleSheet()
592        pdf_data = []
593        pdf_data += [Paragraph(
594            translate(_('<b>Lecturer(s): ${a}</b>',
595                      mapping = {'a':lecturers})), style["Normal"]),]
596        pdf_data += [Paragraph(
597            translate(_('<br /><b>Department: ${a}</b>',
598                      mapping = {'a':view.context.__parent__.__parent__.longtitle})), style["Normal"]),]
599        pdf_data += [Paragraph(
600            translate(_('<br /><b>Credits: ${a}</b>',
601                      mapping = {'a':view.context.credits})), style["Normal"]),]
602        pdf_data += [Paragraph(
603            translate(_('<br /><b>Venue:</b>')), style["Normal"]),]
604        pdf_data += [Paragraph(
605            translate(_('<br /><b>Time:</b>')), style["Normal"]),]
606        # Not used in base package. Requested by AAUE.
607        if data[1]:
608            pdf_data += [Paragraph(
609                translate(_('<b>${a}</b>',
610                    mapping = {'a':data[1][0]})), style["Normal"]),]
611            pdf_data += [Paragraph(
612                translate(_('<b>${a}</b>',
613                    mapping = {'a':data[1][1]})), style["Normal"]),]
614            pdf_data += [Paragraph(
615                translate(_('<b>Total Students: ${a}</b>',
616                    mapping = {'a':data[1][2]})), style["Normal"]),]
617            pdf_data += [Paragraph(
618                translate(_('<b>Total Pass: ${a} (${b}%)</b>',
619                mapping = {'a':data[1][3],'b':data[1][4]})), style["Normal"]),]
620            pdf_data += [Paragraph(
621                translate(_('<b>Total Fail: ${a} (${b}%)</b>',
622                mapping = {'a':data[1][5],'b':data[1][6]})), style["Normal"]),]
623            grade_stats = []
624            for item in sorted(data[1][7].items()):
625                grade_stats.append(('%s=%s' % (item[0], item[1])))
626            grade_stats_string = ', '.join(grade_stats)
627            pdf_data += [Paragraph(
628                translate(_('<b>${a}</b>',
629                mapping = {'a':grade_stats_string})), style["Normal"]),]
630        pdf_data.append(Spacer(1, 20))
631        colWidths = [None] * len(data[0][0])
632        pdf_data += [Table(data[0], colWidths=colWidths, style=CONTENT_STYLE,
633                           repeatRows=1)]
634        # Process title if too long
635        title = " ".join(view.context.title.split())
636        ct = textwrap.fill(title, title_length)
637        ft = "" # title
638        #if len(textwrap.wrap(title, title_length)) > 1:
639        #    ft = textwrap.wrap(title, title_length)[0] + ' ...'
640        doc_title = translate(_('${a} (${b})\nAcademic Session ${d}',
641            mapping = {'a':ct,
642                       'b':view.context.code,
643                       'd':session}))
644        if name == 'attendance':
645            doc_title += '\n' + translate(_('Attendance Sheet'))
646        if name == 'coursetickets':
647            doc_title += '\n' + translate(_('Course Tickets Overview'))
648        if name == 'marksheet':
649            # requested by Uniben
650            dt = view.context.__parent__.__parent__.longtitle
651            #doc_title = '%s\n%s (%s)\nMid-Semester Continuous Assessment\nAcademic Session %s' % (dt, ct, view.context.code, session)
652            doc_title = '%s\n%s (%s)\nAcademic Session %s' % (dt, ct, view.context.code, session)
653        #footer_title = translate(_('${a} (${b}) - ${d}',
654        #    mapping = {'a':ft,
655        #               'b':view.context.code,
656        #               'd':session}))
657        footer_title = translate(_('${b} - ${d}',
658            mapping = {'b':view.context.code,
659                       'd':session}))
660        author = '%s (%s)' % (view.request.principal.title,
661                              view.request.principal.id)
662
663        # Insert signatures
664        # XXX: Not used in waeup.kofa, so we
665        # do not have a test for the following lines.
666        if signatures and not sigs_in_footer:
667            pdf_data.append(Spacer(1, 20))
668            # Render one signature table per signature to
669            # get date and signature in line.
670            for signature in signatures:
671                signaturetables = get_signature_tables(signature)
672                pdf_data.append(signaturetables[0])
673
674        view.response.setHeader(
675            'Content-Type', 'application/pdf')
676        view.response.setHeader(
677            'Content-Disposition:', 'attachment; filename="%s' % filename)
678        pdf_stream = creator.create_pdf(
679            pdf_data, None, doc_title, author, footer_title + ' -', note,
680            sigs_in_footer=sigs_in_footer,
681            )
682        return pdf_stream
Note: See TracBrowser for help on using the repository browser.