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

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

Set provider_amt attribute.

  • Property svn:keywords set to Id
File size: 24.7 KB
Line 
1## $Id: utils.py 18332 2026-09-15 13:50:57Z 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        payment.p_id = "p%s" % timestamp
398        payment.p_category = category
399        payment.p_item = p_item
400        payment.p_session = p_session
401        payment.p_level = p_level
402        payment.p_current = p_current
403        payment.amount_auth = amount
404        payment.p_combi = combi
405        return None, payment
406
407    def setCDLPaymentDetails(self, category, student,
408            previous_session=None, previous_level=None, combi=[]):
409        """Create a payment ticket and set the payment data of a
410        student for the payment category specified.
411        """
412        p_item = u''
413        amount = 0.0
414        if previous_session:
415            if previous_session < student['studycourse'].entry_session:
416                return _('The previous session must not fall below '
417                         'your entry session.'), None
418            if category == 'schoolfee':
419                # School fee is always paid for the following session
420                if previous_session > student['studycourse'].current_session:
421                    return _('This is not a previous session.'), None
422            else:
423                if previous_session > student['studycourse'].current_session - 1:
424                    return _('This is not a previous session.'), None
425            p_session = previous_session
426            p_level = previous_level
427            p_current = False
428        else:
429            p_session = student['studycourse'].current_session
430            p_level = student['studycourse'].current_level
431            p_current = True
432            if category in list(self._all_required_payments) + [
433                'required_combi','schoolfee','schoolfee40','secondinstal'] \
434                and student.state == RETURNING:
435                # In case of school fee or required sundry fee payments the
436                # payment session is always next session if students are in
437                # state returning.
438                p_session, p_level = self.getReturningData(student)
439        academic_session = self._getSessionConfiguration(p_session)
440        if academic_session == None:
441            return _(u'Session configuration object is not available.'), None
442        # Determine fee.
443        if category in ('schoolfee', 'schoolfee40', 'secondinstal'):
444            rpm = self._requiredPaymentsMissing(student, p_session)
445            if rpm:
446                return rpm, None
447            try:
448                certificate = student['studycourse'].certificate
449                p_item = certificate.code
450            except (AttributeError, TypeError):
451                return _('Study course data are incomplete.'), None
452            if previous_session:
453                # Students can pay for previous sessions in all
454                # workflow states.  Fresh students are excluded by the
455                # update method of the PreviousPaymentAddFormPage.
456                if previous_level == 100:
457                    amount = getattr(certificate, 'school_fee_1', 0.0)
458                else:
459                    amount = getattr(certificate, 'school_fee_2', 0.0)
460                if category == 'schoolfee40':
461                    amount = 0.4*amount
462                elif category == 'secondinstal':
463                    amount = 0.6*amount
464            else:
465                if category == 'secondinstal':
466                    if student.is_fresh:
467                        amount = 0.6 * getattr(certificate, 'school_fee_1', 0.0)
468                    else:
469                        amount = 0.6 * getattr(certificate, 'school_fee_2', 0.0)
470                else:
471                    if student.state in (CLEARANCE, REQUESTED, CLEARED):
472                        amount = getattr(certificate, 'school_fee_1', 0.0)
473                    elif student.state == RETURNING:
474                        amount = getattr(certificate, 'school_fee_2', 0.0)
475                    elif student.is_postgrad and student.state == PAID:
476                        # Returning postgraduate students also pay for the
477                        # next session but their level always remains the
478                        # same.
479                        p_session += 1
480                        academic_session = self._getSessionConfiguration(p_session)
481                        if academic_session == None:
482                            return _(
483                                u'Session configuration object is not available.'
484                                ), None
485                        amount = getattr(certificate, 'school_fee_2', 0.0)
486                    if amount and category == 'schoolfee40':
487                        amount = 0.4*amount
488        elif category == 'clearance':
489            try:
490                p_item = student['studycourse'].certificate.code
491            except (AttributeError, TypeError):
492                return _('Study course data are incomplete.'), None
493            amount = academic_session.clearance_fee
494        elif category.startswith('cdlcourse'):
495            amount = academic_session.course_fee
496            number = int(category.strip('cdlcourse'))
497            amount *= number
498        elif category == 'combi' and combi:
499            categories = getUtility(IKofaUtils).COMBI_PAYMENT_CATEGORIES
500            for cat in combi:
501                fee_name = cat + '_fee'
502                cat_amount = getattr(academic_session, fee_name, 0.0)
503                if not cat_amount:
504                    return _('%s undefined.' % categories[cat]), None
505                amount += cat_amount
506                p_item += u'%s + ' % categories[cat]
507            p_item = p_item.strip(' + ')
508        else:
509            fee_name = category + '_fee'
510            amount = getattr(academic_session, fee_name, 0.0)
511        if amount in (0.0, None):
512            return _('Amount could not be determined.'), None
513        if self.samePaymentMade(student, category, p_item, p_session):
514            return _('This type of payment has already been made.'), None
515        if self._isPaymentDisabled(p_session, category, student):
516            return _('This category of payments has been disabled.'), None
517        payment = createObject(u'waeup.StudentOnlinePayment')
518        timestamp = ("%d" % int(time()*10000))[1:]
519        payment.p_id = "p%s" % timestamp
520        payment.p_category = category
521        payment.p_item = p_item
522        payment.p_session = p_session
523        payment.p_level = p_level
524        payment.p_current = p_current
525        payment.amount_auth = amount
526        payment.p_combi = combi
527        return None, payment
528
529    def setBalanceDetails(self, category, student,
530            balance_session, balance_level, balance_amount):
531        """Create a balance payment ticket and set the payment data
532        as selected by the student.
533        """
534        if category in ('schoolfee', 'schoolfee40', 'secondinstal') \
535            and balance_session > 2019:
536            rpm = self._requiredPaymentsMissing(student, balance_session)
537            if rpm:
538                return rpm, None
539        return super(
540            CustomStudentsUtils, self).setBalanceDetails(category, student,
541            balance_session, balance_level, balance_amount)
542
543    def constructMatricNumber(self, student):
544        """Fetch the matric number counter which fits the student and
545        construct the new matric number of the student.
546        """
547        next_integer = grok.getSite()['configuration'].next_matric_integer
548        if next_integer == 0:
549            return _('Matriculation number cannot be set.'), None
550        if not student.state in (
551            RETURNING, CLEARED, PAID, REGISTERED, VALIDATED):
552            return _('Matriculation number cannot be set.'), None
553        year = unicode(student.entry_session)[2:]
554        if grok.getSite().__name__ == 'iuokada-cdl':
555            return None, "%s/%04d/%s/CDL" % (year, next_integer, student.faccode)
556        return None, "%s/%06d/%s" % (year, next_integer, student.faccode)
Note: See TracBrowser for help on using the repository browser.