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

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

Add BSCPST to high clearance fee list.

  • Property svn:keywords set to Id
File size: 20.4 KB
Line 
1## $Id: utils.py 15341 2019-03-06 08:29:04Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18import grok
19from time import time
20from zope.component import createObject, getUtility
21from waeup.kofa.interfaces import (IKofaUtils,
22    CLEARED, RETURNING, PAID, REGISTERED, VALIDATED)
23from waeup.kofa.utils.helpers import to_timezone
24from waeup.kofa.students.utils import trans
25from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
26from waeup.uniben.interfaces import MessageFactory as _
27
28class CustomStudentsUtils(NigeriaStudentsUtils):
29    """A collection of customized methods.
30
31    """
32
33    def getReturningData(self, student):
34        """ This method defines what happens after school fee payment
35        of returning students depending on the student's senate verdict.
36        """
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
49        new_session = student['studycourse'].current_session + 1
50        return new_session, new_level
51
52
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.")
67        if not student.is_postgrad and student.current_mode != 'ug_ft':
68            return _("Only undergraduate full-time students are eligible to book accommodation.")
69        bt = acc_details.get('bt')
70        if not bt:
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.')
78        stage = bt.split('_')[2]
79        if not student.is_postgrad and stage != 'fr' and not student[
80            'studycourse'].previous_verdict in (
81                'A', 'B', 'F', 'J', 'M', 'C', 'Z'):
82            return _("Your are not eligible to book accommodation.")
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:
87            return _('You already booked a bed space in '
88                     'current accommodation session.')
89        return
90
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'
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'
132        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
133        return d
134
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
144    def _isPaymentDisabled(self, p_session, category, student):
145        academic_session = self._getSessionConfiguration(p_session)
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
168        if category == 'hostel_maintenance' and \
169            'maint_all' in academic_session.payment_disabled:
170            return True
171        return False
172
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
181
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
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
204    def setPaymentDetails(self, category, student,
205            previous_session, previous_level):
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
212        if previous_session:
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
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
230        academic_session = self._getSessionConfiguration(p_session)
231        if academic_session == None:
232            return _(u'Session configuration object is not available.'), None
233        # Determine fee.
234        if category == 'transfer':
235            amount = academic_session.transfer_fee
236        elif category == 'transcript':
237            amount = academic_session.transcript_fee
238        elif category == 'gown':
239            amount = academic_session.gown_fee
240        elif category == 'jupeb':
241            amount = academic_session.jupeb_fee
242        elif category == 'clinexam':
243            amount = academic_session.clinexam_fee
244        elif category.startswith('pharmd') \
245            and student.current_mode == 'special_ft':
246            amount = 80000.0
247        #elif category == 'develop' and student.is_postgrad:
248        #    amount = academic_session.development_fee
249        elif category == 'bed_allocation':
250            p_item = self.getAccommodationDetails(student)['bt']
251            desired_hostel = student['accommodation'].desired_hostel
252            if not desired_hostel:
253                return _(u'Select your favoured hostel first.'), None
254            if desired_hostel and desired_hostel != 'no':
255                p_item = u'%s (%s)' % (p_item, desired_hostel)
256            amount = academic_session.booking_fee
257            if student.is_postgrad:
258                amount += 500
259        elif category == 'hostel_maintenance':
260            amount = 0.0
261            bedticket = student['accommodation'].get(
262                str(student.current_session), None)
263            if bedticket is not None and bedticket.bed is not None:
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:
271                return _(u'No bed allocated.'), None
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
285        elif category == 'clearance':
286            p_item = student.certcode
287            if p_item is None:
288                return _('Study course data are incomplete.'), None
289            if student.is_jupeb:
290                amount = 50000.0
291            elif student.faccode.startswith('FCETA'):
292                # ASABA and AKOKA
293                amount = 35000.0
294            elif p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
295                'MBBSMED', 'MBBSNDU', 'BSCPTY', 'BSCPST'):
296                amount = 80000.0
297            else:
298                amount = 60000.0
299        elif category == 'schoolfee':
300            try:
301                certificate = student['studycourse'].certificate
302                p_item = certificate.code
303            except (AttributeError, TypeError):
304                return _('Study course data are incomplete.'), None
305            if previous_session:
306                # Students can pay for previous sessions in all workflow states.
307                # Fresh students are excluded by the update method of the
308                # PreviousPaymentAddFormPage.
309                if previous_session == student['studycourse'].entry_session:
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)
314                else:
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)
319                        # Old returning students might get a discount.
320                        if student.entry_session < 2017 \
321                            and certificate.custom_float_1:
322                            amount -= certificate.custom_float_1
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)
329                elif student.state == PAID and student.is_postgrad:
330                    p_session += 1
331                    academic_session = self._getSessionConfiguration(p_session)
332                    if academic_session == None:
333                        return _(u'Session configuration object is not available.'), None
334
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.
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
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)
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)
353                    academic_session = self._getSessionConfiguration(p_session)
354                    if academic_session == None:
355                        return _(u'Session configuration object is not available.'), None
356
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.
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
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)
370                        # Old returning students might get a discount.
371                        if student.entry_session < 2017 \
372                            and certificate.custom_float_1:
373                            amount -= certificate.custom_float_1
374                # PHARMD school fee amount is fixed and previously paid
375                # installments in current session are deducted.
376                if student.current_mode == 'special_ft':
377                    amount = 160000.0 - self._pharmdInstallments(student)
378            # Give 50% school fee discount to staff members.
379            if student.is_staff:
380                amount /= 2
381        if amount in (0.0, None):
382            return _('Amount could not be determined.'), None
383        # Add session specific penalty fee.
384        if category == 'schoolfee' and student.is_postgrad:
385            amount += academic_session.penalty_pg
386            amount += academic_session.development_fee
387        elif category == 'schoolfee' and student.current_mode == ('ug_ft'):
388            amount += academic_session.penalty_ug_ft
389        elif category == 'schoolfee' and student.current_mode == ('ug_pt'):
390            amount += academic_session.penalty_ug_pt
391        elif category == 'schoolfee' and student.current_mode == ('ug_sw'):
392            amount += academic_session.penalty_sw
393        elif category == 'schoolfee' and student.current_mode in (
394            'dp_ft', 'dp_pt'):
395            amount += academic_session.penalty_dp
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
400            # will be obsolete when Uniben returns to Kofa bed allocation.
401            category = 'hostel_maintenance'
402        # Create ticket.
403        if self.samePaymentMade(student, category, p_item, p_session):
404            return _('This type of payment has already been made.'), None
405        if self._isPaymentDisabled(p_session, category, student):
406            return _('This category of payments has been disabled.'), None
407        payment = createObject(u'waeup.StudentOnlinePayment')
408        timestamp = ("%d" % int(time()*10000))[1:]
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
414        payment.p_current = p_current
415        payment.amount_auth = amount
416        return None, payment
417
418    def warnCreditsOOR(self, studylevel, course=None):
419        studycourse = studylevel.__parent__
420        certificate = getattr(studycourse,'certificate', None)
421        current_level = studycourse.current_level
422        if None in (current_level, certificate):
423            return
424        end_level = certificate.end_level
425        if current_level >= end_level:
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
434
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
447    #: A tuple containing the names of registration states in which changing of
448    #: passport pictures is allowed.
449    PORTRAIT_CHANGE_STATES = ()
450
451    # Uniben prefix
452    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.