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

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

Add folder payment_category.

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