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

Last change on this file since 18236 was 18236, checked in by Henrik Bettermann, 10 months ago

Fix setCDLPaymentDetails.

  • Property svn:keywords set to Id
File size: 25.0 KB
Line 
1## $Id: utils.py 18236 2026-01-29 11:52:47Z 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        }
65
66    REQUIRED_PAYMENTS_FRESH_NON_SCIENCE = {
67        'registration_fresh': 'Registration Fee (Fresh)',
68        'book': 'Book Deposit',
69        'develop': 'Development Fee',
70        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
71        'municipal_fresh': 'Fresh Students Municipal Fee',
72        'matric': 'Matriculation Fee',
73        'waecneco': 'WAEC/NECO Verification',
74        'jambver': 'JAMB Verification Fee',
75        'health_insurance': 'Student Health Insurance',
76        'id_card': 'I.D. Card',
77        'medical_screening': 'Medical Screening Fees',
78        }
79
80    # all students (except PHM) returning
81    REQUIRED_PAYMENTS_RETURNING = {
82        'registration_return': 'Registration Fee (Returning)',
83        'book': 'Book Deposit',
84        'develop': 'Development Fee',
85        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
86        'municipal_returning': 'Returning Students Municipal Fee',
87        'health_insurance': 'Student Health Insurance',
88        }
89
90
91    # all students (except PHM) final year
92    REQUIRED_PAYMENTS_FINAL = {
93        'registration_return': 'Registration Fee (Returning)',
94        'book': 'Book Deposit',
95        'develop': 'Development Fee',
96        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
97        'municipal_returning': 'Returning Students Municipal Fee',
98        'health_insurance': 'Student Health Insurance',
99        'alumni': 'Alumni Fees',
100        'conv': 'Convocation Fees',
101        'grad_clearance': 'Clearance Fees',
102        }
103
104    # PHM returning students
105    REQUIRED_PAYMENTS_RETURNING_PHARMACY = {
106        'registration_return': 'Registration Fee (Returning)',
107        'book': 'Book Deposit',
108        'develop': 'Development Fee',
109        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
110        'municipal_returning': 'Returning Students Municipal Fee',
111        'health_insurance': 'Student Health Insurance',
112        'pharmlab': 'Pharmacy Lab Support Fee',
113        }
114
115    # PHM students final year
116    REQUIRED_PAYMENTS_FINAL_PHARMACY = {
117        'registration_return': 'Registration Fee (Returning)',
118        'book': 'Book Deposit',
119        'develop': 'Development Fee',
120        'parentsconsult': 'Parents Consultative Forum (PCF) Fee',
121        'municipal_returning': 'Returning Students Municipal Fee',
122        'health_insurance': 'Student Health Insurance',
123        'alumni': 'Alumni Fees',
124        'conv': 'Convocation Fees',
125        'grad_clearance': 'Clearance Fees',
126        'pharmlab': 'Pharmacy Lab Support Fee',
127        }
128
129    REQUIRED_PAYMENTS_PG = {
130        'pg_other': 'PG Other Charges',
131        }
132
133    def warnCreditsOOR(self, studylevel, course=None):
134        """Return message if credits are out of range. In the base
135        package only maximum credits is set.
136        """
137        max_credits = 60
138        end_level = getattr(studylevel.__parent__.certificate, 'end_level', None)
139        if end_level and studylevel.level >= end_level:
140            max_credits = 80
141        #if studylevel.certcode == 'LLB':
142        #    max_credits = 50
143        if studylevel.certcode == 'MBBSMED' and studylevel.level == 200:
144            max_credits = 100
145        if studylevel.certcode == 'MBBSMED' and studylevel.level == 300:
146            max_credits = 90
147        if course and studylevel.total_credits + course.credits > max_credits:
148            return _('Maximum credits exceeded.')
149        elif studylevel.total_credits > max_credits:
150            return _('Maximum credits exceeded.')
151        return
152
153    def _collect_required_payment_items(self, student):
154        if student.is_postgrad:
155            rp = self.REQUIRED_PAYMENTS_PG
156        elif student.is_fresh and student.state in (
157            ADMITTED, CLEARANCE, REQUESTED, CLEARED):
158            if student.faccode in ('ENG', 'HSC', 'NAS', 'PHM'):
159                rp = self.REQUIRED_PAYMENTS_FRESH_SCIENCE
160            else:
161                rp = self.REQUIRED_PAYMENTS_FRESH_NON_SCIENCE
162        elif student.faccode == 'PHM' and student.is_final:
163            rp = self.REQUIRED_PAYMENTS_FINAL_PHARMACY
164        elif student.faccode == 'PHM':
165            rp = self.REQUIRED_PAYMENTS_RETURNING_PHARMACY
166        elif student.is_final:
167            rp = self.REQUIRED_PAYMENTS_FINAL
168        else:
169            rp = self.REQUIRED_PAYMENTS_RETURNING
170        return rp
171
172    def _requiredPaymentsMissing(self, student, session):
173        # disabled on 03/04/25
174        # reenabled on 08/04/25
175        if session < 2025:
176            return
177        # Part time, jupeb, medical, and PG students do not pay sundry.
178        if student.is_jupeb or student.current_mode.endswith('_pt') \
179            or student.is_postgrad \
180            or student.certcode in ('MBBSMED',):
181            return
182        # Only in states, which allow to pay school fees, sundry payments
183        # are required
184        if student.state not in (CLEARANCE, REQUESTED, CLEARED, RETURNING):
185            return
186           
187        # Has the required combi payment been made?
188        for ticket in student['payments'].values():
189            if ticket.p_category == 'required_combi'and \
190                ticket.p_session == session and \
191                ticket.p_state == 'paid':
192                return
193
194        # If not, check single payments (no longer possible)
195        rp = self._collect_required_payment_items(student)
196        cats_missing = deepcopy(rp)
197        combi_cats = getUtility(IKofaUtils).PAYMENT_CATEGORIES
198        if len(student['payments']):
199            for category in rp.keys():
200                for ticket in student['payments'].values():
201                    if ticket.p_state == 'paid' and \
202                        ticket.p_category == category and \
203                        ticket.p_session == session:
204                        del cats_missing[category]
205                    elif ticket.p_state == 'paid' and \
206                        ticket.p_category == 'combi' and \
207                        combi_cats[category] in ticket.p_item and \
208                        ticket.p_session == session:
209                        del cats_missing[category]
210                if not cats_missing:
211                    return
212        #return "%s must be paid before Tution Fee." % ', '.join(
213        #    cats_missing.values())
214
215        return "Sundry charges must be paid before tuition."
216
217    @property
218    def _all_required_payments(self):
219        return set(
220            self.REQUIRED_PAYMENTS_PG.keys()
221            + self.REQUIRED_PAYMENTS_FRESH_SCIENCE.keys()
222            + self.REQUIRED_PAYMENTS_FRESH_NON_SCIENCE.keys()
223            + self.REQUIRED_PAYMENTS_FINAL_PHARMACY.keys()
224            + self.REQUIRED_PAYMENTS_RETURNING_PHARMACY.keys()
225            + self.REQUIRED_PAYMENTS_FINAL.keys()
226            + self.REQUIRED_PAYMENTS_RETURNING.keys()
227            )
228
229    def samePaymentMade(self, student, category, p_item, p_session):
230        if category.startswith('resit'):
231            return False
232        if category == 'combi':
233            return False
234        for key in student['payments'].keys():
235            ticket = student['payments'][key]
236            if ticket.p_state == 'paid' and\
237               ticket.p_category == category and \
238               ticket.p_item != 'Balance' and \
239               ticket.p_item == p_item and \
240               ticket.p_session == p_session:
241                  return True
242        return False
243
244    def setPaymentDetails(self, category, student,
245            previous_session=None, previous_level=None, combi=[]):
246        """Create a payment ticket and set the payment data of a
247        student for the payment category specified.
248        """
249        if grok.getSite().__name__ == 'iuokada-cdl':
250            return self.setCDLPaymentDetails(category, student,
251                previous_session, previous_level, combi)
252        p_item = u''
253        amount = 0.0
254        if previous_session:
255            if previous_session < student['studycourse'].entry_session:
256                return _('The previous session must not fall below '
257                         'your entry session.'), None
258            if category == 'schoolfee':
259                # School fee is always paid for the following session
260                if previous_session > student['studycourse'].current_session:
261                    return _('This is not a previous session.'), None
262            else:
263                if previous_session > student['studycourse'].current_session - 1:
264                    return _('This is not a previous session.'), None
265            p_session = previous_session
266            p_level = previous_level
267            p_current = False
268        else:
269            p_session = student['studycourse'].current_session
270            p_level = student['studycourse'].current_level
271            p_current = True
272            if category in list(self._all_required_payments) + [
273                'required_combi','schoolfee','schoolfee40','secondinstal'] \
274                and student.state == RETURNING:
275                # In case of school fee or required sundry fee payments the
276                # payment session is always next session if students are in
277                # state returning.
278                p_session, p_level = self.getReturningData(student)
279        academic_session = self._getSessionConfiguration(p_session)
280        if academic_session == None:
281            return _(u'Session configuration object is not available.'), None
282        # Determine fee.
283        if category in ('schoolfee', 'schoolfee40', 'secondinstal'):
284            rpm = self._requiredPaymentsMissing(student, p_session)
285            if rpm:
286                return rpm, None
287            try:
288                certificate = student['studycourse'].certificate
289                p_item = certificate.code
290            except (AttributeError, TypeError):
291                return _('Study course data are incomplete.'), None
292            if previous_session:
293                # Students can pay for previous sessions in all
294                # workflow states.  Fresh students are excluded by the
295                # update method of the PreviousPaymentAddFormPage.
296                if previous_level == 100:
297                    amount = getattr(certificate, 'school_fee_1', 0.0)
298                else:
299                    amount = getattr(certificate, 'school_fee_2', 0.0)
300                if category == 'schoolfee40':
301                    amount = 0.4*amount
302                elif category == 'secondinstal':
303                    amount = 0.6*amount
304            else:
305                if category == 'secondinstal':
306                    if student.is_fresh:
307                        amount = 0.6 * getattr(certificate, 'school_fee_1', 0.0)
308                    else:
309                        amount = 0.6 * getattr(certificate, 'school_fee_2', 0.0)
310                else:
311                    if student.state in (CLEARANCE, REQUESTED, CLEARED):
312                        amount = getattr(certificate, 'school_fee_1', 0.0)
313                    elif student.state == RETURNING:
314                        amount = getattr(certificate, 'school_fee_2', 0.0)
315                    elif student.is_postgrad and student.state == PAID:
316                        # Returning postgraduate students also pay for the
317                        # next session but their level always remains the
318                        # same.
319                        p_session += 1
320                        academic_session = self._getSessionConfiguration(p_session)
321                        if academic_session == None:
322                            return _(
323                                u'Session configuration object is not available.'
324                                ), None
325                        amount = getattr(certificate, 'school_fee_2', 0.0)
326                    if amount and category == 'schoolfee40':
327                        amount = 0.4*amount
328        elif category == 'clearance':
329            try:
330                p_item = student['studycourse'].certificate.code
331            except (AttributeError, TypeError):
332                return _('Study course data are incomplete.'), None
333            amount = academic_session.clearance_fee
334            if student.is_postgrad:
335                amount *= 0.5
336            if student.certcode in ('DPHARM','MBBSMED','BSCNNUR','LLB'):
337                amount += 200000
338        elif category.startswith('resit'):
339            amount = academic_session.resit_fee
340            number = int(category.strip('resit'))
341            amount *= number
342        #elif category == 'bed_allocation':
343        #    p_item = self.getAccommodationDetails(student)['bt']
344        #    amount = academic_session.booking_fee
345        #elif category == 'hostel_maintenance':
346        #    amount = 0.0
347        #    bedticket = student['accommodation'].get(
348        #        str(student.current_session), None)
349        #    if bedticket is not None and bedticket.bed is not None:
350        #        p_item = bedticket.bed_coordinates
351        #        if bedticket.bed.__parent__.maint_fee > 0:
352        #            amount = bedticket.bed.__parent__.maint_fee
353        #        else:
354        #            # fallback
355        #            amount = academic_session.maint_fee
356        #    else:
357        #        return _(u'No bed allocated.'), None
358        elif category == 'combi' and combi:
359            categories = getUtility(IKofaUtils).COMBI_PAYMENT_CATEGORIES
360            for cat in combi:
361                fee_name = cat + '_fee'
362                cat_amount = getattr(academic_session, fee_name, 0.0)
363                if not cat_amount:
364                    return _('%s undefined.' % categories[cat]), None
365                amount += cat_amount
366                p_item += u'%s + ' % categories[cat]
367            p_item = p_item.strip(' + ')
368
369        elif category == 'required_combi':
370            rp = self._collect_required_payment_items(student)
371            for cat in rp.keys():
372                fee_name = cat + '_fee'
373                cat_amount = getattr(academic_session, fee_name, 0.0)
374                if not cat_amount:
375                    return _('%s undefined.' % rp[cat]), None
376                amount += cat_amount
377                p_item += u'%s + ' % rp[cat]
378            p_item = p_item.strip(' + ')
379
380        else:
381            fee_name = category + '_fee'
382            amount = getattr(academic_session, fee_name, 0.0)
383        if amount in (0.0, None):
384            return _('Amount could not be determined.'), None
385        if self.samePaymentMade(student, category, p_item, p_session):
386            return _('This type of payment has already been made.'), None
387        if self._isPaymentDisabled(p_session, category, student):
388            return _('This category of payments has been disabled.'), None
389        payment = createObject(u'waeup.StudentOnlinePayment')
390        timestamp = ("%d" % int(time()*10000))[1:]
391        if category in (
392            'registration', 'required_combi', 'pg_other', 'jupeb_reg'):
393            payment.provider_amt = 5000.0
394        if category in (
395            'schoolfee', 'schoolfee40') and student.is_jupeb:
396            payment.provider_amt = 5000.0
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        if category in (
520            'registration', 'required_combi', 'pg_other', 'jupeb_reg'):
521            payment.provider_amt = 5000.0
522        if category in (
523            'schoolfee', 'schoolfee40') and student.is_jupeb:
524            payment.provider_amt = 5000.0
525        payment.p_id = "p%s" % timestamp
526        payment.p_category = category
527        payment.p_item = p_item
528        payment.p_session = p_session
529        payment.p_level = p_level
530        payment.p_current = p_current
531        payment.amount_auth = amount
532        payment.p_combi = combi
533        return None, payment
534
535    def setBalanceDetails(self, category, student,
536            balance_session, balance_level, balance_amount):
537        """Create a balance payment ticket and set the payment data
538        as selected by the student.
539        """
540        if category in ('schoolfee', 'schoolfee40', 'secondinstal') \
541            and balance_session > 2019:
542            rpm = self._requiredPaymentsMissing(student, balance_session)
543            if rpm:
544                return rpm, None
545        return super(
546            CustomStudentsUtils, self).setBalanceDetails(category, student,
547            balance_session, balance_level, balance_amount)
548
549    def constructMatricNumber(self, student):
550        """Fetch the matric number counter which fits the student and
551        construct the new matric number of the student.
552        """
553        next_integer = grok.getSite()['configuration'].next_matric_integer
554        if next_integer == 0:
555            return _('Matriculation number cannot be set.'), None
556        if not student.state in (
557            RETURNING, CLEARED, PAID, REGISTERED, VALIDATED):
558            return _('Matriculation number cannot be set.'), None
559        year = unicode(student.entry_session)[2:]
560        if grok.getSite().__name__ == 'iuokada-cdl':
561            return None, "%s/%04d/%s/CDL" % (year, next_integer, student.faccode)
562        return None, "%s/%06d/%s" % (year, next_integer, student.faccode)
Note: See TracBrowser for help on using the repository browser.