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

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

Add pay_item_id for JUPEB schoolfee payments.

  • Property svn:keywords set to Id
File size: 16.3 KB
RevLine 
[7419]1## $Id: utils.py 13333 2015-10-16 11:51:51Z 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
[13332]241
242            #####################################################
[13333]243            #if student.faccode == 'JUPEB':
244            #    return _('Payment temporarily disabled.'), None
[13332]245            #####################################################
246
247
[9152]248            if previous_session:
[9520]249                # Students can pay for previous sessions in all workflow states.
250                # Fresh students are excluded by the update method of the
251                # PreviousPaymentAddFormPage.
[9157]252                if previous_session == student['studycourse'].entry_session:
[9152]253                    if student.is_foreigner:
254                        amount = getattr(certificate, 'school_fee_3', 0.0)
255                    else:
256                        amount = getattr(certificate, 'school_fee_1', 0.0)
[9006]257                else:
[9152]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            else:
263                if student.state == CLEARED:
264                    if student.is_foreigner:
265                        amount = getattr(certificate, 'school_fee_3', 0.0)
266                    else:
267                        amount = getattr(certificate, 'school_fee_1', 0.0)
[9513]268                elif student.state in (PAID, REGISTERED, VALIDATED):
269                    p_session += 1
270                    # We don't know which level the student is paying for.
271                    p_level = None
[9520]272                    academic_session = self._getSessionConfiguration(p_session)
273                    if academic_session == None:
[9513]274                        return _(u'Session configuration object is not available.'), None
[9570]275
[9520]276                    # Students are only allowed to pay for the next session
277                    # if current session payment
278                    # has really been made, i.e. payment object exists.
[9570]279                    #if not self._paymentMade(
280                    #    student, student.current_session):
281                    #    return _('You have not yet paid your current/active' +
282                    #             ' session. Please use the previous session' +
283                    #             ' payment form first.'), None
284
[9513]285                    if student.is_foreigner:
286                        amount = getattr(certificate, 'school_fee_4', 0.0)
287                    else:
288                        amount = getattr(certificate, 'school_fee_2', 0.0)
[9152]289                elif student.state == RETURNING:
290                    # In case of returning school fee payment the payment session
291                    # and level contain the values of the session the student
292                    # has paid for.
293                    p_session, p_level = self.getReturningData(student)
[9520]294                    academic_session = self._getSessionConfiguration(p_session)
295                    if academic_session == None:
[9152]296                        return _(u'Session configuration object is not available.'), None
[9570]297
[9520]298                    # Students are only allowed to pay for the next session
299                    # if current session payment has really been made,
300                    # i.e. payment object exists and is paid.
[9570]301                    #if not self._paymentMade(
302                    #    student, student.current_session):
303                    #    return _('You have not yet paid your current/active' +
304                    #             ' session. Please use the previous session' +
305                    #             ' payment form first.'), None
306
[9152]307                    if student.is_foreigner:
308                        amount = getattr(certificate, 'school_fee_4', 0.0)
309                    else:
310                        amount = getattr(certificate, 'school_fee_2', 0.0)
[9006]311            # Give 50% school fee discount to staff members.
312            if student.is_staff:
313                amount /= 2
[8598]314        if amount in (0.0, None):
[9520]315            return _('Amount could not be determined.'), None
[8676]316        # Add session specific penalty fee.
317        if category == 'schoolfee' and student.is_postgrad:
318            amount += academic_session.penalty_pg
319        elif category == 'schoolfee':
320            amount += academic_session.penalty_ug
[9727]321        if category.startswith('tempmaint'):
322            p_item = getUtility(IKofaUtils).PAYMENT_CATEGORIES[category]
323            p_item = unicode(p_item)
324            # Now we change the category because tempmaint payments
[12566]325            # will be obsolete when Uniben returns to Kofa bed allocation.
[9727]326            category = 'hostel_maintenance'
[8676]327        # Create ticket.
[11644]328        if self.samePaymentMade(student, category, p_item, p_session):
329            return _('This type of payment has already been made.'), None
[11459]330        if self._isPaymentDisabled(p_session, category, student):
331            return _('Payment temporarily disabled.'), None
[8715]332        payment = createObject(u'waeup.StudentOnlinePayment')
[8950]333        timestamp = ("%d" % int(time()*10000))[1:]
[8598]334        payment.p_id = "p%s" % timestamp
335        payment.p_category = category
336        payment.p_item = p_item
337        payment.p_session = p_session
338        payment.p_level = p_level
[9152]339        payment.p_current = p_current
[8598]340        payment.amount_auth = amount
341        return None, payment
[7621]342
[9831]343    def maxCredits(self, studylevel):
344        """Return maximum credits.
345
346        """
347        studycourse = studylevel.__parent__
348        certificate = getattr(studycourse,'certificate', None)
349        current_level = studycourse.current_level
350        if None in (current_level, certificate):
351            return 0
352        end_level = certificate.end_level
353        if current_level >= end_level:
354            return 51
355        return 50
356
[11773]357    def clearance_disabled_message(self, student):
358        if student.is_postgrad:
359            return None
360        try:
361            session_config = grok.getSite()[
362                'configuration'][str(student.current_session)]
363        except KeyError:
364            return _('Session configuration object is not available.')
365        if not session_config.clearance_enabled:
366            return _('Clearance is disabled for this session.')
367        return None
368
[8441]369    # Uniben prefix
[8413]370    STUDENT_ID_PREFIX = u'B'
Note: See TracBrowser for help on using the repository browser.