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

Last change on this file since 14662 was 14598, checked in by Henrik Bettermann, 8 years ago

Extend _isPaymentDisabled.

  • Property svn:keywords set to Id
File size: 18.2 KB
Line 
1## $Id: utils.py 14598 2017-03-01 12:11:54Z 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' and \
145            'sf_all' in academic_session.payment_disabled:
146            return True
147        if category == 'hostel_maintenance' and \
148            'maint_all' in academic_session.payment_disabled:
149            return True
150        if category == 'schoolfee' and \
151            student.current_mode == 'found' and \
152            'sf_found' in academic_session.payment_disabled:
153            return True
154        return False
155
156    #def _hostelApplicationPaymentMade(self, student, session):
157    #    if len(student['payments']):
158    #        for ticket in student['payments'].values():
159    #            if ticket.p_state == 'paid' and \
160    #                ticket.p_category == 'hostel_application' and \
161    #                ticket.p_session == session:
162    #                return True
163    #    return False
164
165    def setPaymentDetails(self, category, student,
166            previous_session, previous_level):
167        """Create Payment object and set the payment data of a student for
168        the payment category specified.
169
170        """
171        p_item = u''
172        amount = 0.0
173        if previous_session:
174            if previous_session < student['studycourse'].entry_session:
175                return _('The previous session must not fall below '
176                         'your entry session.'), None
177            if category == 'schoolfee':
178                # School fee is always paid for the following session
179                if previous_session > student['studycourse'].current_session:
180                    return _('This is not a previous session.'), None
181            else:
182                if previous_session > student['studycourse'].current_session - 1:
183                    return _('This is not a previous session.'), None
184            p_session = previous_session
185            p_level = previous_level
186            p_current = False
187        else:
188            p_session = student['studycourse'].current_session
189            p_level = student['studycourse'].current_level
190            p_current = True
191        academic_session = self._getSessionConfiguration(p_session)
192        if academic_session == None:
193            return _(u'Session configuration object is not available.'), None
194        # Determine fee.
195        if category == 'transfer':
196            amount = academic_session.transfer_fee
197        elif category == 'transcript':
198            amount = academic_session.transcript_fee
199        elif category == 'gown':
200            amount = academic_session.gown_fee
201        elif category == 'jupeb':
202            amount = academic_session.jupeb_fee
203        elif category == 'clinexam':
204            amount = academic_session.clinexam_fee
205        elif category == 'bed_allocation':
206            p_item = self.getAccommodationDetails(student)['bt']
207            amount = academic_session.booking_fee
208            # Add student union dues
209            if not student.is_postgrad:
210                stage = self.getAccommodationDetails(student)['bt']
211                stage = stage.split('_')[2]
212                if stage == 'fr':
213                    amount += 500.0
214                elif stage in ('fi', 're') and student[
215                    'studycourse'].previous_verdict in (
216                        'A', 'B', 'F', 'J', 'M', 'C', 'Z'):
217                    amount += 300.0
218                else:
219                    amount = 0.0
220        elif category == 'hostel_maintenance':
221            amount = 0.0
222            bedticket = student['accommodation'].get(
223                str(student.current_session), None)
224            if bedticket is not None and bedticket.bed is not None:
225                p_item = bedticket.bed_coordinates
226                if bedticket.bed.__parent__.maint_fee > 0:
227                    amount = bedticket.bed.__parent__.maint_fee
228                else:
229                    # fallback
230                    amount = academic_session.maint_fee
231            else:
232                return _(u'No bed allocated.'), None
233        #elif category == 'hostel_application':
234        #    amount = 1000.0
235        #elif category.startswith('tempmaint'):
236        #    if not self._hostelApplicationPaymentMade(
237        #        student, student.current_session):
238        #        return _(
239        #            'You have not yet paid the hostel application fee.'), None
240        #    if category == 'tempmaint_1':
241        #        amount = 8150.0
242        #    elif category == 'tempmaint_2':
243        #        amount = 12650.0
244        #    elif category == 'tempmaint_3':
245        #        amount = 9650.0
246        elif category == 'clearance':
247            p_item = student.certcode
248            if p_item is None:
249                return _('Study course data are incomplete.'), None
250            if student.faccode == 'JUPEB':
251                return _('No payment required.'), None
252            if student.faccode.startswith('FCETA'):
253                # ASABA and AKOKA
254                amount = 30000.0
255            elif p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
256                'MBBSMED', 'MBBSNDU', 'BSCPTY'):
257                amount = 65000.0
258            else:
259                amount = 45000.0
260            # Clearance fee and provider amount have been increased
261            # for new students.
262            if student.entry_session >= 2016:
263                amount += 5000.0
264        elif category == 'schoolfee':
265            try:
266                certificate = student['studycourse'].certificate
267                p_item = certificate.code
268            except (AttributeError, TypeError):
269                return _('Study course data are incomplete.'), None
270
271            #####################################################
272            #if student.faccode == 'JUPEB':
273            #    return _('Payment temporarily disabled.'), None
274            #####################################################
275
276
277            if previous_session:
278                # Students can pay for previous sessions in all workflow states.
279                # Fresh students are excluded by the update method of the
280                # PreviousPaymentAddFormPage.
281                if previous_session == student['studycourse'].entry_session:
282                    if student.is_foreigner:
283                        amount = getattr(certificate, 'school_fee_3', 0.0)
284                    else:
285                        amount = getattr(certificate, 'school_fee_1', 0.0)
286                else:
287                    if student.is_foreigner:
288                        amount = getattr(certificate, 'school_fee_4', 0.0)
289                    else:
290                        amount = getattr(certificate, 'school_fee_2', 0.0)
291            else:
292                if student.state == CLEARED:
293                    if student.is_foreigner:
294                        amount = getattr(certificate, 'school_fee_3', 0.0)
295                    else:
296                        amount = getattr(certificate, 'school_fee_1', 0.0)
297                elif student.state in (PAID, REGISTERED, VALIDATED):
298                    p_session += 1
299                    # We don't know which level the student is paying for.
300                    p_level = None
301                    academic_session = self._getSessionConfiguration(p_session)
302                    if academic_session == None:
303                        return _(u'Session configuration object is not available.'), None
304
305                    # Students are only allowed to pay for the next session
306                    # if current session payment
307                    # has really been made, i.e. payment object exists.
308                    #if not self._paymentMade(
309                    #    student, student.current_session):
310                    #    return _('You have not yet paid your current/active' +
311                    #             ' session. Please use the previous session' +
312                    #             ' payment form first.'), None
313
314                    if student.is_foreigner:
315                        amount = getattr(certificate, 'school_fee_4', 0.0)
316                    else:
317                        amount = getattr(certificate, 'school_fee_2', 0.0)
318                elif student.state == RETURNING:
319                    # In case of returning school fee payment the payment session
320                    # and level contain the values of the session the student
321                    # has paid for.
322                    p_session, p_level = self.getReturningData(student)
323                    academic_session = self._getSessionConfiguration(p_session)
324                    if academic_session == None:
325                        return _(u'Session configuration object is not available.'), None
326
327                    # Students are only allowed to pay for the next session
328                    # if current session payment has really been made,
329                    # i.e. payment object exists and is paid.
330                    #if not self._paymentMade(
331                    #    student, student.current_session):
332                    #    return _('You have not yet paid your current/active' +
333                    #             ' session. Please use the previous session' +
334                    #             ' payment form first.'), None
335
336                    if student.is_foreigner:
337                        amount = getattr(certificate, 'school_fee_4', 0.0)
338                    else:
339                        amount = getattr(certificate, 'school_fee_2', 0.0)
340            # Give 50% school fee discount to staff members.
341            if student.is_staff:
342                amount /= 2
343        if amount in (0.0, None):
344            return _('Amount could not be determined.'), None
345        # Add session specific penalty fee.
346        if category == 'schoolfee' and student.is_postgrad:
347            amount += academic_session.penalty_pg
348        elif category == 'schoolfee' and student.current_mode == ('ug_ft'):
349            amount += academic_session.penalty_ug_ft
350        elif category == 'schoolfee' and student.current_mode == ('ug_pt'):
351            amount += academic_session.penalty_ug_pt
352        elif category == 'schoolfee' and student.current_mode == ('ug_sw'):
353            amount += academic_session.penalty_sw
354        if category.startswith('tempmaint'):
355            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
356            p_item = unicode(p_item)
357            # Now we change the category because tempmaint payments
358            # will be obsolete when Uniben returns to Kofa bed allocation.
359            category = 'hostel_maintenance'
360        # Create ticket.
361        if self.samePaymentMade(student, category, p_item, p_session):
362            return _('This type of payment has already been made.'), None
363        if self._isPaymentDisabled(p_session, category, student):
364            return _('This category of payments has been disabled.'), None
365        payment = createObject(u'waeup.StudentOnlinePayment')
366        timestamp = ("%d" % int(time()*10000))[1:]
367        payment.p_id = "p%s" % timestamp
368        payment.p_category = category
369        payment.p_item = p_item
370        payment.p_session = p_session
371        payment.p_level = p_level
372        payment.p_current = p_current
373        payment.amount_auth = amount
374        return None, payment
375
376    def warnCreditsOOR(self, studylevel, course=None):
377        studycourse = studylevel.__parent__
378        certificate = getattr(studycourse,'certificate', None)
379        current_level = studycourse.current_level
380        if None in (current_level, certificate):
381            return
382        end_level = certificate.end_level
383        if current_level >= end_level:
384            limit = 51
385        else:
386            limit = 50
387        if course and studylevel.total_credits + course.credits > limit:
388            return _('Maximum credits exceeded.')
389        elif studylevel.total_credits > limit:
390            return _('Maximum credits exceeded.')
391        return
392
393    def clearance_disabled_message(self, student):
394        if student.is_postgrad:
395            return None
396        try:
397            session_config = grok.getSite()[
398                'configuration'][str(student.current_session)]
399        except KeyError:
400            return _('Session configuration object is not available.')
401        if not session_config.clearance_enabled:
402            return _('Clearance is disabled for this session.')
403        return None
404
405    #: A tuple containing the names of registration states in which changing of
406    #: passport pictures is allowed.
407    PORTRAIT_CHANGE_STATES = ()
408
409    # Uniben prefix
410    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.