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

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

Add development fee to school fee.

  • Property svn:keywords set to Id
File size: 19.5 KB
Line 
1## $Id: utils.py 15108 2018-08-15 10:46:30Z 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        if str(acc_details[
84            'booking_session']) in student['accommodation'].keys():
85            return _('You already booked a bed space in '
86                     'current accommodation session.')
87        return
88
89    def getAccommodationDetails(self, student):
90        """Determine the accommodation data of a student.
91        """
92        d = {}
93        d['error'] = u''
94        hostels = grok.getSite()['hostels']
95        d['booking_session'] = hostels.accommodation_session
96        d['allowed_states'] = hostels.accommodation_states
97        d['startdate'] = hostels.startdate
98        d['enddate'] = hostels.enddate
99        d['expired'] = hostels.expired
100        # Determine bed type
101        studycourse = student['studycourse']
102        certificate = getattr(studycourse,'certificate',None)
103        entry_session = studycourse.entry_session
104        current_level = studycourse.current_level
105        if None in (entry_session, current_level, certificate):
106            return d
107        if student.sex == 'f':
108            sex = 'female'
109        else:
110            sex = 'male'
111        if student.is_postgrad:
112            bt = 'all'
113            special_handling = 'pg'
114        else:
115            end_level = certificate.end_level
116            if current_level == 10:
117                bt = 'pr'
118            elif entry_session == grok.getSite()['hostels'].accommodation_session:
119                bt = 'fr'
120            elif current_level >= end_level:
121                bt = 'fi'
122            else:
123                bt = 're'
124            special_handling = 'regular'
125            if student.faccode in ('MED', 'DEN'):
126                special_handling = 'clinical'
127            elif student.certcode in ('BARTMAS', 'BARTTHR', 'BARTFAA',
128                                      'BAEDFAA', 'BSCEDECHED'):
129                special_handling = 'ekenwan'
130        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
131        return d
132
133    def _paymentMade(self, student, session):
134        if len(student['payments']):
135            for ticket in student['payments'].values():
136                if ticket.p_state == 'paid' and \
137                    ticket.p_category == 'schoolfee' and \
138                    ticket.p_session == session:
139                    return True
140        return False
141
142    def _isPaymentDisabled(self, p_session, category, student):
143        academic_session = self._getSessionConfiguration(p_session)
144        if category == 'schoolfee':
145            if 'sf_all' in academic_session.payment_disabled:
146                return True
147            if student.current_mode == 'found' and \
148                'sf_found' in academic_session.payment_disabled:
149                return True
150            if student.is_postgrad:
151                if 'sf_pg' in academic_session.payment_disabled:
152                    return True
153                return False
154            if student.current_mode.endswith('ft') and \
155                'sf_ft' in academic_session.payment_disabled:
156                return True
157            if student.current_mode.endswith('pt') and \
158                'sf_pt' in academic_session.payment_disabled:
159                return True
160            if student.current_mode.startswith('dp') and \
161                'sf_dp' in academic_session.payment_disabled:
162                return True
163            if student.current_mode.endswith('sw') and \
164                'sf_sw' in academic_session.payment_disabled:
165                return True
166        if category == 'hostel_maintenance' and \
167            'maint_all' in academic_session.payment_disabled:
168            return True
169        return False
170
171    #def _hostelApplicationPaymentMade(self, student, session):
172    #    if len(student['payments']):
173    #        for ticket in student['payments'].values():
174    #            if ticket.p_state == 'paid' and \
175    #                ticket.p_category == 'hostel_application' and \
176    #                ticket.p_session == session:
177    #                return True
178    #    return False
179
180    def _pharmdInstallments(self, student):
181        installments = 0.0
182        if len(student['payments']):
183            for ticket in student['payments'].values():
184                if ticket.p_state == 'paid' and \
185                    ticket.p_category.startswith('pharmd') and \
186                    ticket.p_session == student.current_session:
187                    installments += ticket.amount_auth
188        return installments
189
190    def setPaymentDetails(self, category, student,
191            previous_session, previous_level):
192        """Create Payment object and set the payment data of a student for
193        the payment category specified.
194
195        """
196        p_item = u''
197        amount = 0.0
198        if previous_session:
199            if previous_session < student['studycourse'].entry_session:
200                return _('The previous session must not fall below '
201                         'your entry session.'), None
202            if category == 'schoolfee':
203                # School fee is always paid for the following session
204                if previous_session > student['studycourse'].current_session:
205                    return _('This is not a previous session.'), None
206            else:
207                if previous_session > student['studycourse'].current_session - 1:
208                    return _('This is not a previous session.'), None
209            p_session = previous_session
210            p_level = previous_level
211            p_current = False
212        else:
213            p_session = student['studycourse'].current_session
214            p_level = student['studycourse'].current_level
215            p_current = True
216        academic_session = self._getSessionConfiguration(p_session)
217        if academic_session == None:
218            return _(u'Session configuration object is not available.'), None
219        # Determine fee.
220        if category == 'transfer':
221            amount = academic_session.transfer_fee
222        elif category == 'transcript':
223            amount = academic_session.transcript_fee
224        elif category == 'gown':
225            amount = academic_session.gown_fee
226        elif category == 'jupeb':
227            amount = academic_session.jupeb_fee
228        elif category == 'clinexam':
229            amount = academic_session.clinexam_fee
230        elif category.startswith('pharmd') \
231            and student.current_mode == 'special_ft':
232            amount = 80000.0
233        #elif category == 'develop' and student.is_postgrad:
234        #    amount = academic_session.development_fee
235        elif category == 'bed_allocation':
236            p_item = self.getAccommodationDetails(student)['bt']
237            amount = academic_session.booking_fee
238            if student.is_postgrad:
239                amount += 500
240        elif category == 'hostel_maintenance':
241            amount = 0.0
242            bedticket = student['accommodation'].get(
243                str(student.current_session), None)
244            if bedticket is not None and bedticket.bed is not None:
245                p_item = bedticket.bed_coordinates
246                if bedticket.bed.__parent__.maint_fee > 0:
247                    amount = bedticket.bed.__parent__.maint_fee
248                else:
249                    # fallback
250                    amount = academic_session.maint_fee
251            else:
252                return _(u'No bed allocated.'), None
253        #elif category == 'hostel_application':
254        #    amount = 1000.0
255        #elif category.startswith('tempmaint'):
256        #    if not self._hostelApplicationPaymentMade(
257        #        student, student.current_session):
258        #        return _(
259        #            'You have not yet paid the hostel application fee.'), None
260        #    if category == 'tempmaint_1':
261        #        amount = 8150.0
262        #    elif category == 'tempmaint_2':
263        #        amount = 12650.0
264        #    elif category == 'tempmaint_3':
265        #        amount = 9650.0
266        elif category == 'clearance':
267            p_item = student.certcode
268            if p_item is None:
269                return _('Study course data are incomplete.'), None
270            if student.is_jupeb:
271                amount = 50000.0
272            elif student.faccode.startswith('FCETA'):
273                # ASABA and AKOKA
274                amount = 35000.0
275            elif p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
276                'MBBSMED', 'MBBSNDU', 'BSCPTY'):
277                amount = 80000.0
278            else:
279                amount = 60000.0
280        elif category == 'schoolfee':
281            try:
282                certificate = student['studycourse'].certificate
283                p_item = certificate.code
284            except (AttributeError, TypeError):
285                return _('Study course data are incomplete.'), None
286            if previous_session:
287                # Students can pay for previous sessions in all workflow states.
288                # Fresh students are excluded by the update method of the
289                # PreviousPaymentAddFormPage.
290                if previous_session == student['studycourse'].entry_session:
291                    if student.is_foreigner:
292                        amount = getattr(certificate, 'school_fee_3', 0.0)
293                    else:
294                        amount = getattr(certificate, 'school_fee_1', 0.0)
295                else:
296                    if student.is_foreigner:
297                        amount = getattr(certificate, 'school_fee_4', 0.0)
298                    else:
299                        amount = getattr(certificate, 'school_fee_2', 0.0)
300                        # Old returning students might get a discount.
301                        if student.entry_session < 2017 \
302                            and certificate.custom_float_1:
303                            amount -= certificate.custom_float_1
304            else:
305                if student.state == CLEARED:
306                    if student.is_foreigner:
307                        amount = getattr(certificate, 'school_fee_3', 0.0)
308                    else:
309                        amount = getattr(certificate, 'school_fee_1', 0.0)
310                elif student.state == PAID and student.is_postgrad:
311                    p_session += 1
312                    academic_session = self._getSessionConfiguration(p_session)
313                    if academic_session == None:
314                        return _(u'Session configuration object is not available.'), None
315
316                    # Students are only allowed to pay for the next session
317                    # if current session payment
318                    # has really been made, i.e. payment object exists.
319                    #if not self._paymentMade(
320                    #    student, student.current_session):
321                    #    return _('You have not yet paid your current/active' +
322                    #             ' session. Please use the previous session' +
323                    #             ' payment form first.'), None
324
325                    if student.is_foreigner:
326                        amount = getattr(certificate, 'school_fee_4', 0.0)
327                    else:
328                        amount = getattr(certificate, 'school_fee_2', 0.0)
329                elif student.state == RETURNING:
330                    # In case of returning school fee payment the payment session
331                    # and level contain the values of the session the student
332                    # has paid for.
333                    p_session, p_level = self.getReturningData(student)
334                    academic_session = self._getSessionConfiguration(p_session)
335                    if academic_session == None:
336                        return _(u'Session configuration object is not available.'), None
337
338                    # Students are only allowed to pay for the next session
339                    # if current session payment has really been made,
340                    # i.e. payment object exists and is paid.
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
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)
351                        # Old returning students might get a discount.
352                        if student.entry_session < 2017 \
353                            and certificate.custom_float_1:
354                            amount -= certificate.custom_float_1
355                # PHARMD school fee amount is fixed and previously paid
356                # installments in current session are deducted.
357                if student.current_mode == 'special_ft':
358                    amount = 160000.0 - self._pharmdInstallments(student)
359            # Give 50% school fee discount to staff members.
360            if student.is_staff:
361                amount /= 2
362        if amount in (0.0, None):
363            return _('Amount could not be determined.'), None
364        # Add session specific penalty fee.
365        if category == 'schoolfee' and student.is_postgrad:
366            amount += academic_session.penalty_pg
367            amount += academic_session.development_fee
368        elif category == 'schoolfee' and student.current_mode == ('ug_ft'):
369            amount += academic_session.penalty_ug_ft
370        elif category == 'schoolfee' and student.current_mode == ('ug_pt'):
371            amount += academic_session.penalty_ug_pt
372        elif category == 'schoolfee' and student.current_mode == ('ug_sw'):
373            amount += academic_session.penalty_sw
374        elif category == 'schoolfee' and student.current_mode in (
375            'dp_ft', 'dp_pt'):
376            amount += academic_session.penalty_dp
377        if category.startswith('tempmaint'):
378            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
379            p_item = unicode(p_item)
380            # Now we change the category because tempmaint payments
381            # will be obsolete when Uniben returns to Kofa bed allocation.
382            category = 'hostel_maintenance'
383        # Create ticket.
384        if self.samePaymentMade(student, category, p_item, p_session):
385            return _('This type of payment has already been made.'), None
386        if self._isPaymentDisabled(p_session, category, student):
387            return _('This category of payments has been disabled.'), None
388        payment = createObject(u'waeup.StudentOnlinePayment')
389        timestamp = ("%d" % int(time()*10000))[1:]
390        payment.p_id = "p%s" % timestamp
391        payment.p_category = category
392        payment.p_item = p_item
393        payment.p_session = p_session
394        payment.p_level = p_level
395        payment.p_current = p_current
396        payment.amount_auth = amount
397        return None, payment
398
399    def warnCreditsOOR(self, studylevel, course=None):
400        studycourse = studylevel.__parent__
401        certificate = getattr(studycourse,'certificate', None)
402        current_level = studycourse.current_level
403        if None in (current_level, certificate):
404            return
405        end_level = certificate.end_level
406        if current_level >= end_level:
407            limit = 51
408        else:
409            limit = 50
410        if course and studylevel.total_credits + course.credits > limit:
411            return _('Maximum credits exceeded.')
412        elif studylevel.total_credits > limit:
413            return _('Maximum credits exceeded.')
414        return
415
416    def clearance_disabled_message(self, student):
417        if student.is_postgrad:
418            return None
419        try:
420            session_config = grok.getSite()[
421                'configuration'][str(student.current_session)]
422        except KeyError:
423            return _('Session configuration object is not available.')
424        if not session_config.clearance_enabled:
425            return _('Clearance is disabled for this session.')
426        return None
427
428    #: A tuple containing the names of registration states in which changing of
429    #: passport pictures is allowed.
430    PORTRAIT_CHANGE_STATES = ()
431
432    # Uniben prefix
433    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.