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

Last change on this file since 15392 was 15392, checked in by Henrik Bettermann, 5 years ago

Referred students should be able to book accommodation.

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