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

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

JUPEB students don't need to pay.

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