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

Last change on this file since 17627 was 17606, checked in by Henrik Bettermann, 13 months ago

Define setCDLPaymentDetails.

  • Property svn:keywords set to Id
File size: 36.8 KB
RevLine 
[7419]1## $Id: utils.py 17606 2023-10-10 16:52:33Z 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##
[11773]18import grok
[17457]19import os
20import csv
[8598]21from time import time
[16108]22from reportlab.platypus import Paragraph, Table
[9459]23from zope.component import createObject, getUtility
[16106]24from reportlab.lib.styles import getSampleStyleSheet
[16108]25from waeup.kofa.browser.pdf import ENTRY1_STYLE
[16359]26from waeup.kofa.interfaces import (IKofaUtils, ADMITTED, CLEARANCE,
[16445]27    CLEARED, REQUESTED, RETURNING, PAID, REGISTERED, VALIDATED, GRADUATED)
[13251]28from waeup.kofa.utils.helpers import to_timezone
[16108]29from waeup.kofa.students.utils import (
30    trans, render_student_data, formatted_text, render_transcript_data,
31    SLIP_STYLE)
[8821]32from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
[8020]33from waeup.uniben.interfaces import MessageFactory as _
[6902]34
[17457]35SCHOOLFEES = dict()
36
37schoolfees_path = os.path.join(
38    os.path.dirname(__file__), 'schoolfees_22.csv')
39reader = csv.DictReader(open(schoolfees_path, 'rb'))
40SCHOOLFEES[22] = {line['code']: {item[0]:item[1] for item in line.items()}
41    for line in reader}
42
43
44schoolfees_path = os.path.join(
45    os.path.dirname(__file__), 'schoolfees_20.csv')
46reader = csv.DictReader(open(schoolfees_path, 'rb'))
47SCHOOLFEES[20] = {line['code']: {item[0]:item[1] for item in line.items()}
48    for line in reader}
49
50
51schoolfees_path = os.path.join(
52    os.path.dirname(__file__), 'schoolfees_17.csv')
53reader = csv.DictReader(open(schoolfees_path, 'rb'))
54SCHOOLFEES[17] = {line['code']: {item[0]:item[1] for item in line.items()}
55    for line in reader}
56
57schoolfees_path = os.path.join(
58    os.path.dirname(__file__), 'schoolfees_12.csv')
59reader = csv.DictReader(open(schoolfees_path, 'rb'))
60SCHOOLFEES[12] = {line['code']: {item[0]:item[1] for item in line.items()}
61    for line in reader}
62
[8821]63class CustomStudentsUtils(NigeriaStudentsUtils):
[7151]64    """A collection of customized methods.
65
66    """
67
[16382]68    SEPARATORS_DICT = {
69        'form.fst_sit_fname': _(u'First Sitting Record'),
70        'form.scd_sit_fname': _(u'Second Sitting Record'),
71        'form.alr_fname': _(u'Advanced Level Record'),
72        'form.hq_type': _(u'Higher Education Record'),
73        'form.hq2_type': _(u'Second Higher Education Record'),
74        'form.nysc_year': _(u'NYSC Information'),
75        'form.employer': _(u'Employment History'),
76        'form.former_matric': _(u'Former Student'),
77        'form.fever': _(u'History of Symptoms'),
78        'form.asthma': _(u'Medical History'),
79        'form.lagos_abuja': _(u'Travel History'),
80        'form.company_suspected': _(u'History of Contact/Infection'),
[17255]81        'form.genotype': _(u'TISHIP Registration Form Data'),
[16382]82        }
83
[8270]84    def getReturningData(self, student):
85        """ This method defines what happens after school fee payment
[8319]86        of returning students depending on the student's senate verdict.
[8270]87        """
[8319]88        prev_level = student['studycourse'].current_level
89        cur_verdict = student['studycourse'].current_verdict
[16714]90        if cur_verdict == 'N' and prev_level in (100, 200):
[15482]91            new_level = prev_level
[17536]92        elif cur_verdict in ('A','B','M','N','Z',):
[8319]93            # Successful student
94            new_level = divmod(int(prev_level),100)[0]*100 + 100
[17536]95        elif cur_verdict in ('C', 'L',):
[8319]96            # Student on probation
97            new_level = int(prev_level) + 10
98        else:
99            # Student is somehow in an undefined state.
100            # Level has to be set manually.
101            new_level = prev_level
[8270]102        new_session = student['studycourse'].current_session + 1
103        return new_session, new_level
104
[13251]105
[13248]106    def checkAccommodationRequirements(self, student, acc_details):
107        if acc_details.get('expired', False):
108            startdate = acc_details.get('startdate')
109            enddate = acc_details.get('enddate')
110            if startdate and enddate:
111                tz = getUtility(IKofaUtils).tzinfo
112                startdate = to_timezone(
113                    startdate, tz).strftime("%d/%m/%Y %H:%M:%S")
114                enddate = to_timezone(
115                    enddate, tz).strftime("%d/%m/%Y %H:%M:%S")
116                return _("Outside booking period: ${a} - ${b}",
117                         mapping = {'a': startdate, 'b': enddate})
118            else:
119                return _("Outside booking period.")
[13777]120        if not student.is_postgrad and student.current_mode != 'ug_ft':
[13446]121            return _("Only undergraduate full-time students are eligible to book accommodation.")
[13283]122        bt = acc_details.get('bt')
123        if not bt:
[13248]124            return _("Your data are incomplete.")
125        if not student.state in acc_details['allowed_states']:
126            return _("You are in the wrong registration state.")
[17255]127        #if student['studycourse'].current_session != acc_details[
128        #    'booking_session']:
129        #    return _('Your current session does not '
130        #             'match accommodation session.')
131        if  acc_details['booking_session'] - student[
132            'studycourse'].current_session > self.ACCOMMODATION_SPAN:
133            return _('Your current session does not allow ' + \
134                    'to book accommodation.')
[13283]135        stage = bt.split('_')[2]
[13777]136        if not student.is_postgrad and stage != 'fr' and not student[
[14328]137            'studycourse'].previous_verdict in (
[15392]138                'A', 'B', 'F', 'J', 'L', 'M', 'C', 'Z'):
[13283]139            return _("Your are not eligible to book accommodation.")
[15307]140        bsession = str(acc_details['booking_session'])
141        if bsession in student['accommodation'].keys() \
142            and not 'booking expired' in \
143            student['accommodation'][bsession].bed_coordinates:
[13248]144            return _('You already booked a bed space in '
145                     'current accommodation session.')
146        return
[13244]147
[13295]148    def getAccommodationDetails(self, student):
149        """Determine the accommodation data of a student.
150        """
151        d = {}
152        d['error'] = u''
153        hostels = grok.getSite()['hostels']
154        d['booking_session'] = hostels.accommodation_session
155        d['allowed_states'] = hostels.accommodation_states
156        d['startdate'] = hostels.startdate
157        d['enddate'] = hostels.enddate
158        d['expired'] = hostels.expired
159        # Determine bed type
160        studycourse = student['studycourse']
161        certificate = getattr(studycourse,'certificate',None)
162        entry_session = studycourse.entry_session
163        current_level = studycourse.current_level
164        if None in (entry_session, current_level, certificate):
165            return d
166        if student.sex == 'f':
167            sex = 'female'
168        else:
169            sex = 'male'
[13777]170        if student.is_postgrad:
171            bt = 'all'
172            special_handling = 'pg'
173        else:
174            end_level = certificate.end_level
175            if current_level == 10:
176                bt = 'pr'
177            elif entry_session == grok.getSite()['hostels'].accommodation_session:
178                bt = 'fr'
179            elif current_level >= end_level:
180                bt = 'fi'
181            else:
182                bt = 're'
183            special_handling = 'regular'
[15354]184            desired_hostel = student['accommodation'].desired_hostel
185            if student.faccode in ('MED', 'DEN') and (
186                not desired_hostel or desired_hostel.startswith('clinical')):
[13777]187                special_handling = 'clinical'
188            elif student.certcode in ('BARTMAS', 'BARTTHR', 'BARTFAA',
[17324]189                                      'BAEDFAA', 'BSCEDECHED', 'BAFAA',
[17603]190                                      'BARTMUS', 'BSCEDECHED', 'BEDECHEDU'):
[13777]191                special_handling = 'ekenwan'
[13295]192        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
193        return d
194
[9520]195    def _paymentMade(self, student, session):
196        if len(student['payments']):
197            for ticket in student['payments'].values():
198                if ticket.p_state == 'paid' and \
199                    ticket.p_category == 'schoolfee' and \
200                    ticket.p_session == session:
201                    return True
202        return False
203
[13566]204    def _isPaymentDisabled(self, p_session, category, student):
205        academic_session = self._getSessionConfiguration(p_session)
[14688]206        if category == 'schoolfee':
207            if 'sf_all' in academic_session.payment_disabled:
208                return True
[16516]209            if student.state == RETURNING and \
210                'sf_return' in academic_session.payment_disabled:
211                return True
[14688]212            if student.current_mode == 'found' and \
213                'sf_found' in academic_session.payment_disabled:
214                return True
215            if student.is_postgrad:
216                if 'sf_pg' in academic_session.payment_disabled:
217                    return True
218                return False
219            if student.current_mode.endswith('ft') and \
220                'sf_ft' in academic_session.payment_disabled:
221                return True
222            if student.current_mode.endswith('pt') and \
223                'sf_pt' in academic_session.payment_disabled:
224                return True
225            if student.current_mode.startswith('dp') and \
226                'sf_dp' in academic_session.payment_disabled:
227                return True
228            if student.current_mode.endswith('sw') and \
229                'sf_sw' in academic_session.payment_disabled:
230                return True
[13566]231        if category == 'hostel_maintenance' and \
232            'maint_all' in academic_session.payment_disabled:
233            return True
[16025]234        if category == 'clearance':
235            if 'cl_all' in academic_session.payment_disabled:
236                return True
237            if student.is_jupeb and \
238                'cl_jupeb' in academic_session.payment_disabled:
239                return True
[16374]240            if not student.is_jupeb and \
241                'cl_allexj' in academic_session.payment_disabled:
242                return True
[13566]243        return False
244
[13251]245    #def _hostelApplicationPaymentMade(self, student, session):
246    #    if len(student['payments']):
247    #        for ticket in student['payments'].values():
248    #            if ticket.p_state == 'paid' and \
249    #                ticket.p_category == 'hostel_application' and \
250    #                ticket.p_session == session:
251    #                return True
252    #    return False
[12566]253
[14960]254    def _pharmdInstallments(self, student):
255        installments = 0.0
256        if len(student['payments']):
257            for ticket in student['payments'].values():
258                if ticket.p_state == 'paid' and \
259                    ticket.p_category.startswith('pharmd') and \
260                    ticket.p_session == student.current_session:
261                    installments += ticket.amount_auth
262        return installments
263
[15320]264    def samePaymentMade(self, student, category, p_item, p_session):
[15447]265        if category in ('bed_allocation', 'transcript'):
[15320]266            return False
267        for key in student['payments'].keys():
268            ticket = student['payments'][key]
269            if ticket.p_state == 'paid' and\
270               ticket.p_category == category and \
271               ticket.p_item == p_item and \
272               ticket.p_session == p_session:
273                  return True
274        return False
275
[17606]276    def setCDLPaymentDetails(self, category, student,
277            previous_session, previous_level, combi):
278        """Create Payment object and set the payment data of a CDL student for
279        the payment category specified.
280        """
281        p_item = u''
282        amount = 0.0
283        if previous_session:
284            if previous_session < student['studycourse'].entry_session:
285                return _('The previous session must not fall below '
286                         'your entry session.'), None
287            if category == 'schoolfee':
288                # School fee is always paid for the following session
289                if previous_session > student['studycourse'].current_session:
290                    return _('This is not a previous session.'), None
291            else:
292                if previous_session > student['studycourse'].current_session - 1:
293                    return _('This is not a previous session.'), None
294            p_session = previous_session
295            p_level = previous_level
296            p_current = False
297        else:
298            p_session = student['studycourse'].current_session
299            p_level = student['studycourse'].current_level
300            p_current = True
301        academic_session = self._getSessionConfiguration(p_session)
302        if academic_session == None:
303            return _(u'Session configuration object is not available.'), None
304        # Determine fee.
305        if category == 'schoolfee':
306            try:
307                certificate = student['studycourse'].certificate
308                p_item = certificate.code
309            except (AttributeError, TypeError):
310                return _('Study course data are incomplete.'), None
311            if previous_session:
312                # Students can pay for previous sessions in all
313                # workflow states.  Fresh students are excluded by the
314                # update method of the PreviousPaymentAddFormPage.
315                if previous_level == 100:
316                    amount = getattr(certificate, 'school_fee_1', 0.0)
317                else:
318                    amount = getattr(certificate, 'school_fee_2', 0.0)
319            else:
320                if student.state == CLEARED:
321                    amount = getattr(certificate, 'school_fee_1', 0.0)
322                elif student.state == RETURNING:
323                    # In case of returning school fee payment the
324                    # payment session and level contain the values of
325                    # the session the student has paid for. Payment
326                    # session is always next session.
327                    p_session, p_level = self.getReturningData(student)
328                    academic_session = self._getSessionConfiguration(p_session)
329                    if academic_session == None:
330                        return _(
331                            u'Session configuration object is not available.'
332                            ), None
333                    amount = getattr(certificate, 'school_fee_2', 0.0)
334                elif student.is_postgrad and student.state == PAID:
335                    # Returning postgraduate students also pay for the
336                    # next session but their level always remains the
337                    # same.
338                    p_session += 1
339                    academic_session = self._getSessionConfiguration(p_session)
340                    if academic_session == None:
341                        return _(
342                            u'Session configuration object is not available.'
343                            ), None
344                    amount = getattr(certificate, 'school_fee_2', 0.0)
345        elif category == 'clearance':
346            try:
347                p_item = student['studycourse'].certificate.code
348            except (AttributeError, TypeError):
349                return _('Study course data are incomplete.'), None
350            amount = academic_session.clearance_fee
351        elif category == 'combi' and combi:
352            categories = getUtility(IKofaUtils).COMBI_PAYMENT_CATEGORIES
353            for cat in combi:
354                fee_name = cat + '_fee'
355                cat_amount = getattr(academic_session, fee_name, 0.0)
356                if not cat_amount:
357                    return _('%s undefined.' % categories[cat]), None
358                amount += cat_amount
359                p_item += u'%s + ' % categories[cat]
360            p_item = p_item.strip(' + ')
361        else:
362            fee_name = category + '_fee'
363            amount = getattr(academic_session, fee_name, 0.0)
364        if amount in (0.0, None):
365            return _('Amount could not be determined.'), None
366        if self.samePaymentMade(student, category, p_item, p_session):
367            return _('This type of payment has already been made.'), None
368        if self._isPaymentDisabled(p_session, category, student):
369            return _('This category of payments has been disabled.'), None
370        payment = createObject(u'waeup.StudentOnlinePayment')
371        timestamp = ("%d" % int(time()*10000))[1:]
372        payment.p_id = "p%s" % timestamp
373        payment.p_category = category
374        payment.p_item = p_item
375        payment.p_session = p_session
376        payment.p_level = p_level
377        payment.p_current = p_current
378        payment.amount_auth = amount
379        payment.p_combi = combi
380        return None, payment
381
382
[9152]383    def setPaymentDetails(self, category, student,
[15666]384            previous_session, previous_level, combi):
[8598]385        """Create Payment object and set the payment data of a student for
386        the payment category specified.
387
388        """
[17606]389        if grok.getSite().__name__ == 'uniben-cdl':
390            return self.setCDLPaymentDetails(category, student,
391                previous_session, previous_level, combi)
[8598]392        p_item = u''
393        amount = 0.0
[9152]394        if previous_session:
[9520]395            if previous_session < student['studycourse'].entry_session:
396                return _('The previous session must not fall below '
397                         'your entry session.'), None
398            if category == 'schoolfee':
399                # School fee is always paid for the following session
400                if previous_session > student['studycourse'].current_session:
401                    return _('This is not a previous session.'), None
402            else:
403                if previous_session > student['studycourse'].current_session - 1:
404                    return _('This is not a previous session.'), None
[9152]405            p_session = previous_session
406            p_level = previous_level
407            p_current = False
408        else:
409            p_session = student['studycourse'].current_session
410            p_level = student['studycourse'].current_level
411            p_current = True
[9520]412        academic_session = self._getSessionConfiguration(p_session)
413        if academic_session == None:
[8598]414            return _(u'Session configuration object is not available.'), None
[8676]415        # Determine fee.
[16873]416        if category.startswith('pharmd') \
[14960]417            and student.current_mode == 'special_ft':
418            amount = 80000.0
[16780]419        elif category == 'plag_test':
420            amount = 2500.0
421            if student.is_postgrad:
422                amount = 5000.0
[15108]423        #elif category == 'develop' and student.is_postgrad:
424        #    amount = academic_session.development_fee
[13251]425        elif category == 'bed_allocation':
[17236]426            acco_details = self.getAccommodationDetails(student)
427            p_session = acco_details['booking_session']
428            p_item = acco_details['bt']
[15268]429            desired_hostel = student['accommodation'].desired_hostel
[15314]430            if not desired_hostel:
431                return _(u'Select your favoured hostel first.'), None
432            if desired_hostel and desired_hostel != 'no':
[15268]433                p_item = u'%s (%s)' % (p_item, desired_hostel)
[13251]434            amount = academic_session.booking_fee
[15002]435            if student.is_postgrad:
436                amount += 500
[13251]437        elif category == 'hostel_maintenance':
438            amount = 0.0
[17236]439            booking_session = grok.getSite()['hostels'].accommodation_session
440            bedticket = student['accommodation'].get(str(booking_session), None)
[13500]441            if bedticket is not None and bedticket.bed is not None:
[13251]442                p_item = bedticket.bed_coordinates
[17236]443                p_session = booking_session
[13251]444                if bedticket.bed.__parent__.maint_fee > 0:
445                    amount = bedticket.bed.__parent__.maint_fee
446                else:
447                    # fallback
448                    amount = academic_session.maint_fee
449            else:
[13508]450                return _(u'No bed allocated.'), None
[13251]451        #elif category == 'hostel_application':
452        #    amount = 1000.0
453        #elif category.startswith('tempmaint'):
454        #    if not self._hostelApplicationPaymentMade(
455        #        student, student.current_session):
456        #        return _(
457        #            'You have not yet paid the hostel application fee.'), None
458        #    if category == 'tempmaint_1':
459        #        amount = 8150.0
460        #    elif category == 'tempmaint_2':
461        #        amount = 12650.0
462        #    elif category == 'tempmaint_3':
463        #        amount = 9650.0
[7151]464        elif category == 'clearance':
[9796]465            p_item = student.certcode
466            if p_item is None:
[8598]467                return _('Study course data are incomplete.'), None
[17606]468            if student.is_jupeb:
[14897]469                amount = 50000.0
470            elif student.faccode.startswith('FCETA'):
[13869]471                # ASABA and AKOKA
[14932]472                amount = 35000.0
[17112]473            elif student.depcode == 'DMIC':
474                amount = 70000.0
[17361]475            elif student.faccode in ('BMS', 'MED', 'DEN') \
476                and not student.is_postgrad:
[14897]477                amount = 80000.0
[15574]478            elif student.faccode == 'DCOEM':
479                return _('Acceptance fee payment not necessary.'), None
[11479]480            else:
[14897]481                amount = 60000.0
[7151]482        elif category == 'schoolfee':
[8598]483            try:
484                certificate = student['studycourse'].certificate
485                p_item = certificate.code
486            except (AttributeError, TypeError):
487                return _('Study course data are incomplete.'), None
[17457]488            try:
489                if student.entry_session < 2017:
490                    schoolfees_dict = SCHOOLFEES[12][p_item]
491                elif student.entry_session < 2020:
492                    schoolfees_dict = SCHOOLFEES[17][p_item]
493                elif student.entry_session < 2022:
494                    schoolfees_dict = SCHOOLFEES[20][p_item]
495                else:
496                    schoolfees_dict = SCHOOLFEES[22][p_item]
497            except KeyError:
498                return _('School fee not yet fixed: p_item = %s' % p_item), None
[9152]499            if previous_session:
[9520]500                # Students can pay for previous sessions in all workflow states.
501                # Fresh students are excluded by the update method of the
502                # PreviousPaymentAddFormPage.
[9157]503                if previous_session == student['studycourse'].entry_session:
[9152]504                    if student.is_foreigner:
[17457]505                        amount = schoolfees_dict['initial_foreigner']
[9152]506                    else:
[17457]507                        amount = schoolfees_dict['initial']
[9006]508                else:
[9152]509                    if student.is_foreigner:
[17457]510                        amount = schoolfees_dict['returning_foreigner']
[9152]511                    else:
[17457]512                        amount = schoolfees_dict['returning']
[9152]513            else:
514                if student.state == CLEARED:
515                    if student.is_foreigner:
[17457]516                        amount = schoolfees_dict['initial_foreigner']
[9152]517                    else:
[17457]518                        amount = schoolfees_dict['initial']
[14858]519                elif student.state == PAID and student.is_postgrad:
[9513]520                    p_session += 1
[9520]521                    academic_session = self._getSessionConfiguration(p_session)
522                    if academic_session == None:
[9513]523                        return _(u'Session configuration object is not available.'), None
524                    if student.is_foreigner:
[17457]525                        amount = schoolfees_dict['returning_foreigner']
[9513]526                    else:
[17457]527                        amount = schoolfees_dict['returning']
[9152]528                elif student.state == RETURNING:
529                    # In case of returning school fee payment the payment session
530                    # and level contain the values of the session the student
531                    # has paid for.
532                    p_session, p_level = self.getReturningData(student)
[9520]533                    academic_session = self._getSessionConfiguration(p_session)
534                    if academic_session == None:
[9152]535                        return _(u'Session configuration object is not available.'), None
[9570]536
[9520]537                    # Students are only allowed to pay for the next session
538                    # if current session payment has really been made,
539                    # i.e. payment object exists and is paid.
[9570]540                    #if not self._paymentMade(
541                    #    student, student.current_session):
542                    #    return _('You have not yet paid your current/active' +
543                    #             ' session. Please use the previous session' +
544                    #             ' payment form first.'), None
545
[9152]546                    if student.is_foreigner:
[17457]547                        amount = schoolfees_dict['returning_foreigner']
[9152]548                    else:
[17457]549                        amount = schoolfees_dict['returning']
[14960]550                # PHARMD school fee amount is fixed and previously paid
551                # installments in current session are deducted.
[15363]552                if student.current_mode == 'special_ft' \
553                    and student.state in (RETURNING, CLEARED):
554                    if student.is_foreigner:
555                        amount = 260000.0 - self._pharmdInstallments(student)
556                    else:
557                        amount = 160000.0 - self._pharmdInstallments(student)
[17457]558            try:
559                amount = float(amount)
560            except ValueError:
561                return _(u'School fee not yet fixed: p_item = %s' % p_item), None
[9006]562            # Give 50% school fee discount to staff members.
563            if student.is_staff:
564                amount /= 2
[17457]565
[16873]566        else:
567            fee_name = category + '_fee'
568            amount = getattr(academic_session, fee_name, 0.0)
[8598]569        if amount in (0.0, None):
[9520]570            return _('Amount could not be determined.'), None
[8676]571        # Add session specific penalty fee.
572        if category == 'schoolfee' and student.is_postgrad:
573            amount += academic_session.penalty_pg
[15108]574            amount += academic_session.development_fee
[13757]575        elif category == 'schoolfee' and student.current_mode == ('ug_ft'):
[13756]576            amount += academic_session.penalty_ug_ft
[13757]577        elif category == 'schoolfee' and student.current_mode == ('ug_pt'):
[13756]578            amount += academic_session.penalty_ug_pt
[13998]579        elif category == 'schoolfee' and student.current_mode == ('ug_sw'):
580            amount += academic_session.penalty_sw
[14717]581        elif category == 'schoolfee' and student.current_mode in (
582            'dp_ft', 'dp_pt'):
583            amount += academic_session.penalty_dp
[9727]584        if category.startswith('tempmaint'):
585            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
586            p_item = unicode(p_item)
587            # Now we change the category because tempmaint payments
[12566]588            # will be obsolete when Uniben returns to Kofa bed allocation.
[9727]589            category = 'hostel_maintenance'
[8676]590        # Create ticket.
[15320]591        if self.samePaymentMade(student, category, p_item, p_session):
[11644]592            return _('This type of payment has already been made.'), None
[11459]593        if self._isPaymentDisabled(p_session, category, student):
[13814]594            return _('This category of payments has been disabled.'), None
[8715]595        payment = createObject(u'waeup.StudentOnlinePayment')
[8950]596        timestamp = ("%d" % int(time()*10000))[1:]
[8598]597        payment.p_id = "p%s" % timestamp
598        payment.p_category = category
599        payment.p_item = p_item
600        payment.p_session = p_session
601        payment.p_level = p_level
[9152]602        payment.p_current = p_current
[8598]603        payment.amount_auth = amount
604        return None, payment
[7621]605
[14588]606    def warnCreditsOOR(self, studylevel, course=None):
[9831]607        studycourse = studylevel.__parent__
608        certificate = getattr(studycourse,'certificate', None)
609        current_level = studycourse.current_level
610        if None in (current_level, certificate):
[14588]611            return
[16438]612        if studylevel.__parent__.previous_verdict == 'R':
613            return
[9831]614        end_level = certificate.end_level
[15840]615        if studylevel.student.faccode in (
616            'MED', 'DEN', 'BMS') and studylevel.level == 200:
617            limit = 61
618        elif current_level >= end_level:
[14588]619            limit = 51
620        else:
621            limit = 50
622        if course and studylevel.total_credits + course.credits > limit:
623            return _('Maximum credits exceeded.')
624        elif studylevel.total_credits > limit:
625            return _('Maximum credits exceeded.')
626        return
[9831]627
[16406]628    def warnCourseAlreadyPassed(self, studylevel, course):
629        """Return message if course has already been passed at
630        previous levels.
631        """
[16413]632
633        # med: we may need to put this matter on hold and allow
634        # all the students to register.
635        return False
636
[16406]637        previous_verdict = studylevel.__parent__.previous_verdict
638        if previous_verdict in ('C', 'M'):
639            return False
640        for slevel in studylevel.__parent__.values():
641            for cticket in slevel.values():
642                if cticket.code == course.code \
643                    and cticket.total_score >= cticket.passmark:
644                    return _('Course has already been passed at previous level.')
645        return False
646
[11773]647    def clearance_disabled_message(self, student):
648        if student.is_postgrad:
649            return None
650        try:
651            session_config = grok.getSite()[
652                'configuration'][str(student.current_session)]
653        except KeyError:
654            return _('Session configuration object is not available.')
655        if not session_config.clearance_enabled:
656            return _('Clearance is disabled for this session.')
657        return None
658
[16100]659    def renderPDFTranscript(self, view, filename='transcript.pdf',
660                  student=None,
661                  studentview=None,
662                  note=None,
663                  signatures=(),
664                  sigs_in_footer=(),
665                  digital_sigs=(),
666                  show_scans=True, topMargin=1.5,
667                  omit_fields=(),
668                  tableheader=None,
669                  no_passport=False,
670                  save_file=False):
671        """Render pdf slip of a transcripts.
672        """
673        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
674        # XXX: tell what the different parameters mean
675        style = getSampleStyleSheet()
676        creator = self.getPDFCreator(student)
677        data = []
678        doc_title = view.label
679        author = '%s (%s)' % (view.request.principal.title,
680                              view.request.principal.id)
681        footer_text = view.label.split('\n')
682        if len(footer_text) > 2:
683            # We can add a department in first line
684            footer_text = footer_text[1]
685        else:
686            # Only the first line is used for the footer
687            footer_text = footer_text[0]
688        if getattr(student, 'student_id', None) is not None:
689            footer_text = "%s - %s - " % (student.student_id, footer_text)
690
691        # Insert student data table
692        if student is not None:
693            #bd_translation = trans(_('Base Data'), portal_language)
694            #data.append(Paragraph(bd_translation, HEADING_STYLE))
695            data.append(render_student_data(
696                studentview, view.context,
697                omit_fields, lang=portal_language,
698                slipname=filename,
699                no_passport=no_passport))
700
701        transcript_data = view.context.getTranscriptData()
702        levels_data = transcript_data[0]
703
704        contextdata = []
705        f_label = trans(_('Course of Study:'), portal_language)
706        f_label = Paragraph(f_label, ENTRY1_STYLE)
707        f_text = formatted_text(view.context.certificate.longtitle)
708        f_text = Paragraph(f_text, ENTRY1_STYLE)
709        contextdata.append([f_label,f_text])
710
711        f_label = trans(_('Faculty:'), portal_language)
712        f_label = Paragraph(f_label, ENTRY1_STYLE)
713        f_text = formatted_text(
714            view.context.certificate.__parent__.__parent__.__parent__.longtitle)
715        f_text = Paragraph(f_text, ENTRY1_STYLE)
716        contextdata.append([f_label,f_text])
717
718        f_label = trans(_('Department:'), portal_language)
719        f_label = Paragraph(f_label, ENTRY1_STYLE)
720        f_text = formatted_text(
721            view.context.certificate.__parent__.__parent__.longtitle)
722        f_text = Paragraph(f_text, ENTRY1_STYLE)
723        contextdata.append([f_label,f_text])
724
725        f_label = trans(_('Entry Session:'), portal_language)
726        f_label = Paragraph(f_label, ENTRY1_STYLE)
727        f_text = formatted_text(
728            view.session_dict.get(view.context.entry_session))
729        f_text = Paragraph(f_text, ENTRY1_STYLE)
730        contextdata.append([f_label,f_text])
731
732        f_label = trans(_('Final Session:'), portal_language)
733        f_label = Paragraph(f_label, ENTRY1_STYLE)
734        f_text = formatted_text(
735            view.session_dict.get(view.context.current_session))
736        f_text = Paragraph(f_text, ENTRY1_STYLE)
737        contextdata.append([f_label,f_text])
738
739        f_label = trans(_('Entry Mode:'), portal_language)
740        f_label = Paragraph(f_label, ENTRY1_STYLE)
741        f_text = formatted_text(view.studymode_dict.get(
742            view.context.entry_mode))
743        f_text = Paragraph(f_text, ENTRY1_STYLE)
744        contextdata.append([f_label,f_text])
745
746        f_label = trans(_('Final Verdict:'), portal_language)
747        f_label = Paragraph(f_label, ENTRY1_STYLE)
748        f_text = formatted_text(view.studymode_dict.get(
749            view.context.current_verdict))
750        f_text = Paragraph(f_text, ENTRY1_STYLE)
751        contextdata.append([f_label,f_text])
752
753        f_label = trans(_('Cumulative GPA:'), portal_language)
754        f_label = Paragraph(f_label, ENTRY1_STYLE)
755        format_float = getUtility(IKofaUtils).format_float
756        cgpa = format_float(transcript_data[1], 3)
757        if student.state == GRADUATED:
758            f_text = formatted_text('%s (%s)' % (
759                cgpa, self.getClassFromCGPA(transcript_data[1], student)[1]))
760        else:
761            f_text = formatted_text('%s' % cgpa)
[17498]762            if not transcript_data[1]:
763                f_text = formatted_text('No results yet!')
[16100]764        f_text = Paragraph(f_text, ENTRY1_STYLE)
765        contextdata.append([f_label,f_text])
766
767        contexttable = Table(contextdata,style=SLIP_STYLE)
768        data.append(contexttable)
769
[17498]770        if transcript_data[1]:
771            transcripttables = render_transcript_data(
772                view, tableheader, levels_data, lang=portal_language)
773            data.extend(transcripttables)
[16100]774
775        # Insert signatures
776        # XXX: We are using only sigs_in_footer in waeup.kofa, so we
777        # do not have a test for the following lines.
778        if signatures and not sigs_in_footer:
779            data.append(Spacer(1, 20))
780            # Render one signature table per signature to
781            # get date and signature in line.
782            for signature in signatures:
783                signaturetables = get_signature_tables(signature)
784                data.append(signaturetables[0])
785
786        # Insert digital signatures
787        if digital_sigs:
788            data.append(Spacer(1, 20))
789            sigs = digital_sigs.split('\n')
790            for sig in sigs:
791                data.append(Paragraph(sig, NOTE_STYLE))
792
793        view.response.setHeader(
794            'Content-Type', 'application/pdf')
795        try:
796            pdf_stream = creator.create_pdf(
797                data, None, doc_title, author=author, footer=footer_text,
[16906]798                note=note, sigs_in_footer=sigs_in_footer, topMargin=topMargin,
799                view=view)
[16100]800        except IOError:
801            view.flash(_('Error in image file.'))
802            return view.redirect(view.url(view.context))
803        if save_file:
804            self._saveTranscriptPDF(student, pdf_stream)
805            return
806        return pdf_stream
807
[14038]808    #: A tuple containing the names of registration states in which changing of
809    #: passport pictures is allowed.
[16445]810    PORTRAIT_CHANGE_STATES = (CLEARANCE, REQUESTED)
[14038]811
[16611]812    #: A tuple containing the names of registration states in which changing of
813    #: scanned signatures is allowed.
[16620]814    SIGNATURE_CHANGE_STATES = (CLEARED, RETURNING, PAID, REGISTERED, VALIDATED, )
[16611]815
[8441]816    # Uniben prefix
[17145]817    @property
818    def STUDENT_ID_PREFIX(self):
819        if grok.getSite().__name__ == 'uniben-cdl':
820            return u'C'
821        return u'B'
[15980]822
823    STUDENT_EXPORTER_NAMES = (
824            'students',
825            'studentstudycourses',
[16840]826            'studentstudycourses_1',
[15980]827            'studentstudylevels',
[16840]828            #'studentstudylevels_1',
[15980]829            'coursetickets',
[16840]830            #'coursetickets_1',
[15980]831            'studentpayments',
832            'bedtickets',
833            'trimmed',
834            'outstandingcourses',
835            'unpaidpayments',
836            'sfpaymentsoverview',
837            'sessionpaymentsoverview',
838            'studylevelsoverview',
839            'combocard',
840            'bursary',
841            'accommodationpayments',
842            'transcriptdata',
843            'trimmedpayments',
[16390]844            'medicalhistory',
[17396]845            'nysc',
[15980]846            )
Note: See TracBrowser for help on using the repository browser.