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

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

Do only allow adding bed_allocation payments if desired_hostel is set.

  • Property svn:keywords set to Id
File size: 19.9 KB
Line 
1## $Id: utils.py 15314 2019-01-29 21:47:26Z 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 setPaymentDetails(self, category, student,
193            previous_session, previous_level):
194        """Create Payment object and set the payment data of a student for
195        the payment category specified.
196
197        """
198        p_item = u''
199        amount = 0.0
200        if previous_session:
201            if previous_session < student['studycourse'].entry_session:
202                return _('The previous session must not fall below '
203                         'your entry session.'), None
204            if category == 'schoolfee':
205                # School fee is always paid for the following session
206                if previous_session > student['studycourse'].current_session:
207                    return _('This is not a previous session.'), None
208            else:
209                if previous_session > student['studycourse'].current_session - 1:
210                    return _('This is not a previous session.'), None
211            p_session = previous_session
212            p_level = previous_level
213            p_current = False
214        else:
215            p_session = student['studycourse'].current_session
216            p_level = student['studycourse'].current_level
217            p_current = True
218        academic_session = self._getSessionConfiguration(p_session)
219        if academic_session == None:
220            return _(u'Session configuration object is not available.'), None
221        # Determine fee.
222        if category == 'transfer':
223            amount = academic_session.transfer_fee
224        elif category == 'transcript':
225            amount = academic_session.transcript_fee
226        elif category == 'gown':
227            amount = academic_session.gown_fee
228        elif category == 'jupeb':
229            amount = academic_session.jupeb_fee
230        elif category == 'clinexam':
231            amount = academic_session.clinexam_fee
232        elif category.startswith('pharmd') \
233            and student.current_mode == 'special_ft':
234            amount = 80000.0
235        #elif category == 'develop' and student.is_postgrad:
236        #    amount = academic_session.development_fee
237        elif category == 'bed_allocation':
238            p_item = self.getAccommodationDetails(student)['bt']
239            desired_hostel = student['accommodation'].desired_hostel
240            if not desired_hostel:
241                return _(u'Select your favoured hostel first.'), None
242            if desired_hostel and desired_hostel != 'no':
243                p_item = u'%s (%s)' % (p_item, desired_hostel)
244            amount = academic_session.booking_fee
245            if student.is_postgrad:
246                amount += 500
247        elif category == 'hostel_maintenance':
248            amount = 0.0
249            bedticket = student['accommodation'].get(
250                str(student.current_session), None)
251            if bedticket is not None and bedticket.bed is not None:
252                p_item = bedticket.bed_coordinates
253                if bedticket.bed.__parent__.maint_fee > 0:
254                    amount = bedticket.bed.__parent__.maint_fee
255                else:
256                    # fallback
257                    amount = academic_session.maint_fee
258            else:
259                return _(u'No bed allocated.'), None
260        #elif category == 'hostel_application':
261        #    amount = 1000.0
262        #elif category.startswith('tempmaint'):
263        #    if not self._hostelApplicationPaymentMade(
264        #        student, student.current_session):
265        #        return _(
266        #            'You have not yet paid the hostel application fee.'), None
267        #    if category == 'tempmaint_1':
268        #        amount = 8150.0
269        #    elif category == 'tempmaint_2':
270        #        amount = 12650.0
271        #    elif category == 'tempmaint_3':
272        #        amount = 9650.0
273        elif category == 'clearance':
274            p_item = student.certcode
275            if p_item is None:
276                return _('Study course data are incomplete.'), None
277            if student.is_jupeb:
278                amount = 50000.0
279            elif student.faccode.startswith('FCETA'):
280                # ASABA and AKOKA
281                amount = 35000.0
282            elif p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
283                'MBBSMED', 'MBBSNDU', 'BSCPTY'):
284                amount = 80000.0
285            else:
286                amount = 60000.0
287        elif category == 'schoolfee':
288            try:
289                certificate = student['studycourse'].certificate
290                p_item = certificate.code
291            except (AttributeError, TypeError):
292                return _('Study course data are incomplete.'), None
293            if previous_session:
294                # Students can pay for previous sessions in all workflow states.
295                # Fresh students are excluded by the update method of the
296                # PreviousPaymentAddFormPage.
297                if previous_session == student['studycourse'].entry_session:
298                    if student.is_foreigner:
299                        amount = getattr(certificate, 'school_fee_3', 0.0)
300                    else:
301                        amount = getattr(certificate, 'school_fee_1', 0.0)
302                else:
303                    if student.is_foreigner:
304                        amount = getattr(certificate, 'school_fee_4', 0.0)
305                    else:
306                        amount = getattr(certificate, 'school_fee_2', 0.0)
307                        # Old returning students might get a discount.
308                        if student.entry_session < 2017 \
309                            and certificate.custom_float_1:
310                            amount -= certificate.custom_float_1
311            else:
312                if student.state == CLEARED:
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)
317                elif student.state == PAID and student.is_postgrad:
318                    p_session += 1
319                    academic_session = self._getSessionConfiguration(p_session)
320                    if academic_session == None:
321                        return _(u'Session configuration object is not available.'), None
322
323                    # Students are only allowed to pay for the next session
324                    # if current session payment
325                    # has really been made, i.e. payment object exists.
326                    #if not self._paymentMade(
327                    #    student, student.current_session):
328                    #    return _('You have not yet paid your current/active' +
329                    #             ' session. Please use the previous session' +
330                    #             ' payment form first.'), None
331
332                    if student.is_foreigner:
333                        amount = getattr(certificate, 'school_fee_4', 0.0)
334                    else:
335                        amount = getattr(certificate, 'school_fee_2', 0.0)
336                elif student.state == RETURNING:
337                    # In case of returning school fee payment the payment session
338                    # and level contain the values of the session the student
339                    # has paid for.
340                    p_session, p_level = self.getReturningData(student)
341                    academic_session = self._getSessionConfiguration(p_session)
342                    if academic_session == None:
343                        return _(u'Session configuration object is not available.'), None
344
345                    # Students are only allowed to pay for the next session
346                    # if current session payment has really been made,
347                    # i.e. payment object exists and is paid.
348                    #if not self._paymentMade(
349                    #    student, student.current_session):
350                    #    return _('You have not yet paid your current/active' +
351                    #             ' session. Please use the previous session' +
352                    #             ' payment form first.'), None
353
354                    if student.is_foreigner:
355                        amount = getattr(certificate, 'school_fee_4', 0.0)
356                    else:
357                        amount = getattr(certificate, 'school_fee_2', 0.0)
358                        # Old returning students might get a discount.
359                        if student.entry_session < 2017 \
360                            and certificate.custom_float_1:
361                            amount -= certificate.custom_float_1
362                # PHARMD school fee amount is fixed and previously paid
363                # installments in current session are deducted.
364                if student.current_mode == 'special_ft':
365                    amount = 160000.0 - self._pharmdInstallments(student)
366            # Give 50% school fee discount to staff members.
367            if student.is_staff:
368                amount /= 2
369        if amount in (0.0, None):
370            return _('Amount could not be determined.'), None
371        # Add session specific penalty fee.
372        if category == 'schoolfee' and student.is_postgrad:
373            amount += academic_session.penalty_pg
374            amount += academic_session.development_fee
375        elif category == 'schoolfee' and student.current_mode == ('ug_ft'):
376            amount += academic_session.penalty_ug_ft
377        elif category == 'schoolfee' and student.current_mode == ('ug_pt'):
378            amount += academic_session.penalty_ug_pt
379        elif category == 'schoolfee' and student.current_mode == ('ug_sw'):
380            amount += academic_session.penalty_sw
381        elif category == 'schoolfee' and student.current_mode in (
382            'dp_ft', 'dp_pt'):
383            amount += academic_session.penalty_dp
384        if category.startswith('tempmaint'):
385            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
386            p_item = unicode(p_item)
387            # Now we change the category because tempmaint payments
388            # will be obsolete when Uniben returns to Kofa bed allocation.
389            category = 'hostel_maintenance'
390        # Create ticket.
391        if self.samePaymentMade(student, category, p_item, p_session):
392            return _('This type of payment has already been made.'), None
393        if self._isPaymentDisabled(p_session, category, student):
394            return _('This category of payments has been disabled.'), None
395        payment = createObject(u'waeup.StudentOnlinePayment')
396        timestamp = ("%d" % int(time()*10000))[1:]
397        payment.p_id = "p%s" % timestamp
398        payment.p_category = category
399        payment.p_item = p_item
400        payment.p_session = p_session
401        payment.p_level = p_level
402        payment.p_current = p_current
403        payment.amount_auth = amount
404        return None, payment
405
406    def warnCreditsOOR(self, studylevel, course=None):
407        studycourse = studylevel.__parent__
408        certificate = getattr(studycourse,'certificate', None)
409        current_level = studycourse.current_level
410        if None in (current_level, certificate):
411            return
412        end_level = certificate.end_level
413        if current_level >= end_level:
414            limit = 51
415        else:
416            limit = 50
417        if course and studylevel.total_credits + course.credits > limit:
418            return _('Maximum credits exceeded.')
419        elif studylevel.total_credits > limit:
420            return _('Maximum credits exceeded.')
421        return
422
423    def clearance_disabled_message(self, student):
424        if student.is_postgrad:
425            return None
426        try:
427            session_config = grok.getSite()[
428                'configuration'][str(student.current_session)]
429        except KeyError:
430            return _('Session configuration object is not available.')
431        if not session_config.clearance_enabled:
432            return _('Clearance is disabled for this session.')
433        return None
434
435    #: A tuple containing the names of registration states in which changing of
436    #: passport pictures is allowed.
437    PORTRAIT_CHANGE_STATES = ()
438
439    # Uniben prefix
440    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.