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

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

Allow hostel booking if current session bed ticket has expired.

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