source: main/kofacustom.iuokada/trunk/src/kofacustom/iuokada/students/utils.py @ 18330

Last change on this file since 18330 was 18330, checked in by Henrik Bettermann, 3 months ago

Add sundry payment category.

  • Property svn:keywords set to Id
File size: 25.2 KB
Line 
1## $Id: utils.py 18330 2026-09-15 10:02:13Z 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 copy import deepcopy
21from zope.component import createObject, getUtility
22from waeup.kofa.interfaces import (IKofaUtils,
23    ADMITTED, CLEARANCE, REQUESTED, CLEARED, RETURNING, PAID,
24    REGISTERED, VALIDATED)
25from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
26from kofacustom.iuokada.interfaces import MessageFactory as _
27
28class CustomStudentsUtils(NigeriaStudentsUtils):
29    """A collection of customized methods.
30
31    """
32
33    @property
34    def STUDENT_ID_PREFIX(self):
35        if grok.getSite().__name__ == 'iuokada-cdl':
36            return u'F'
37        return u'I'
38
39
40    SKIP_UPLOAD_VIEWLETS = (
41        'acceptanceletterupload', 'certificateupload'
42        )
43    # Maximum size of upload files in kB
44    MAX_KB = 500
45
46    #: A tuple containing the names of registration states in which changing of
47    #: passport pictures is allowed.
48
49    PORTRAIT_CHANGE_STATES = (ADMITTED, CLEARANCE,)
50
51    REQUIRED_PAYMENTS_FRESH_SCIENCE = {
52        'registration_fresh': 'Registration Fee (Fresh)',
53        'book': 'Book Deposit',
54        'develop': 'Development Fee',
55        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
56        'municipal_fresh': 'Fresh Students Municipal Fee',
57        'matric': 'Matriculation Fee',
58        'waecneco': 'WAEC/NECO Verification',
59        'jambver': 'JAMB Verification Fee',
60        'health_insurance': 'Student Health Insurance',
61        'id_card': 'I.D. Card',
62        'medical_screening': 'Medical Screening Fees',
63        'science': 'Science Bench Fee',
64        'endowment': 'Endowment Fund',
65        }
66
67    REQUIRED_PAYMENTS_FRESH_NON_SCIENCE = {
68        'registration_fresh': 'Registration Fee (Fresh)',
69        'book': 'Book Deposit',
70        'develop': 'Development Fee',
71        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
72        'municipal_fresh': 'Fresh Students Municipal Fee',
73        'matric': 'Matriculation Fee',
74        'waecneco': 'WAEC/NECO Verification',
75        'jambver': 'JAMB Verification Fee',
76        'health_insurance': 'Student Health Insurance',
77        'id_card': 'I.D. Card',
78        'medical_screening': 'Medical Screening Fees',
79        'endowment': 'Endowment Fund',
80        }
81
82    # all students (except PHM) returning
83    REQUIRED_PAYMENTS_RETURNING = {
84        'registration_return': 'Registration Fee (Returning)',
85        'book': 'Book Deposit',
86        'develop': 'Development Fee',
87        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
88        'municipal_returning': 'Returning Students Municipal Fee',
89        'health_insurance': 'Student Health Insurance',
90        'endowment': 'Endowment Fund',
91        }
92
93
94    # all students (except PHM) final year
95    REQUIRED_PAYMENTS_FINAL = {
96        'registration_return': 'Registration Fee (Returning)',
97        'book': 'Book Deposit',
98        'develop': 'Development Fee',
99        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
100        'municipal_returning': 'Returning Students Municipal Fee',
101        'health_insurance': 'Student Health Insurance',
102        'alumni': 'Alumni Fees',
103        'conv': 'Convocation Fees',
104        'grad_clearance': 'Clearance Fees',
105        'endowment': 'Endowment Fund',
106        }
107
108    # PHM returning students
109    REQUIRED_PAYMENTS_RETURNING_PHARMACY = {
110        'registration_return': 'Registration Fee (Returning)',
111        'book': 'Book Deposit',
112        'develop': 'Development Fee',
113        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
114        'municipal_returning': 'Returning Students Municipal Fee',
115        'health_insurance': 'Student Health Insurance',
116        'pharmlab': 'Pharmacy Lab Support Fee',
117        'endowment': 'Endowment Fund',
118        }
119
120    # PHM students final year
121    REQUIRED_PAYMENTS_FINAL_PHARMACY = {
122        'registration_return': 'Registration Fee (Returning)',
123        'book': 'Book Deposit',
124        'develop': 'Development Fee',
125        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
126        'municipal_returning': 'Returning Students Municipal Fee',
127        'health_insurance': 'Student Health Insurance',
128        'alumni': 'Alumni Fees',
129        'conv': 'Convocation Fees',
130        'grad_clearance': 'Clearance Fees',
131        'pharmlab': 'Pharmacy Lab Support Fee',
132        'endowment': 'Endowment Fund',
133        }
134
135    REQUIRED_PAYMENTS_PG = {
136        'pg_other': 'PG Other Charges',
137        }
138
139    def warnCreditsOOR(self, studylevel, course=None):
140        """Return message if credits are out of range. In the base
141        package only maximum credits is set.
142        """
143        max_credits = 60
144        end_level = getattr(studylevel.__parent__.certificate, 'end_level', None)
145        if end_level and studylevel.level >= end_level:
146            max_credits = 80
147        #if studylevel.certcode == 'LLB':
148        #    max_credits = 50
149        if studylevel.certcode == 'MBBSMED' and studylevel.level == 200:
150            max_credits = 100
151        if studylevel.certcode == 'MBBSMED' and studylevel.level == 300:
152            max_credits = 90
153        if course and studylevel.total_credits + course.credits > max_credits:
154            return _('Maximum credits exceeded.')
155        elif studylevel.total_credits > max_credits:
156            return _('Maximum credits exceeded.')
157        return
158
159    def _collect_required_payment_items(self, student):
160        if student.is_postgrad:
161            rp = self.REQUIRED_PAYMENTS_PG
162        elif student.is_fresh and student.state in (
163            ADMITTED, CLEARANCE, REQUESTED, CLEARED):
164            if student.faccode in ('ENG', 'HSC', 'NAS', 'PHM'):
165                rp = self.REQUIRED_PAYMENTS_FRESH_SCIENCE
166            else:
167                rp = self.REQUIRED_PAYMENTS_FRESH_NON_SCIENCE
168        elif student.faccode == 'PHM' and student.is_final:
169            rp = self.REQUIRED_PAYMENTS_FINAL_PHARMACY
170        elif student.faccode == 'PHM':
171            rp = self.REQUIRED_PAYMENTS_RETURNING_PHARMACY
172        elif student.is_final:
173            rp = self.REQUIRED_PAYMENTS_FINAL
174        else:
175            rp = self.REQUIRED_PAYMENTS_RETURNING
176        return rp
177
178    def _requiredPaymentsMissing(self, student, session):
179        # disabled on 03/04/25
180        # reenabled on 08/04/25
181        if session < 2025:
182            return
183        # Part time, jupeb, medical, and PG students do not pay sundry.
184        if student.is_jupeb or student.current_mode.endswith('_pt') \
185            or student.is_postgrad \
186            or student.certcode in ('MBBSMED',):
187            return
188        # Only in states, which allow to pay school fees, sundry payments
189        # are required
190        if student.state not in (CLEARANCE, REQUESTED, CLEARED, RETURNING):
191            return
192           
193        # Has the required combi payment been made?
194        for ticket in student['payments'].values():
195            if ticket.p_category == 'required_combi'and \
196                ticket.p_session == session and \
197                ticket.p_state == 'paid':
198                return
199
200        # If not, check single payments (no longer possible)
201        rp = self._collect_required_payment_items(student)
202        cats_missing = deepcopy(rp)
203        combi_cats = getUtility(IKofaUtils).PAYMENT_CATEGORIES
204        if len(student['payments']):
205            for category in rp.keys():
206                for ticket in student['payments'].values():
207                    if ticket.p_state == 'paid' and \
208                        ticket.p_category == category and \
209                        ticket.p_session == session:
210                        del cats_missing[category]
211                    elif ticket.p_state == 'paid' and \
212                        ticket.p_category == 'combi' and \
213                        combi_cats[category] in ticket.p_item and \
214                        ticket.p_session == session:
215                        del cats_missing[category]
216                if not cats_missing:
217                    return
218        #return "%s must be paid before Tution Fee." % ', '.join(
219        #    cats_missing.values())
220
221        return "Sundry charges must be paid before tuition."
222
223    @property
224    def _all_required_payments(self):
225        return set(
226            self.REQUIRED_PAYMENTS_PG.keys()
227            + self.REQUIRED_PAYMENTS_FRESH_SCIENCE.keys()
228            + self.REQUIRED_PAYMENTS_FRESH_NON_SCIENCE.keys()
229            + self.REQUIRED_PAYMENTS_FINAL_PHARMACY.keys()
230            + self.REQUIRED_PAYMENTS_RETURNING_PHARMACY.keys()
231            + self.REQUIRED_PAYMENTS_FINAL.keys()
232            + self.REQUIRED_PAYMENTS_RETURNING.keys()
233            )
234
235    def samePaymentMade(self, student, category, p_item, p_session):
236        if category.startswith('resit'):
237            return False
238        if category == 'combi':
239            return False
240        for key in student['payments'].keys():
241            ticket = student['payments'][key]
242            if ticket.p_state == 'paid' and\
243               ticket.p_category == category and \
244               ticket.p_item != 'Balance' and \
245               ticket.p_item == p_item and \
246               ticket.p_session == p_session:
247                  return True
248        return False
249
250    def setPaymentDetails(self, category, student,
251            previous_session=None, previous_level=None, combi=[]):
252        """Create a payment ticket and set the payment data of a
253        student for the payment category specified.
254        """
255        if grok.getSite().__name__ == 'iuokada-cdl':
256            return self.setCDLPaymentDetails(category, student,
257                previous_session, previous_level, combi)
258        p_item = u''
259        amount = 0.0
260        if previous_session:
261            if previous_session < student['studycourse'].entry_session:
262                return _('The previous session must not fall below '
263                         'your entry session.'), None
264            if category == 'schoolfee':
265                # School fee is always paid for the following session
266                if previous_session > student['studycourse'].current_session:
267                    return _('This is not a previous session.'), None
268            else:
269                if previous_session > student['studycourse'].current_session - 1:
270                    return _('This is not a previous session.'), None
271            p_session = previous_session
272            p_level = previous_level
273            p_current = False
274        else:
275            p_session = student['studycourse'].current_session
276            p_level = student['studycourse'].current_level
277            p_current = True
278            if category in list(self._all_required_payments) + [
279                'required_combi','schoolfee','schoolfee40','secondinstal'] \
280                and student.state == RETURNING:
281                # In case of school fee or required sundry fee payments the
282                # payment session is always next session if students are in
283                # state returning.
284                p_session, p_level = self.getReturningData(student)
285        academic_session = self._getSessionConfiguration(p_session)
286        if academic_session == None:
287            return _(u'Session configuration object is not available.'), None
288        # Determine fee.
289        if category in ('schoolfee', 'schoolfee40', 'secondinstal'):
290            rpm = self._requiredPaymentsMissing(student, p_session)
291            if rpm:
292                return rpm, None
293            try:
294                certificate = student['studycourse'].certificate
295                p_item = certificate.code
296            except (AttributeError, TypeError):
297                return _('Study course data are incomplete.'), None
298            if previous_session:
299                # Students can pay for previous sessions in all
300                # workflow states.  Fresh students are excluded by the
301                # update method of the PreviousPaymentAddFormPage.
302                if previous_level == 100:
303                    amount = getattr(certificate, 'school_fee_1', 0.0)
304                else:
305                    amount = getattr(certificate, 'school_fee_2', 0.0)
306                if category == 'schoolfee40':
307                    amount = 0.4*amount
308                elif category == 'secondinstal':
309                    amount = 0.6*amount
310            else:
311                if category == 'secondinstal':
312                    if student.is_fresh:
313                        amount = 0.6 * getattr(certificate, 'school_fee_1', 0.0)
314                    else:
315                        amount = 0.6 * getattr(certificate, 'school_fee_2', 0.0)
316                else:
317                    if student.state in (CLEARANCE, REQUESTED, CLEARED):
318                        amount = getattr(certificate, 'school_fee_1', 0.0)
319                    elif student.state == RETURNING:
320                        amount = getattr(certificate, 'school_fee_2', 0.0)
321                    elif student.is_postgrad and student.state == PAID:
322                        # Returning postgraduate students also pay for the
323                        # next session but their level always remains the
324                        # same.
325                        p_session += 1
326                        academic_session = self._getSessionConfiguration(p_session)
327                        if academic_session == None:
328                            return _(
329                                u'Session configuration object is not available.'
330                                ), None
331                        amount = getattr(certificate, 'school_fee_2', 0.0)
332                    if amount and category == 'schoolfee40':
333                        amount = 0.4*amount
334        elif category == 'clearance':
335            try:
336                p_item = student['studycourse'].certificate.code
337            except (AttributeError, TypeError):
338                return _('Study course data are incomplete.'), None
339            amount = academic_session.clearance_fee
340            if student.is_postgrad:
341                amount *= 0.5
342            if student.certcode in ('DPHARM','MBBSMED','BSCNNUR','LLB'):
343                amount += 200000
344        elif category.startswith('resit'):
345            amount = academic_session.resit_fee
346            number = int(category.strip('resit'))
347            amount *= number
348        #elif category == 'bed_allocation':
349        #    p_item = self.getAccommodationDetails(student)['bt']
350        #    amount = academic_session.booking_fee
351        #elif category == 'hostel_maintenance':
352        #    amount = 0.0
353        #    bedticket = student['accommodation'].get(
354        #        str(student.current_session), None)
355        #    if bedticket is not None and bedticket.bed is not None:
356        #        p_item = bedticket.bed_coordinates
357        #        if bedticket.bed.__parent__.maint_fee > 0:
358        #            amount = bedticket.bed.__parent__.maint_fee
359        #        else:
360        #            # fallback
361        #            amount = academic_session.maint_fee
362        #    else:
363        #        return _(u'No bed allocated.'), None
364        elif category == 'combi' and combi:
365            categories = getUtility(IKofaUtils).COMBI_PAYMENT_CATEGORIES
366            for cat in combi:
367                fee_name = cat + '_fee'
368                cat_amount = getattr(academic_session, fee_name, 0.0)
369                if not cat_amount:
370                    return _('%s undefined.' % categories[cat]), None
371                amount += cat_amount
372                p_item += u'%s + ' % categories[cat]
373            p_item = p_item.strip(' + ')
374
375        elif category == 'required_combi':
376            rp = self._collect_required_payment_items(student)
377            for cat in rp.keys():
378                fee_name = cat + '_fee'
379                cat_amount = getattr(academic_session, fee_name, 0.0)
380                if not cat_amount:
381                    return _('%s undefined.' % rp[cat]), None
382                amount += cat_amount
383                p_item += u'%s + ' % rp[cat]
384            p_item = p_item.strip(' + ')
385
386        else:
387            fee_name = category + '_fee'
388            amount = getattr(academic_session, fee_name, 0.0)
389        if amount in (0.0, None):
390            return _('Amount could not be determined.'), None
391        if self.samePaymentMade(student, category, p_item, p_session):
392            return _('This type of payment has already been made.'), None
393        if self._isPaymentDisabled(p_session, category, student):
394            return _('This category of payments has been disabled.'), None
395        payment = createObject(u'waeup.StudentOnlinePayment')
396        timestamp = ("%d" % int(time()*10000))[1:]
397        if category in (
398            'registration', 'required_combi', 'pg_other', 'jupeb_reg'):
399            payment.provider_amt = 5000.0
400        if category in (
401            'schoolfee', 'schoolfee40') and student.is_jupeb:
402            payment.provider_amt = 5000.0
403        payment.p_id = "p%s" % timestamp
404        payment.p_category = category
405        payment.p_item = p_item
406        payment.p_session = p_session
407        payment.p_level = p_level
408        payment.p_current = p_current
409        payment.amount_auth = amount
410        payment.p_combi = combi
411        return None, payment
412
413    def setCDLPaymentDetails(self, category, student,
414            previous_session=None, previous_level=None, combi=[]):
415        """Create a payment ticket and set the payment data of a
416        student for the payment category specified.
417        """
418        p_item = u''
419        amount = 0.0
420        if previous_session:
421            if previous_session < student['studycourse'].entry_session:
422                return _('The previous session must not fall below '
423                         'your entry session.'), None
424            if category == 'schoolfee':
425                # School fee is always paid for the following session
426                if previous_session > student['studycourse'].current_session:
427                    return _('This is not a previous session.'), None
428            else:
429                if previous_session > student['studycourse'].current_session - 1:
430                    return _('This is not a previous session.'), None
431            p_session = previous_session
432            p_level = previous_level
433            p_current = False
434        else:
435            p_session = student['studycourse'].current_session
436            p_level = student['studycourse'].current_level
437            p_current = True
438            if category in list(self._all_required_payments) + [
439                'required_combi','schoolfee','schoolfee40','secondinstal'] \
440                and student.state == RETURNING:
441                # In case of school fee or required sundry fee payments the
442                # payment session is always next session if students are in
443                # state returning.
444                p_session, p_level = self.getReturningData(student)
445        academic_session = self._getSessionConfiguration(p_session)
446        if academic_session == None:
447            return _(u'Session configuration object is not available.'), None
448        # Determine fee.
449        if category in ('schoolfee', 'schoolfee40', 'secondinstal'):
450            rpm = self._requiredPaymentsMissing(student, p_session)
451            if rpm:
452                return rpm, None
453            try:
454                certificate = student['studycourse'].certificate
455                p_item = certificate.code
456            except (AttributeError, TypeError):
457                return _('Study course data are incomplete.'), None
458            if previous_session:
459                # Students can pay for previous sessions in all
460                # workflow states.  Fresh students are excluded by the
461                # update method of the PreviousPaymentAddFormPage.
462                if previous_level == 100:
463                    amount = getattr(certificate, 'school_fee_1', 0.0)
464                else:
465                    amount = getattr(certificate, 'school_fee_2', 0.0)
466                if category == 'schoolfee40':
467                    amount = 0.4*amount
468                elif category == 'secondinstal':
469                    amount = 0.6*amount
470            else:
471                if category == 'secondinstal':
472                    if student.is_fresh:
473                        amount = 0.6 * getattr(certificate, 'school_fee_1', 0.0)
474                    else:
475                        amount = 0.6 * getattr(certificate, 'school_fee_2', 0.0)
476                else:
477                    if student.state in (CLEARANCE, REQUESTED, CLEARED):
478                        amount = getattr(certificate, 'school_fee_1', 0.0)
479                    elif student.state == RETURNING:
480                        amount = getattr(certificate, 'school_fee_2', 0.0)
481                    elif student.is_postgrad and student.state == PAID:
482                        # Returning postgraduate students also pay for the
483                        # next session but their level always remains the
484                        # same.
485                        p_session += 1
486                        academic_session = self._getSessionConfiguration(p_session)
487                        if academic_session == None:
488                            return _(
489                                u'Session configuration object is not available.'
490                                ), None
491                        amount = getattr(certificate, 'school_fee_2', 0.0)
492                    if amount and category == 'schoolfee40':
493                        amount = 0.4*amount
494        elif category == 'clearance':
495            try:
496                p_item = student['studycourse'].certificate.code
497            except (AttributeError, TypeError):
498                return _('Study course data are incomplete.'), None
499            amount = academic_session.clearance_fee
500        elif category.startswith('cdlcourse'):
501            amount = academic_session.course_fee
502            number = int(category.strip('cdlcourse'))
503            amount *= number
504        elif category == 'combi' and combi:
505            categories = getUtility(IKofaUtils).COMBI_PAYMENT_CATEGORIES
506            for cat in combi:
507                fee_name = cat + '_fee'
508                cat_amount = getattr(academic_session, fee_name, 0.0)
509                if not cat_amount:
510                    return _('%s undefined.' % categories[cat]), None
511                amount += cat_amount
512                p_item += u'%s + ' % categories[cat]
513            p_item = p_item.strip(' + ')
514        else:
515            fee_name = category + '_fee'
516            amount = getattr(academic_session, fee_name, 0.0)
517        if amount in (0.0, None):
518            return _('Amount could not be determined.'), None
519        if self.samePaymentMade(student, category, p_item, p_session):
520            return _('This type of payment has already been made.'), None
521        if self._isPaymentDisabled(p_session, category, student):
522            return _('This category of payments has been disabled.'), None
523        payment = createObject(u'waeup.StudentOnlinePayment')
524        timestamp = ("%d" % int(time()*10000))[1:]
525        if category in (
526            'registration', 'required_combi', 'pg_other', 'jupeb_reg'):
527            payment.provider_amt = 5000.0
528        if category in (
529            'schoolfee', 'schoolfee40') and student.is_jupeb:
530            payment.provider_amt = 5000.0
531        payment.p_id = "p%s" % timestamp
532        payment.p_category = category
533        payment.p_item = p_item
534        payment.p_session = p_session
535        payment.p_level = p_level
536        payment.p_current = p_current
537        payment.amount_auth = amount
538        payment.p_combi = combi
539        return None, payment
540
541    def setBalanceDetails(self, category, student,
542            balance_session, balance_level, balance_amount):
543        """Create a balance payment ticket and set the payment data
544        as selected by the student.
545        """
546        if category in ('schoolfee', 'schoolfee40', 'secondinstal') \
547            and balance_session > 2019:
548            rpm = self._requiredPaymentsMissing(student, balance_session)
549            if rpm:
550                return rpm, None
551        return super(
552            CustomStudentsUtils, self).setBalanceDetails(category, student,
553            balance_session, balance_level, balance_amount)
554
555    def constructMatricNumber(self, student):
556        """Fetch the matric number counter which fits the student and
557        construct the new matric number of the student.
558        """
559        next_integer = grok.getSite()['configuration'].next_matric_integer
560        if next_integer == 0:
561            return _('Matriculation number cannot be set.'), None
562        if not student.state in (
563            RETURNING, CLEARED, PAID, REGISTERED, VALIDATED):
564            return _('Matriculation number cannot be set.'), None
565        year = unicode(student.entry_session)[2:]
566        if grok.getSite().__name__ == 'iuokada-cdl':
567            return None, "%s/%04d/%s/CDL" % (year, next_integer, student.faccode)
568        return None, "%s/%06d/%s" % (year, next_integer, student.faccode)
Note: See TracBrowser for help on using the repository browser.