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

Last change on this file since 13324 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
RevLine 
[7419]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##
[11773]18import grok
[8598]19from time import time
[9459]20from zope.component import createObject, getUtility
[9513]21from waeup.kofa.interfaces import (IKofaUtils,
22    CLEARED, RETURNING, PAID, REGISTERED, VALIDATED)
[13251]23from waeup.kofa.utils.helpers import to_timezone
24from waeup.kofa.students.utils import trans
[8821]25from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
[8020]26from waeup.uniben.interfaces import MessageFactory as _
[6902]27
[8821]28class CustomStudentsUtils(NigeriaStudentsUtils):
[7151]29    """A collection of customized methods.
30
31    """
32
[8270]33    def getReturningData(self, student):
34        """ This method defines what happens after school fee payment
[8319]35        of returning students depending on the student's senate verdict.
[8270]36        """
[8319]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
[8270]49        new_session = student['studycourse'].current_session + 1
50        return new_session, new_level
51
[13251]52
[13248]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.")
[13283]67        bt = acc_details.get('bt')
68        if not bt:
[13248]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.')
[13283]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.")
[13309]79        if stage != 'fr' and not student['studycourse'].previous_verdict in ('A', 'B'):
[13283]80            return _("Your are not eligible to book accommodation.")
[13248]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
[13244]85
[13295]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'
[13298]118        if student.faccode in ('MED', 'DEN'):
[13296]119            special_handling = 'clinical'
[13295]120        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
121        return d
122
[9520]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
[13251]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
[12566]140
[9152]141    def setPaymentDetails(self, category, student,
142            previous_session, previous_level):
[8598]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
[9152]149        if previous_session:
[9520]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
[9152]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
[9520]167        academic_session = self._getSessionConfiguration(p_session)
168        if academic_session == None:
[8598]169            return _(u'Session configuration object is not available.'), None
[8676]170        # Determine fee.
[7151]171        if category == 'transfer':
[8598]172            amount = academic_session.transfer_fee
[10469]173        elif category == 'transcript':
174            amount = academic_session.transcript_fee
[7151]175        elif category == 'gown':
[8598]176            amount = academic_session.gown_fee
[13251]177        elif category == 'bed_allocation':
178            p_item = self.getAccommodationDetails(student)['bt']
179            amount = academic_session.booking_fee
[13283]180            # Add student union dues
181            stage = self.getAccommodationDetails(student)['bt']
182            stage = stage.split('_')[2]
183            if stage == 'fr':
184                amount += 500.0
[13309]185            elif stage == 'fi' and student[
186                'studycourse'].previous_verdict in ('A', 'B'):
[13296]187                amount += 300.0
[13283]188            else:
[13296]189                amount = 0.0
[13251]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
[7151]219        elif category == 'clearance':
[9796]220            p_item = student.certcode
221            if p_item is None:
[8598]222                return _('Study course data are incomplete.'), None
[13310]223            if student.faccode == 'JUPEB':
224                return _('No payment required.'), None
[11479]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:
[9346]234                amount = 45000.0
[7151]235        elif category == 'schoolfee':
[8598]236            try:
237                certificate = student['studycourse'].certificate
238                p_item = certificate.code
239            except (AttributeError, TypeError):
240                return _('Study course data are incomplete.'), None
[9152]241            if previous_session:
[9520]242                # Students can pay for previous sessions in all workflow states.
243                # Fresh students are excluded by the update method of the
244                # PreviousPaymentAddFormPage.
[9157]245                if previous_session == student['studycourse'].entry_session:
[9152]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)
[9006]250                else:
[9152]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)
[9513]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
[9520]265                    academic_session = self._getSessionConfiguration(p_session)
266                    if academic_session == None:
[9513]267                        return _(u'Session configuration object is not available.'), None
[9570]268
[9520]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.
[9570]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
[9513]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)
[9152]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)
[9520]287                    academic_session = self._getSessionConfiguration(p_session)
288                    if academic_session == None:
[9152]289                        return _(u'Session configuration object is not available.'), None
[9570]290
[9520]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.
[9570]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
[9152]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)
[9006]304            # Give 50% school fee discount to staff members.
305            if student.is_staff:
306                amount /= 2
[8598]307        if amount in (0.0, None):
[9520]308            return _('Amount could not be determined.'), None
[8676]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
[9727]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
[12566]318            # will be obsolete when Uniben returns to Kofa bed allocation.
[9727]319            category = 'hostel_maintenance'
[8676]320        # Create ticket.
[11644]321        if self.samePaymentMade(student, category, p_item, p_session):
322            return _('This type of payment has already been made.'), None
[11459]323        if self._isPaymentDisabled(p_session, category, student):
324            return _('Payment temporarily disabled.'), None
[8715]325        payment = createObject(u'waeup.StudentOnlinePayment')
[8950]326        timestamp = ("%d" % int(time()*10000))[1:]
[8598]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
[9152]332        payment.p_current = p_current
[8598]333        payment.amount_auth = amount
334        return None, payment
[7621]335
[9831]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
[11773]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
[8441]362    # Uniben prefix
[8413]363    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.