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

Last change on this file since 13499 was 13499, checked in by Henrik Bettermann, 9 years ago

Remove PHA and BMS from clinical hostel allocation.

  • Property svn:keywords set to Id
File size: 17.0 KB
Line 
1## $Id: utils.py 13499 2015-11-26 16:18:08Z 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 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        ####################################################################################
80        #if stage in ('fi', 're'):
81        #    return _("Accommodation booking for returning and final year students has not yet started.")
82        ####################################################################################
83        if stage != 'fr' and not student['studycourse'].previous_verdict in ('A', 'B'):
84            return _("Your are not eligible to book accommodation.")
85        if str(acc_details['booking_session']) in student['accommodation'].keys():
86            return _('You already booked a bed space in '
87                     'current accommodation session.')
88        return
89
90    def getAccommodationDetails(self, student):
91        """Determine the accommodation data of a student.
92        """
93        d = {}
94        d['error'] = u''
95        hostels = grok.getSite()['hostels']
96        d['booking_session'] = hostels.accommodation_session
97        d['allowed_states'] = hostels.accommodation_states
98        d['startdate'] = hostels.startdate
99        d['enddate'] = hostels.enddate
100        d['expired'] = hostels.expired
101        # Determine bed type
102        studycourse = student['studycourse']
103        certificate = getattr(studycourse,'certificate',None)
104        entry_session = studycourse.entry_session
105        current_level = studycourse.current_level
106        if None in (entry_session, current_level, certificate):
107            return d
108        end_level = certificate.end_level
109        if current_level == 10:
110            bt = 'pr'
111        elif entry_session == grok.getSite()['hostels'].accommodation_session:
112            bt = 'fr'
113        elif current_level >= end_level:
114            bt = 'fi'
115        else:
116            bt = 're'
117        if student.sex == 'f':
118            sex = 'female'
119        else:
120            sex = 'male'
121        special_handling = 'regular'
122        if student.faccode in ('MED', 'DEN'):
123            special_handling = 'clinical'
124        elif student.certcode in ('BARTMAS', 'BARTTHR', 'BARTFAA',
125                                  'BAEDFAA', 'BSCEDECHED'):
126            special_handling = 'ekenwan'
127        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
128        return d
129
130    def _paymentMade(self, student, session):
131        if len(student['payments']):
132            for ticket in student['payments'].values():
133                if ticket.p_state == 'paid' and \
134                    ticket.p_category == 'schoolfee' and \
135                    ticket.p_session == session:
136                    return True
137        return False
138
139    #def _hostelApplicationPaymentMade(self, student, session):
140    #    if len(student['payments']):
141    #        for ticket in student['payments'].values():
142    #            if ticket.p_state == 'paid' and \
143    #                ticket.p_category == 'hostel_application' and \
144    #                ticket.p_session == session:
145    #                return True
146    #    return False
147
148    def setPaymentDetails(self, category, student,
149            previous_session, previous_level):
150        """Create Payment object and set the payment data of a student for
151        the payment category specified.
152
153        """
154        p_item = u''
155        amount = 0.0
156        if previous_session:
157            if previous_session < student['studycourse'].entry_session:
158                return _('The previous session must not fall below '
159                         'your entry session.'), None
160            if category == 'schoolfee':
161                # School fee is always paid for the following session
162                if previous_session > student['studycourse'].current_session:
163                    return _('This is not a previous session.'), None
164            else:
165                if previous_session > student['studycourse'].current_session - 1:
166                    return _('This is not a previous session.'), None
167            p_session = previous_session
168            p_level = previous_level
169            p_current = False
170        else:
171            p_session = student['studycourse'].current_session
172            p_level = student['studycourse'].current_level
173            p_current = True
174        academic_session = self._getSessionConfiguration(p_session)
175        if academic_session == None:
176            return _(u'Session configuration object is not available.'), None
177        # Determine fee.
178        if category == 'transfer':
179            amount = academic_session.transfer_fee
180        elif category == 'transcript':
181            amount = academic_session.transcript_fee
182        elif category == 'gown':
183            amount = academic_session.gown_fee
184        elif category == 'bed_allocation':
185            p_item = self.getAccommodationDetails(student)['bt']
186            amount = academic_session.booking_fee
187            # Add student union dues
188            stage = self.getAccommodationDetails(student)['bt']
189            stage = stage.split('_')[2]
190            #####################################################
191            #if stage == 'fi':
192            #    return _('Payment temporarily disabled.'), None
193            #####################################################
194            if stage == 'fr':
195                amount += 500.0
196            elif stage in ('fi', 're') and student[
197                'studycourse'].previous_verdict in ('A', 'B'):
198                amount += 300.0
199            else:
200                amount = 0.0
201        elif category == 'hostel_maintenance':
202            amount = 0.0
203            bedticket = student['accommodation'].get(
204                str(student.current_session), None)
205            if bedticket:
206                p_item = bedticket.bed_coordinates
207                if bedticket.bed.__parent__.maint_fee > 0:
208                    amount = bedticket.bed.__parent__.maint_fee
209                else:
210                    # fallback
211                    amount = academic_session.maint_fee
212            else:
213                # Should not happen because this is already checked
214                # in the browser module, but anyway ...
215                portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
216                p_item = trans(_('no bed allocated'), portal_language)
217
218        #elif category == 'hostel_application':
219        #    amount = 1000.0
220        #elif category.startswith('tempmaint'):
221        #    if not self._hostelApplicationPaymentMade(
222        #        student, student.current_session):
223        #        return _(
224        #            'You have not yet paid the hostel application fee.'), None
225        #    if category == 'tempmaint_1':
226        #        amount = 8150.0
227        #    elif category == 'tempmaint_2':
228        #        amount = 12650.0
229        #    elif category == 'tempmaint_3':
230        #        amount = 9650.0
231        elif category == 'clearance':
232            p_item = student.certcode
233            if p_item is None:
234                return _('Study course data are incomplete.'), None
235            if student.faccode == 'JUPEB':
236                return _('No payment required.'), None
237            if student.faccode == 'FCETA':
238                amount = 22500.0
239            elif p_item in ('BSCANA', 'BSCMBC', 'BMLS', 'BSCNUR', 'BSCPHS', 'BDS',
240                'MBBSMED', 'MBBSNDU'):
241                amount = 65000.0
242            elif p_item in ('BEDCET', 'BIOEDCET', 'CHMEDCET', 'ISEDCET',
243                'MTHEDCET', 'PHYEDCET', 'ITECET', 'AGREDCET', 'HEEDCET'):
244                amount = 22500.0
245            else:
246                amount = 45000.0
247        elif category == 'schoolfee':
248            try:
249                certificate = student['studycourse'].certificate
250                p_item = certificate.code
251            except (AttributeError, TypeError):
252                return _('Study course data are incomplete.'), None
253
254            #####################################################
255            #if student.faccode == 'JUPEB':
256            #    return _('Payment temporarily disabled.'), None
257            #####################################################
258
259
260            if previous_session:
261                # Students can pay for previous sessions in all workflow states.
262                # Fresh students are excluded by the update method of the
263                # PreviousPaymentAddFormPage.
264                if previous_session == student['studycourse'].entry_session:
265                    if student.is_foreigner:
266                        amount = getattr(certificate, 'school_fee_3', 0.0)
267                    else:
268                        amount = getattr(certificate, 'school_fee_1', 0.0)
269                else:
270                    if student.is_foreigner:
271                        amount = getattr(certificate, 'school_fee_4', 0.0)
272                    else:
273                        amount = getattr(certificate, 'school_fee_2', 0.0)
274            else:
275                if student.state == CLEARED:
276                    if student.is_foreigner:
277                        amount = getattr(certificate, 'school_fee_3', 0.0)
278                    else:
279                        amount = getattr(certificate, 'school_fee_1', 0.0)
280                elif student.state in (PAID, REGISTERED, VALIDATED):
281                    p_session += 1
282                    # We don't know which level the student is paying for.
283                    p_level = None
284                    academic_session = self._getSessionConfiguration(p_session)
285                    if academic_session == None:
286                        return _(u'Session configuration object is not available.'), None
287
288                    # Students are only allowed to pay for the next session
289                    # if current session payment
290                    # has really been made, i.e. payment object exists.
291                    #if not self._paymentMade(
292                    #    student, student.current_session):
293                    #    return _('You have not yet paid your current/active' +
294                    #             ' session. Please use the previous session' +
295                    #             ' payment form first.'), None
296
297                    if student.is_foreigner:
298                        amount = getattr(certificate, 'school_fee_4', 0.0)
299                    else:
300                        amount = getattr(certificate, 'school_fee_2', 0.0)
301                elif student.state == RETURNING:
302                    # In case of returning school fee payment the payment session
303                    # and level contain the values of the session the student
304                    # has paid for.
305                    p_session, p_level = self.getReturningData(student)
306                    academic_session = self._getSessionConfiguration(p_session)
307                    if academic_session == None:
308                        return _(u'Session configuration object is not available.'), None
309
310                    # Students are only allowed to pay for the next session
311                    # if current session payment has really been made,
312                    # i.e. payment object exists and is paid.
313                    #if not self._paymentMade(
314                    #    student, student.current_session):
315                    #    return _('You have not yet paid your current/active' +
316                    #             ' session. Please use the previous session' +
317                    #             ' payment form first.'), None
318
319                    if student.is_foreigner:
320                        amount = getattr(certificate, 'school_fee_4', 0.0)
321                    else:
322                        amount = getattr(certificate, 'school_fee_2', 0.0)
323            # Give 50% school fee discount to staff members.
324            if student.is_staff:
325                amount /= 2
326        if amount in (0.0, None):
327            return _('Amount could not be determined.'), None
328        # Add session specific penalty fee.
329        if category == 'schoolfee' and student.is_postgrad:
330            amount += academic_session.penalty_pg
331        elif category == 'schoolfee':
332            amount += academic_session.penalty_ug
333        if category.startswith('tempmaint'):
334            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
335            p_item = unicode(p_item)
336            # Now we change the category because tempmaint payments
337            # will be obsolete when Uniben returns to Kofa bed allocation.
338            category = 'hostel_maintenance'
339        # Create ticket.
340        if self.samePaymentMade(student, category, p_item, p_session):
341            return _('This type of payment has already been made.'), None
342        if self._isPaymentDisabled(p_session, category, student):
343            return _('Payment temporarily disabled.'), None
344        payment = createObject(u'waeup.StudentOnlinePayment')
345        timestamp = ("%d" % int(time()*10000))[1:]
346        payment.p_id = "p%s" % timestamp
347        payment.p_category = category
348        payment.p_item = p_item
349        payment.p_session = p_session
350        payment.p_level = p_level
351        payment.p_current = p_current
352        payment.amount_auth = amount
353        return None, payment
354
355    def maxCredits(self, studylevel):
356        """Return maximum credits.
357
358        """
359        studycourse = studylevel.__parent__
360        certificate = getattr(studycourse,'certificate', None)
361        current_level = studycourse.current_level
362        if None in (current_level, certificate):
363            return 0
364        end_level = certificate.end_level
365        if current_level >= end_level:
366            return 51
367        return 50
368
369    def clearance_disabled_message(self, student):
370        if student.is_postgrad:
371            return None
372        try:
373            session_config = grok.getSite()[
374                'configuration'][str(student.current_session)]
375        except KeyError:
376            return _('Session configuration object is not available.')
377        if not session_config.clearance_enabled:
378            return _('Clearance is disabled for this session.')
379        return None
380
381    # Uniben prefix
382    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.