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

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

Further customize checkAccommodationRequirements.

Add student union dues to bed allocation fees.

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