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

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

Customize samePaymentMade.

  • Property svn:keywords set to Id
File size: 20.4 KB
RevLine 
[7419]1## $Id: utils.py 15320 2019-02-04 12:15:59Z 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'
127            if student.faccode in ('MED', 'DEN'):
128                special_handling = 'clinical'
129            elif student.certcode in ('BARTMAS', 'BARTTHR', 'BARTFAA',
130                                      'BAEDFAA', 'BSCEDECHED'):
131                special_handling = 'ekenwan'
[13295]132        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
133        return d
134
[9520]135    def _paymentMade(self, student, session):
136        if len(student['payments']):
137            for ticket in student['payments'].values():
138                if ticket.p_state == 'paid' and \
139                    ticket.p_category == 'schoolfee' and \
140                    ticket.p_session == session:
141                    return True
142        return False
143
[13566]144    def _isPaymentDisabled(self, p_session, category, student):
145        academic_session = self._getSessionConfiguration(p_session)
[14688]146        if category == 'schoolfee':
147            if 'sf_all' in academic_session.payment_disabled:
148                return True
149            if student.current_mode == 'found' and \
150                'sf_found' in academic_session.payment_disabled:
151                return True
152            if student.is_postgrad:
153                if 'sf_pg' in academic_session.payment_disabled:
154                    return True
155                return False
156            if student.current_mode.endswith('ft') and \
157                'sf_ft' in academic_session.payment_disabled:
158                return True
159            if student.current_mode.endswith('pt') and \
160                'sf_pt' in academic_session.payment_disabled:
161                return True
162            if student.current_mode.startswith('dp') and \
163                'sf_dp' in academic_session.payment_disabled:
164                return True
165            if student.current_mode.endswith('sw') and \
166                'sf_sw' in academic_session.payment_disabled:
167                return True
[13566]168        if category == 'hostel_maintenance' and \
169            'maint_all' in academic_session.payment_disabled:
170            return True
171        return False
172
[13251]173    #def _hostelApplicationPaymentMade(self, student, session):
174    #    if len(student['payments']):
175    #        for ticket in student['payments'].values():
176    #            if ticket.p_state == 'paid' and \
177    #                ticket.p_category == 'hostel_application' and \
178    #                ticket.p_session == session:
179    #                return True
180    #    return False
[12566]181
[14960]182    def _pharmdInstallments(self, student):
183        installments = 0.0
184        if len(student['payments']):
185            for ticket in student['payments'].values():
186                if ticket.p_state == 'paid' and \
187                    ticket.p_category.startswith('pharmd') and \
188                    ticket.p_session == student.current_session:
189                    installments += ticket.amount_auth
190        return installments
191
[15320]192    def samePaymentMade(self, student, category, p_item, p_session):
193        if category == 'bed_allocation':
194            return False
195        for key in student['payments'].keys():
196            ticket = student['payments'][key]
197            if ticket.p_state == 'paid' and\
198               ticket.p_category == category and \
199               ticket.p_item == p_item and \
200               ticket.p_session == p_session:
201                  return True
202        return False
203
[9152]204    def setPaymentDetails(self, category, student,
205            previous_session, previous_level):
[8598]206        """Create Payment object and set the payment data of a student for
207        the payment category specified.
208
209        """
210        p_item = u''
211        amount = 0.0
[9152]212        if previous_session:
[9520]213            if previous_session < student['studycourse'].entry_session:
214                return _('The previous session must not fall below '
215                         'your entry session.'), None
216            if category == 'schoolfee':
217                # School fee is always paid for the following session
218                if previous_session > student['studycourse'].current_session:
219                    return _('This is not a previous session.'), None
220            else:
221                if previous_session > student['studycourse'].current_session - 1:
222                    return _('This is not a previous session.'), None
[9152]223            p_session = previous_session
224            p_level = previous_level
225            p_current = False
226        else:
227            p_session = student['studycourse'].current_session
228            p_level = student['studycourse'].current_level
229            p_current = True
[9520]230        academic_session = self._getSessionConfiguration(p_session)
231        if academic_session == None:
[8598]232            return _(u'Session configuration object is not available.'), None
[8676]233        # Determine fee.
[7151]234        if category == 'transfer':
[8598]235            amount = academic_session.transfer_fee
[10469]236        elif category == 'transcript':
237            amount = academic_session.transcript_fee
[7151]238        elif category == 'gown':
[8598]239            amount = academic_session.gown_fee
[13785]240        elif category == 'jupeb':
241            amount = academic_session.jupeb_fee
[14358]242        elif category == 'clinexam':
243            amount = academic_session.clinexam_fee
[14960]244        elif category.startswith('pharmd') \
245            and student.current_mode == 'special_ft':
246            amount = 80000.0
[15108]247        #elif category == 'develop' and student.is_postgrad:
248        #    amount = academic_session.development_fee
[13251]249        elif category == 'bed_allocation':
250            p_item = self.getAccommodationDetails(student)['bt']
[15268]251            desired_hostel = student['accommodation'].desired_hostel
[15314]252            if not desired_hostel:
253                return _(u'Select your favoured hostel first.'), None
254            if desired_hostel and desired_hostel != 'no':
[15268]255                p_item = u'%s (%s)' % (p_item, desired_hostel)
[13251]256            amount = academic_session.booking_fee
[15002]257            if student.is_postgrad:
258                amount += 500
[13251]259        elif category == 'hostel_maintenance':
260            amount = 0.0
261            bedticket = student['accommodation'].get(
262                str(student.current_session), None)
[13500]263            if bedticket is not None and bedticket.bed is not None:
[13251]264                p_item = bedticket.bed_coordinates
265                if bedticket.bed.__parent__.maint_fee > 0:
266                    amount = bedticket.bed.__parent__.maint_fee
267                else:
268                    # fallback
269                    amount = academic_session.maint_fee
270            else:
[13508]271                return _(u'No bed allocated.'), None
[13251]272        #elif category == 'hostel_application':
273        #    amount = 1000.0
274        #elif category.startswith('tempmaint'):
275        #    if not self._hostelApplicationPaymentMade(
276        #        student, student.current_session):
277        #        return _(
278        #            'You have not yet paid the hostel application fee.'), None
279        #    if category == 'tempmaint_1':
280        #        amount = 8150.0
281        #    elif category == 'tempmaint_2':
282        #        amount = 12650.0
283        #    elif category == 'tempmaint_3':
284        #        amount = 9650.0
[7151]285        elif category == 'clearance':
[9796]286            p_item = student.certcode
287            if p_item is None:
[8598]288                return _('Study course data are incomplete.'), None
[14902]289            if student.is_jupeb:
[14897]290                amount = 50000.0
291            elif student.faccode.startswith('FCETA'):
[13869]292                # ASABA and AKOKA
[14932]293                amount = 35000.0
[11479]294            elif p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
[14289]295                'MBBSMED', 'MBBSNDU', 'BSCPTY'):
[14897]296                amount = 80000.0
[11479]297            else:
[14897]298                amount = 60000.0
[7151]299        elif category == 'schoolfee':
[8598]300            try:
301                certificate = student['studycourse'].certificate
302                p_item = certificate.code
303            except (AttributeError, TypeError):
304                return _('Study course data are incomplete.'), None
[9152]305            if previous_session:
[9520]306                # Students can pay for previous sessions in all workflow states.
307                # Fresh students are excluded by the update method of the
308                # PreviousPaymentAddFormPage.
[9157]309                if previous_session == student['studycourse'].entry_session:
[9152]310                    if student.is_foreigner:
311                        amount = getattr(certificate, 'school_fee_3', 0.0)
312                    else:
313                        amount = getattr(certificate, 'school_fee_1', 0.0)
[9006]314                else:
[9152]315                    if student.is_foreigner:
316                        amount = getattr(certificate, 'school_fee_4', 0.0)
317                    else:
318                        amount = getattr(certificate, 'school_fee_2', 0.0)
[14904]319                        # Old returning students might get a discount.
[15094]320                        if student.entry_session < 2017 \
321                            and certificate.custom_float_1:
322                            amount -= certificate.custom_float_1
[9152]323            else:
324                if student.state == CLEARED:
325                    if student.is_foreigner:
326                        amount = getattr(certificate, 'school_fee_3', 0.0)
327                    else:
328                        amount = getattr(certificate, 'school_fee_1', 0.0)
[14858]329                elif student.state == PAID and student.is_postgrad:
[9513]330                    p_session += 1
[9520]331                    academic_session = self._getSessionConfiguration(p_session)
332                    if academic_session == None:
[9513]333                        return _(u'Session configuration object is not available.'), None
[9570]334
[9520]335                    # Students are only allowed to pay for the next session
336                    # if current session payment
337                    # has really been made, i.e. payment object exists.
[9570]338                    #if not self._paymentMade(
339                    #    student, student.current_session):
340                    #    return _('You have not yet paid your current/active' +
341                    #             ' session. Please use the previous session' +
342                    #             ' payment form first.'), None
343
[9513]344                    if student.is_foreigner:
345                        amount = getattr(certificate, 'school_fee_4', 0.0)
346                    else:
347                        amount = getattr(certificate, 'school_fee_2', 0.0)
[9152]348                elif student.state == RETURNING:
349                    # In case of returning school fee payment the payment session
350                    # and level contain the values of the session the student
351                    # has paid for.
352                    p_session, p_level = self.getReturningData(student)
[9520]353                    academic_session = self._getSessionConfiguration(p_session)
354                    if academic_session == None:
[9152]355                        return _(u'Session configuration object is not available.'), None
[9570]356
[9520]357                    # Students are only allowed to pay for the next session
358                    # if current session payment has really been made,
359                    # i.e. payment object exists and is paid.
[9570]360                    #if not self._paymentMade(
361                    #    student, student.current_session):
362                    #    return _('You have not yet paid your current/active' +
363                    #             ' session. Please use the previous session' +
364                    #             ' payment form first.'), None
365
[9152]366                    if student.is_foreigner:
367                        amount = getattr(certificate, 'school_fee_4', 0.0)
368                    else:
369                        amount = getattr(certificate, 'school_fee_2', 0.0)
[14893]370                        # Old returning students might get a discount.
[14892]371                        if student.entry_session < 2017 \
[14893]372                            and certificate.custom_float_1:
373                            amount -= certificate.custom_float_1
[14960]374                # PHARMD school fee amount is fixed and previously paid
375                # installments in current session are deducted.
376                if student.current_mode == 'special_ft':
[14970]377                    amount = 160000.0 - self._pharmdInstallments(student)
[9006]378            # Give 50% school fee discount to staff members.
379            if student.is_staff:
380                amount /= 2
[8598]381        if amount in (0.0, None):
[9520]382            return _('Amount could not be determined.'), None
[8676]383        # Add session specific penalty fee.
384        if category == 'schoolfee' and student.is_postgrad:
385            amount += academic_session.penalty_pg
[15108]386            amount += academic_session.development_fee
[13757]387        elif category == 'schoolfee' and student.current_mode == ('ug_ft'):
[13756]388            amount += academic_session.penalty_ug_ft
[13757]389        elif category == 'schoolfee' and student.current_mode == ('ug_pt'):
[13756]390            amount += academic_session.penalty_ug_pt
[13998]391        elif category == 'schoolfee' and student.current_mode == ('ug_sw'):
392            amount += academic_session.penalty_sw
[14717]393        elif category == 'schoolfee' and student.current_mode in (
394            'dp_ft', 'dp_pt'):
395            amount += academic_session.penalty_dp
[9727]396        if category.startswith('tempmaint'):
397            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
398            p_item = unicode(p_item)
399            # Now we change the category because tempmaint payments
[12566]400            # will be obsolete when Uniben returns to Kofa bed allocation.
[9727]401            category = 'hostel_maintenance'
[8676]402        # Create ticket.
[15320]403        if self.samePaymentMade(student, category, p_item, p_session):
[11644]404            return _('This type of payment has already been made.'), None
[11459]405        if self._isPaymentDisabled(p_session, category, student):
[13814]406            return _('This category of payments has been disabled.'), None
[8715]407        payment = createObject(u'waeup.StudentOnlinePayment')
[8950]408        timestamp = ("%d" % int(time()*10000))[1:]
[8598]409        payment.p_id = "p%s" % timestamp
410        payment.p_category = category
411        payment.p_item = p_item
412        payment.p_session = p_session
413        payment.p_level = p_level
[9152]414        payment.p_current = p_current
[8598]415        payment.amount_auth = amount
416        return None, payment
[7621]417
[14588]418    def warnCreditsOOR(self, studylevel, course=None):
[9831]419        studycourse = studylevel.__parent__
420        certificate = getattr(studycourse,'certificate', None)
421        current_level = studycourse.current_level
422        if None in (current_level, certificate):
[14588]423            return
[9831]424        end_level = certificate.end_level
425        if current_level >= end_level:
[14588]426            limit = 51
427        else:
428            limit = 50
429        if course and studylevel.total_credits + course.credits > limit:
430            return _('Maximum credits exceeded.')
431        elif studylevel.total_credits > limit:
432            return _('Maximum credits exceeded.')
433        return
[9831]434
[11773]435    def clearance_disabled_message(self, student):
436        if student.is_postgrad:
437            return None
438        try:
439            session_config = grok.getSite()[
440                'configuration'][str(student.current_session)]
441        except KeyError:
442            return _('Session configuration object is not available.')
443        if not session_config.clearance_enabled:
444            return _('Clearance is disabled for this session.')
445        return None
446
[14038]447    #: A tuple containing the names of registration states in which changing of
448    #: passport pictures is allowed.
449    PORTRAIT_CHANGE_STATES = ()
450
[8441]451    # Uniben prefix
[8413]452    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.