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

Last change on this file since 15369 was 15363, checked in by Henrik Bettermann, 6 years ago

Improve configuration of special_ft school fee payments. Distinguish foreign and local students.

  • Property svn:keywords set to Id
File size: 20.8 KB
RevLine 
[7419]1## $Id: utils.py 15363 2019-03-22 11:39:47Z 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
[8598]19from time import time
[9459]20from zope.component import createObject, getUtility
[9513]21from waeup.kofa.interfaces import (IKofaUtils,
22    CLEARED, RETURNING, PAID, REGISTERED, VALIDATED)
[13251]23from waeup.kofa.utils.helpers import to_timezone
24from waeup.kofa.students.utils import trans
[8821]25from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
[8020]26from waeup.uniben.interfaces import MessageFactory as _
[6902]27
[8821]28class CustomStudentsUtils(NigeriaStudentsUtils):
[7151]29    """A collection of customized methods.
30
31    """
32
[8270]33    def getReturningData(self, student):
34        """ This method defines what happens after school fee payment
[8319]35        of returning students depending on the student's senate verdict.
[8270]36        """
[8319]37        prev_level = student['studycourse'].current_level
38        cur_verdict = student['studycourse'].current_verdict
39        if cur_verdict in ('A','B','L','M','N','Z',):
40            # Successful student
41            new_level = divmod(int(prev_level),100)[0]*100 + 100
42        elif cur_verdict == 'C':
43            # Student on probation
44            new_level = int(prev_level) + 10
45        else:
46            # Student is somehow in an undefined state.
47            # Level has to be set manually.
48            new_level = prev_level
[8270]49        new_session = student['studycourse'].current_session + 1
50        return new_session, new_level
51
[13251]52
[13248]53    def checkAccommodationRequirements(self, student, acc_details):
54        if acc_details.get('expired', False):
55            startdate = acc_details.get('startdate')
56            enddate = acc_details.get('enddate')
57            if startdate and enddate:
58                tz = getUtility(IKofaUtils).tzinfo
59                startdate = to_timezone(
60                    startdate, tz).strftime("%d/%m/%Y %H:%M:%S")
61                enddate = to_timezone(
62                    enddate, tz).strftime("%d/%m/%Y %H:%M:%S")
63                return _("Outside booking period: ${a} - ${b}",
64                         mapping = {'a': startdate, 'b': enddate})
65            else:
66                return _("Outside booking period.")
[13777]67        if not student.is_postgrad and student.current_mode != 'ug_ft':
[13446]68            return _("Only undergraduate full-time students are eligible to book accommodation.")
[13283]69        bt = acc_details.get('bt')
70        if not bt:
[13248]71            return _("Your data are incomplete.")
72        if not student.state in acc_details['allowed_states']:
73            return _("You are in the wrong registration state.")
74        if student['studycourse'].current_session != acc_details[
75            'booking_session']:
76            return _('Your current session does not '
77                     'match accommodation session.')
[13283]78        stage = bt.split('_')[2]
[13777]79        if not student.is_postgrad and stage != 'fr' and not student[
[14328]80            'studycourse'].previous_verdict in (
[14343]81                'A', 'B', 'F', 'J', 'M', 'C', 'Z'):
[13283]82            return _("Your are not eligible to book accommodation.")
[15307]83        bsession = str(acc_details['booking_session'])
84        if bsession in student['accommodation'].keys() \
85            and not 'booking expired' in \
86            student['accommodation'][bsession].bed_coordinates:
[13248]87            return _('You already booked a bed space in '
88                     'current accommodation session.')
89        return
[13244]90
[13295]91    def getAccommodationDetails(self, student):
92        """Determine the accommodation data of a student.
93        """
94        d = {}
95        d['error'] = u''
96        hostels = grok.getSite()['hostels']
97        d['booking_session'] = hostels.accommodation_session
98        d['allowed_states'] = hostels.accommodation_states
99        d['startdate'] = hostels.startdate
100        d['enddate'] = hostels.enddate
101        d['expired'] = hostels.expired
102        # Determine bed type
103        studycourse = student['studycourse']
104        certificate = getattr(studycourse,'certificate',None)
105        entry_session = studycourse.entry_session
106        current_level = studycourse.current_level
107        if None in (entry_session, current_level, certificate):
108            return d
109        if student.sex == 'f':
110            sex = 'female'
111        else:
112            sex = 'male'
[13777]113        if student.is_postgrad:
114            bt = 'all'
115            special_handling = 'pg'
116        else:
117            end_level = certificate.end_level
118            if current_level == 10:
119                bt = 'pr'
120            elif entry_session == grok.getSite()['hostels'].accommodation_session:
121                bt = 'fr'
122            elif current_level >= end_level:
123                bt = 'fi'
124            else:
125                bt = 're'
126            special_handling = 'regular'
[15354]127            desired_hostel = student['accommodation'].desired_hostel
128            if student.faccode in ('MED', 'DEN') and (
129                not desired_hostel or desired_hostel.startswith('clinical')):
[13777]130                special_handling = 'clinical'
131            elif student.certcode in ('BARTMAS', 'BARTTHR', 'BARTFAA',
132                                      'BAEDFAA', 'BSCEDECHED'):
133                special_handling = 'ekenwan'
[13295]134        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
135        return d
136
[9520]137    def _paymentMade(self, student, session):
138        if len(student['payments']):
139            for ticket in student['payments'].values():
140                if ticket.p_state == 'paid' and \
141                    ticket.p_category == 'schoolfee' and \
142                    ticket.p_session == session:
143                    return True
144        return False
145
[13566]146    def _isPaymentDisabled(self, p_session, category, student):
147        academic_session = self._getSessionConfiguration(p_session)
[14688]148        if category == 'schoolfee':
149            if 'sf_all' in academic_session.payment_disabled:
150                return True
151            if student.current_mode == 'found' and \
152                'sf_found' in academic_session.payment_disabled:
153                return True
154            if student.is_postgrad:
155                if 'sf_pg' in academic_session.payment_disabled:
156                    return True
157                return False
158            if student.current_mode.endswith('ft') and \
159                'sf_ft' in academic_session.payment_disabled:
160                return True
161            if student.current_mode.endswith('pt') and \
162                'sf_pt' in academic_session.payment_disabled:
163                return True
164            if student.current_mode.startswith('dp') and \
165                'sf_dp' in academic_session.payment_disabled:
166                return True
167            if student.current_mode.endswith('sw') and \
168                'sf_sw' in academic_session.payment_disabled:
169                return True
[13566]170        if category == 'hostel_maintenance' and \
171            'maint_all' in academic_session.payment_disabled:
172            return True
173        return False
174
[13251]175    #def _hostelApplicationPaymentMade(self, student, session):
176    #    if len(student['payments']):
177    #        for ticket in student['payments'].values():
178    #            if ticket.p_state == 'paid' and \
179    #                ticket.p_category == 'hostel_application' and \
180    #                ticket.p_session == session:
181    #                return True
182    #    return False
[12566]183
[14960]184    def _pharmdInstallments(self, student):
185        installments = 0.0
186        if len(student['payments']):
187            for ticket in student['payments'].values():
188                if ticket.p_state == 'paid' and \
189                    ticket.p_category.startswith('pharmd') and \
190                    ticket.p_session == student.current_session:
191                    installments += ticket.amount_auth
192        return installments
193
[15320]194    def samePaymentMade(self, student, category, p_item, p_session):
195        if category == 'bed_allocation':
196            return False
197        for key in student['payments'].keys():
198            ticket = student['payments'][key]
199            if ticket.p_state == 'paid' and\
200               ticket.p_category == category and \
201               ticket.p_item == p_item and \
202               ticket.p_session == p_session:
203                  return True
204        return False
205
[9152]206    def setPaymentDetails(self, category, student,
207            previous_session, previous_level):
[8598]208        """Create Payment object and set the payment data of a student for
209        the payment category specified.
210
211        """
212        p_item = u''
213        amount = 0.0
[9152]214        if previous_session:
[9520]215            if previous_session < student['studycourse'].entry_session:
216                return _('The previous session must not fall below '
217                         'your entry session.'), None
218            if category == 'schoolfee':
219                # School fee is always paid for the following session
220                if previous_session > student['studycourse'].current_session:
221                    return _('This is not a previous session.'), None
222            else:
223                if previous_session > student['studycourse'].current_session - 1:
224                    return _('This is not a previous session.'), None
[9152]225            p_session = previous_session
226            p_level = previous_level
227            p_current = False
228        else:
229            p_session = student['studycourse'].current_session
230            p_level = student['studycourse'].current_level
231            p_current = True
[9520]232        academic_session = self._getSessionConfiguration(p_session)
233        if academic_session == None:
[8598]234            return _(u'Session configuration object is not available.'), None
[8676]235        # Determine fee.
[7151]236        if category == 'transfer':
[8598]237            amount = academic_session.transfer_fee
[10469]238        elif category == 'transcript':
239            amount = academic_session.transcript_fee
[7151]240        elif category == 'gown':
[8598]241            amount = academic_session.gown_fee
[13785]242        elif category == 'jupeb':
243            amount = academic_session.jupeb_fee
[14358]244        elif category == 'clinexam':
245            amount = academic_session.clinexam_fee
[14960]246        elif category.startswith('pharmd') \
247            and student.current_mode == 'special_ft':
248            amount = 80000.0
[15108]249        #elif category == 'develop' and student.is_postgrad:
250        #    amount = academic_session.development_fee
[13251]251        elif category == 'bed_allocation':
252            p_item = self.getAccommodationDetails(student)['bt']
[15268]253            desired_hostel = student['accommodation'].desired_hostel
[15314]254            if not desired_hostel:
255                return _(u'Select your favoured hostel first.'), None
256            if desired_hostel and desired_hostel != 'no':
[15268]257                p_item = u'%s (%s)' % (p_item, desired_hostel)
[13251]258            amount = academic_session.booking_fee
[15002]259            if student.is_postgrad:
260                amount += 500
[13251]261        elif category == 'hostel_maintenance':
262            amount = 0.0
263            bedticket = student['accommodation'].get(
264                str(student.current_session), None)
[13500]265            if bedticket is not None and bedticket.bed is not None:
[13251]266                p_item = bedticket.bed_coordinates
267                if bedticket.bed.__parent__.maint_fee > 0:
268                    amount = bedticket.bed.__parent__.maint_fee
269                else:
270                    # fallback
271                    amount = academic_session.maint_fee
272            else:
[13508]273                return _(u'No bed allocated.'), None
[13251]274        #elif category == 'hostel_application':
275        #    amount = 1000.0
276        #elif category.startswith('tempmaint'):
277        #    if not self._hostelApplicationPaymentMade(
278        #        student, student.current_session):
279        #        return _(
280        #            'You have not yet paid the hostel application fee.'), None
281        #    if category == 'tempmaint_1':
282        #        amount = 8150.0
283        #    elif category == 'tempmaint_2':
284        #        amount = 12650.0
285        #    elif category == 'tempmaint_3':
286        #        amount = 9650.0
[7151]287        elif category == 'clearance':
[9796]288            p_item = student.certcode
289            if p_item is None:
[8598]290                return _('Study course data are incomplete.'), None
[14902]291            if student.is_jupeb:
[14897]292                amount = 50000.0
293            elif student.faccode.startswith('FCETA'):
[13869]294                # ASABA and AKOKA
[14932]295                amount = 35000.0
[15342]296            elif student.faccode == 'BMS':
297            #elif p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
298            #    'MBBSMED', 'MBBSNDU', 'BSCPTY', 'BSCPST'):
[14897]299                amount = 80000.0
[11479]300            else:
[14897]301                amount = 60000.0
[7151]302        elif category == 'schoolfee':
[8598]303            try:
304                certificate = student['studycourse'].certificate
305                p_item = certificate.code
306            except (AttributeError, TypeError):
307                return _('Study course data are incomplete.'), None
[9152]308            if previous_session:
[9520]309                # Students can pay for previous sessions in all workflow states.
310                # Fresh students are excluded by the update method of the
311                # PreviousPaymentAddFormPage.
[9157]312                if previous_session == student['studycourse'].entry_session:
[9152]313                    if student.is_foreigner:
314                        amount = getattr(certificate, 'school_fee_3', 0.0)
315                    else:
316                        amount = getattr(certificate, 'school_fee_1', 0.0)
[9006]317                else:
[9152]318                    if student.is_foreigner:
319                        amount = getattr(certificate, 'school_fee_4', 0.0)
320                    else:
321                        amount = getattr(certificate, 'school_fee_2', 0.0)
[14904]322                        # Old returning students might get a discount.
[15094]323                        if student.entry_session < 2017 \
324                            and certificate.custom_float_1:
325                            amount -= certificate.custom_float_1
[9152]326            else:
327                if student.state == CLEARED:
328                    if student.is_foreigner:
329                        amount = getattr(certificate, 'school_fee_3', 0.0)
330                    else:
331                        amount = getattr(certificate, 'school_fee_1', 0.0)
[14858]332                elif student.state == PAID and student.is_postgrad:
[9513]333                    p_session += 1
[9520]334                    academic_session = self._getSessionConfiguration(p_session)
335                    if academic_session == None:
[9513]336                        return _(u'Session configuration object is not available.'), None
[9570]337
[9520]338                    # Students are only allowed to pay for the next session
339                    # if current session payment
340                    # has really been made, i.e. payment object exists.
[9570]341                    #if not self._paymentMade(
342                    #    student, student.current_session):
343                    #    return _('You have not yet paid your current/active' +
344                    #             ' session. Please use the previous session' +
345                    #             ' payment form first.'), None
346
[9513]347                    if student.is_foreigner:
348                        amount = getattr(certificate, 'school_fee_4', 0.0)
349                    else:
350                        amount = getattr(certificate, 'school_fee_2', 0.0)
[9152]351                elif student.state == RETURNING:
352                    # In case of returning school fee payment the payment session
353                    # and level contain the values of the session the student
354                    # has paid for.
355                    p_session, p_level = self.getReturningData(student)
[9520]356                    academic_session = self._getSessionConfiguration(p_session)
357                    if academic_session == None:
[9152]358                        return _(u'Session configuration object is not available.'), None
[9570]359
[9520]360                    # Students are only allowed to pay for the next session
361                    # if current session payment has really been made,
362                    # i.e. payment object exists and is paid.
[9570]363                    #if not self._paymentMade(
364                    #    student, student.current_session):
365                    #    return _('You have not yet paid your current/active' +
366                    #             ' session. Please use the previous session' +
367                    #             ' payment form first.'), None
368
[9152]369                    if student.is_foreigner:
370                        amount = getattr(certificate, 'school_fee_4', 0.0)
371                    else:
372                        amount = getattr(certificate, 'school_fee_2', 0.0)
[14893]373                        # Old returning students might get a discount.
[14892]374                        if student.entry_session < 2017 \
[14893]375                            and certificate.custom_float_1:
376                            amount -= certificate.custom_float_1
[14960]377                # PHARMD school fee amount is fixed and previously paid
378                # installments in current session are deducted.
[15363]379                if student.current_mode == 'special_ft' \
380                    and student.state in (RETURNING, CLEARED):
381                    if student.is_foreigner:
382                        amount = 260000.0 - self._pharmdInstallments(student)
383                    else:
384                        amount = 160000.0 - self._pharmdInstallments(student)
[9006]385            # Give 50% school fee discount to staff members.
386            if student.is_staff:
387                amount /= 2
[8598]388        if amount in (0.0, None):
[9520]389            return _('Amount could not be determined.'), None
[8676]390        # Add session specific penalty fee.
391        if category == 'schoolfee' and student.is_postgrad:
392            amount += academic_session.penalty_pg
[15108]393            amount += academic_session.development_fee
[13757]394        elif category == 'schoolfee' and student.current_mode == ('ug_ft'):
[13756]395            amount += academic_session.penalty_ug_ft
[13757]396        elif category == 'schoolfee' and student.current_mode == ('ug_pt'):
[13756]397            amount += academic_session.penalty_ug_pt
[13998]398        elif category == 'schoolfee' and student.current_mode == ('ug_sw'):
399            amount += academic_session.penalty_sw
[14717]400        elif category == 'schoolfee' and student.current_mode in (
401            'dp_ft', 'dp_pt'):
402            amount += academic_session.penalty_dp
[9727]403        if category.startswith('tempmaint'):
404            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
405            p_item = unicode(p_item)
406            # Now we change the category because tempmaint payments
[12566]407            # will be obsolete when Uniben returns to Kofa bed allocation.
[9727]408            category = 'hostel_maintenance'
[8676]409        # Create ticket.
[15320]410        if self.samePaymentMade(student, category, p_item, p_session):
[11644]411            return _('This type of payment has already been made.'), None
[11459]412        if self._isPaymentDisabled(p_session, category, student):
[13814]413            return _('This category of payments has been disabled.'), None
[8715]414        payment = createObject(u'waeup.StudentOnlinePayment')
[8950]415        timestamp = ("%d" % int(time()*10000))[1:]
[8598]416        payment.p_id = "p%s" % timestamp
417        payment.p_category = category
418        payment.p_item = p_item
419        payment.p_session = p_session
420        payment.p_level = p_level
[9152]421        payment.p_current = p_current
[8598]422        payment.amount_auth = amount
423        return None, payment
[7621]424
[14588]425    def warnCreditsOOR(self, studylevel, course=None):
[9831]426        studycourse = studylevel.__parent__
427        certificate = getattr(studycourse,'certificate', None)
428        current_level = studycourse.current_level
429        if None in (current_level, certificate):
[14588]430            return
[9831]431        end_level = certificate.end_level
432        if current_level >= end_level:
[14588]433            limit = 51
434        else:
435            limit = 50
436        if course and studylevel.total_credits + course.credits > limit:
437            return _('Maximum credits exceeded.')
438        elif studylevel.total_credits > limit:
439            return _('Maximum credits exceeded.')
440        return
[9831]441
[11773]442    def clearance_disabled_message(self, student):
443        if student.is_postgrad:
444            return None
445        try:
446            session_config = grok.getSite()[
447                'configuration'][str(student.current_session)]
448        except KeyError:
449            return _('Session configuration object is not available.')
450        if not session_config.clearance_enabled:
451            return _('Clearance is disabled for this session.')
452        return None
453
[14038]454    #: A tuple containing the names of registration states in which changing of
455    #: passport pictures is allowed.
456    PORTRAIT_CHANGE_STATES = ()
457
[8441]458    # Uniben prefix
[8413]459    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.