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

Last change on this file since 18152 was 18152, checked in by Henrik Bettermann, 16 months ago

Fresh students are in certain registration states.

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