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

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

Initiate customization of getAccommodationDetails.

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