source: main/waeup.aaue/trunk/src/waeup/aaue/students/studylevel.py @ 18158

Last change on this file since 18158 was 18158, checked in by Henrik Bettermann, 15 months ago

Round CGPA.

  • Property svn:keywords set to Id
File size: 20.3 KB
RevLine 
[8326]1## $Id: studylevel.py 18158 2025-08-24 15:09:48Z henrik $
2##
3## Copyright (C) 2012 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##
18"""
19Container which holds the data of a student study level
20and contains the course tickets.
21"""
22import grok
[13036]23import pytz
[18158]24import pytz
25import decimal
[13036]26from datetime import datetime
[8326]27from zope.component.interfaces import IFactory
[18158]28from zope.component import createObject, getUtility
[8326]29from zope.interface import implementedBy
30from waeup.kofa.utils.helpers import attrs_to_fields
[18158]31from waeup.kofa.interfaces import (
32    RETURNING, VALIDATED, REGISTERED, PAID, IKofaUtils)
[14227]33from waeup.kofa.students.browser import TicketError
[8326]34from waeup.kofa.students.studylevel import (
35    StudentStudyLevel, CourseTicket,
36    CourseTicketFactory, StudentStudyLevelFactory)
[14075]37from waeup.kofa.students.interfaces import IStudentNavigation, ICourseTicket
[8444]38from waeup.aaue.students.interfaces import (
[8867]39    ICustomStudentStudyLevel, ICustomCourseTicket)
[14663]40from waeup.aaue.students.utils import MINIMUM_UNITS_THRESHOLD
[14248]41from waeup.aaue.interfaces import MessageFactory as _
[8326]42
43
44class CustomStudentStudyLevel(StudentStudyLevel):
45    """This is a container for course tickets.
46    """
47    grok.implements(ICustomStudentStudyLevel, IStudentNavigation)
48    grok.provides(ICustomStudentStudyLevel)
49
[9914]50    @property
51    def total_credits_s1(self):
52        total = 0
53        for ticket in self.values():
[14576]54            if ticket.semester == 1 and not ticket.outstanding:
[9914]55                total += ticket.credits
56        return total
57
58    @property
59    def total_credits_s2(self):
60        total = 0
61        for ticket in self.values():
[14576]62            if ticket.semester == 2 and not ticket.outstanding:
[9914]63                total += ticket.credits
64        return total
65
[10443]66    @property
[13834]67    def gpa_params(self):
68        """Calculate gpa parameters for this level.
69        """
70        credits_weighted = 0.0
71        credits_counted = 0
72        level_gpa = 0.0
73        for ticket in self.values():
[14532]74            if ticket.total_score is not None:
[13834]75                credits_counted += ticket.credits
76                credits_weighted += ticket.credits * ticket.weight
77        if credits_counted:
[14384]78            level_gpa = credits_weighted/credits_counted
[14206]79        # Override level_gpa if value has been imported
80        imported_gpa = getattr(self, 'imported_gpa', None)
81        if imported_gpa:
82            level_gpa = imported_gpa
[13834]83        return level_gpa, credits_counted, credits_weighted
84
85    @property
[10480]86    def gpa_params_rectified(self):
87        return self.gpa_params
[10443]88
[13036]89    @property
[14357]90    def passed_params(self):
91        """Determine the number and credits of passed and failed courses.
92        This method is used for level reports.
93        """
94        passed = failed = 0
95        courses_failed = ''
96        credits_failed = 0
97        credits_passed = 0
[14393]98        courses_not_taken = ''
[16663]99        courses_passed = ''
[14357]100        for ticket in self.values():
[14532]101            if ticket.total_score is not None:
[14357]102                if ticket.total_score < ticket.passmark:
103                    failed += 1
104                    credits_failed += ticket.credits
[16042]105                    if ticket.mandatory or ticket.course_category == 'C':
[14357]106                        courses_failed += 'm_%s_m ' % ticket.code
107                    else:
108                        courses_failed += '%s ' % ticket.code
109                else:
110                    passed += 1
111                    credits_passed += ticket.credits
[16663]112                    courses_passed += '%s ' % ticket.code
[14370]113            else:
[14393]114                courses_not_taken += '%s ' % ticket.code
[14388]115        if not len(courses_failed):
[14506]116            courses_failed = 'Nil'
[14428]117        if not len(courses_not_taken):
[14506]118            courses_not_taken = 'Nil'
[14370]119        return (passed, failed, credits_passed,
120                credits_failed, courses_failed,
[16663]121                courses_not_taken, courses_passed)
[14357]122
123    @property
[14248]124    def course_registration_forbidden(self):
[14501]125        #fac_dep_paid = True
126        #if self.student.entry_session >= 2016:
127        #    fac_dep_paid = False
128        #    for ticket in self.student['payments'].values():
129        #        if ticket.p_category == 'fac_dep' and \
130        #            ticket.p_session == self.level_session and \
131        #            ticket.p_state == 'paid':
132        #                fac_dep_paid = True
133        #                continue
134        #if not fac_dep_paid:
135        #    return _("Please pay faculty and departmental dues first.")
[14509]136
137
138        ######################################################
[15370]139        # Temporarily disable ug_ft course registration
[15378]140        #if self.student.current_mode == 'ug_ft':
141        #    return _("Course registration has been disabled.")
[14509]142        ######################################################
143
144
[14500]145        restitution_paid = True
[15178]146        if self.student.current_session == 2016 \
147            and self.student.current_mode in ('ug_ft', 'dp_ft') \
148            and not self.student.is_fresh:
[14500]149            restitution_paid = False
150            for ticket in self.student['payments'].values():
151                if ticket.p_category == 'restitution' and \
152                    ticket.p_session == self.level_session and \
153                    ticket.p_state == 'paid':
154                        restitution_paid = True
155                        continue
156        if not restitution_paid:
157            return _("Please pay restitution fee first.")
[15428]158        #if self.student.is_fresh:
159        #    return
[13036]160        try:
[15398]161            academic_session = grok.getSite()['configuration'][
162                str(self.level_session)]
[14117]163            if self.student.is_postgrad:
[15398]164                deadline = academic_session.coursereg_deadline_pg
[14117]165            elif self.student.current_mode.startswith('dp'):
[15398]166                deadline = academic_session.coursereg_deadline_dp
[15477]167            elif self.student.current_mode in (
[15478]168                'ug_pt', 'de_pt', 'de_dsh', 'ug_dsh'):
[15398]169                deadline = academic_session.coursereg_deadline_pt
[14117]170            elif self.student.current_mode == 'found':
[15398]171                deadline = academic_session.coursereg_deadline_found
[15458]172            elif self.student.current_mode == 'bridge':
173                deadline = academic_session.coursereg_deadline_bridge
[14117]174            else:
[15398]175                deadline = academic_session.coursereg_deadline
[13071]176        except (TypeError, KeyError):
[14248]177            return
[13070]178        if not deadline or deadline > datetime.now(pytz.utc):
[14248]179            return
[15398]180        if self.student.is_postgrad:
181            lcrfee = academic_session.late_pg_registration_fee
182        else:
183            lcrfee = academic_session.late_registration_fee
184        if not lcrfee:
185            return _("Course registration has been disabled.")
[13036]186        if len(self.student['payments']):
187            for ticket in self.student['payments'].values():
188                if ticket.p_category == 'late_registration' and \
189                    ticket.p_session == self.level_session and \
190                    ticket.p_state == 'paid':
[14248]191                        return
192        return _("Course registration has ended. "
193                 "Please pay the late registration fee.")
[13036]194
[14082]195    # only AAUE
196    @property
197    def remark(self):
[14161]198        certificate = getattr(self.__parent__,'certificate',None)
199        end_level = getattr(certificate, 'end_level', None)
[14918]200        study_mode = getattr(certificate, 'study_mode', None)
[18158]201        value = decimal.Decimal(str(self.cumulative_params[0]))
202        cgpa = round(value,2)
203        #cgpa = self.cumulative_params[0]
[14918]204        is_dp = False
205        if study_mode and study_mode.startswith('dp'):
206            is_dp = True
[14380]207        failed_limit = 1.5
208        if self.student.entry_session < 2013:
209            failed_limit = 1.0
[14377]210        # final level student remark
211        if end_level and self.level >= end_level:
[14464]212            if self.level > end_level:
213                # spill-over level
214                if self.gpa_params[1] == 0:
215                    # no credits taken
[14487]216                    return 'NER'
[14663]217            elif self.gpa_params[1] < MINIMUM_UNITS_THRESHOLD:
[14537]218                # credits taken below limit
219                return 'NER'
[14487]220            if self.level_verdict in ('FRNS', 'NER', 'NYV'):
[14415]221                return self.level_verdict
[14412]222            if '_m' in self.passed_params[4]:
[14161]223                return 'FRNS'
[14412]224            if not self.cumulative_params[0]:
225                return 'FRNS'
[14435]226            if len(self.passed_params[5]) \
[14506]227                and not self.passed_params[5] == 'Nil':
[14412]228                return 'FRNS'
[14955]229            if self.cumulative_params[1] < 60:
[14623]230                return 'FRNS'
[18158]231            if cgpa < failed_limit:
[14161]232                return 'Fail'
[15054]233            dummy, repeat = divmod(self.level, 100)
[18158]234            if cgpa < 5.1 and repeat == 20:
[15054]235                # Irrespective of the CGPA of a student, if the He/She has
236                # 3rd Extension, such student will be graduated with a "Pass".
237                return 'Pass'
[18158]238            if cgpa < 1.5:
[14918]239                if is_dp:
240                    return 'Fail'
[14463]241                return 'Pass'
[18158]242            if cgpa < 2.4:
[14918]243                if is_dp:
244                    return 'Pass'
[14327]245                return '3s_rd_s'
[18158]246            if cgpa < 3.5:
[14918]247                if is_dp:
248                    return 'Merit'
[14327]249                return '2s_2_s'
[18158]250            if cgpa < 4.5:
[14918]251                if is_dp:
252                    return 'Credit'
[14327]253                return '2s_1_s'
[18158]254            if cgpa < 5.1:
[14918]255                if is_dp:
256                    return 'Distinction'
[14327]257                return '1s_st_s'
[14161]258            return 'N/A'
259        # returning student remark
[14487]260        if self.level_verdict in ('FRNS', 'NER', 'NYV'):
[14475]261            return 'Probation'
262        if self.level_verdict == 'D':
263            return 'Withdrawn'
[14662]264        if self.gpa_params[1] == 0:
265            # no credits taken
266            return 'NER'
[14663]267        if self.gpa_params[1] < MINIMUM_UNITS_THRESHOLD:
[14464]268            # credits taken below limit
[14415]269            return 'Probation'
[18158]270        if cgpa < failed_limit:
[14082]271            return 'Probation'
[18158]272        if cgpa < 5.1:
[14082]273            return 'Proceed'
274        return 'N/A'
275
[14227]276    def _schoolfeePaymentMade(self):
277        if len(self.student['payments']):
278            for ticket in self.student['payments'].values():
279                if ticket.p_state == 'paid' and \
280                    ticket.p_category in (
281                        'schoolfee', 'schoolfee_incl', 'schoolfee_2',)  and \
282                    ticket.p_session == self.student[
283                        'studycourse'].current_session:
284                    return True
285        return False
286
[14259]287    def _coursePaymentsMade(self, course):
[14266]288        if self.level_session < 2016:
289            return True
[14259]290        if not course.code[:3] in ('GST', 'ENT'):
291            return True
292        if len(self.student['payments']):
293            paid_cats = list()
294            for pticket in self.student['payments'].values():
295                if pticket.p_state == 'paid':
296                    paid_cats.append(pticket.p_category)
297            if course.code in ('GST101', 'GST102', 'GST111', 'GST112') and \
298                not 'gst_registration_1' in paid_cats:
299                return False
300            if course.code in ('GST222',) and \
301                not 'gst_registration_2' in paid_cats:
302                return False
[14355]303            if course.code in ('GST101', 'GST102') and \
[14348]304                not 'gst_text_book_1' in paid_cats and \
[14355]305                not 'gst_text_book_0' in paid_cats:
[14259]306                return False
[14355]307            if course.code in ('GST111', 'GST112') and \
[14348]308                not 'gst_text_book_2' in paid_cats and \
[14355]309                not 'gst_text_book_0' in paid_cats:
[14348]310                return False
[14259]311            if course.code in ('GST222',) and \
312                not 'gst_text_book_3' in paid_cats:
313                return False
[16754]314            if course.code in ('ENT201',) and \
315                not 'ent_registration_1' in paid_cats and \
[16810]316                not 'ent_registration_0' in paid_cats and \
317                not 'ent_combined' in paid_cats:
[16754]318                return False
[16749]319            if course.code in ('ENT211',) and \
[16754]320                not 'ent_registration_2' in paid_cats and \
[16810]321                not 'ent_registration_0' in paid_cats and \
322                not 'ent_combined' in paid_cats:
[16749]323                return False
[16754]324            if course.code in ('ENT201',) and \
325                not 'ent_text_book_1' in paid_cats and \
[16810]326                not 'ent_text_book_0' in paid_cats and \
327                not 'ent_combined' in paid_cats:
[16754]328                return False
329            if course.code in ('ENT211',) and \
330                not 'ent_text_book_2' in paid_cats and \
[16810]331                not 'ent_text_book_0' in paid_cats and \
332                not 'ent_combined' in paid_cats:
[16754]333                return False
[14259]334            return True
335        return False
336
[14075]337    def addCourseTicket(self, ticket, course):
338        """Add a course ticket object.
339        """
340        if not ICourseTicket.providedBy(ticket):
341            raise TypeError(
342                'StudentStudyLeves contain only ICourseTicket instances')
[14227]343        # Raise TicketError if course is in 2nd semester but
344        # schoolfee has not yet been fully paid.
345        if course.semester == 2 and not self._schoolfeePaymentMade():
[14252]346            raise TicketError(
347                _('%s is a 2nd semester course which can only be added '
348                  'if school fees have been fully paid.' % course.code))
[14259]349        # Raise TicketError if registration fee or text
350        # book fee haven't been paid.
351        if not self._coursePaymentsMade(course):
352            raise TicketError(
353                _('%s can only be added if both registration fee and text '
354                  'book fee have been paid.'
355                  % course.code))
[15429]356        # We check if there exists a certificate course in the certificate
357        # container which refers to the course. If such an object does
358        # not exist, students and managers will be prevented from registering
359        # the corresponding course.
[16757]360        # If a certificate course is found, the course_category will be used
361        # for the course ticket.
[15429]362        cert = self.__parent__.certificate
363        ticket_allowed = False
364        for val in cert.values():
365            if val.course == course:
366                ticket_allowed = True
[16757]367                course_category = val.course_category
[15429]368                break
369        if not ticket_allowed:
370            raise TicketError(
371                _('%s is not part of the %s curriculum.'
372                  % (course.code, cert.code)))
[14075]373        ticket.code = course.code
374        ticket.title = course.title
375        ticket.fcode = course.__parent__.__parent__.__parent__.code
376        ticket.dcode = course.__parent__.__parent__.code
377        ticket.credits = course.credits
[16757]378        ticket.course_category = course_category
[17653]379        if self.student.entry_session < 2013 or self.student.entry_session > 2021:
[14075]380            ticket.passmark = course.passmark - 5
381        else:
382            ticket.passmark = course.passmark
383        ticket.semester = course.semester
384        self[ticket.code] = ticket
385        return
386
[14227]387    def addCertCourseTickets(self, cert):
388        """Collect all certificate courses and create course
389        tickets automatically.
390        """
391        if cert is not None:
392            for key, val in cert.items():
393                if val.level != self.level:
394                    continue
[16900]395                if val.course_category != 'C':
396                    continue
[14227]397                ticket = createObject(u'waeup.CourseTicket')
398                ticket.automatic = True
399                ticket.mandatory = val.mandatory
400                ticket.carry_over = False
[16757]401                #ticket.course_category = val.course_category
[14227]402                try:
403                    self.addCourseTicket(ticket, val.course)
404                except TicketError:
405                    pass
406        return
407
[17700]408    def updateCourseTicket(self, ticket, course):
409        """Updates a course ticket object and return code
410        if ticket has been invalidated. AAUE: Do not update passmark
411        """
412        if not course:
413            if ticket.title.endswith('cancelled)'):
414                # Skip this tiket
415                return
416            # Invalidate course ticket
417            ticket.title += u' (course cancelled)'
418            ticket.credits = 0
419            ticket.passmark = 0
420            return ticket.code
421        ticket.code = course.code
422        ticket.title = course.title
423        ticket.fcode = course.__parent__.__parent__.__parent__.code
424        ticket.dcode = course.__parent__.__parent__.code
425        ticket.credits = course.credits
426        # ticket.passmark = course.passmark
427        ticket.semester = course.semester
428        return
429
[9692]430CustomStudentStudyLevel = attrs_to_fields(
[9914]431    CustomStudentStudyLevel, omit=[
[10480]432    'total_credits', 'total_credits_s1', 'total_credits_s2', 'gpa'])
[8326]433
434class CustomStudentStudyLevelFactory(StudentStudyLevelFactory):
435    """A factory for student study levels.
436    """
437
438    def __call__(self, *args, **kw):
439        return CustomStudentStudyLevel()
440
441    def getInterfaces(self):
442        return implementedBy(CustomStudentStudyLevel)
443
444class CustomCourseTicket(CourseTicket):
445    """This is a course ticket which allows the
446    student to attend the course. Lecturers will enter scores and more at
447    the end of the term.
448
449    A course ticket contains a copy of the original course and
450    course referrer data. If the courses and/or their referrers are removed, the
451    corresponding tickets remain unchanged. So we do not need any event
452    triggered actions on course tickets.
453    """
454    grok.implements(ICustomCourseTicket, IStudentNavigation)
455    grok.provides(ICustomCourseTicket)
456
[13834]457    @property
[14532]458    def _getGradeWeightFromScore(self):
[16579]459        """AAUE Course Grading System
[14532]460        """
461        if self.score == -1:
462            return ('-',0) # core course and result not yet available (used by AAUE)
463        if self.total_score is None:
464            return (None, None)
465        if self.total_score >= 70:
466            return ('A',5)
467        if self.total_score >= 60:
468            return ('B',4)
469        if self.total_score >= 50:
470            return ('C',3)
471        if self.total_score >= 45:
472            return ('D',2)
[17653]473        if self.total_score >= self.passmark: # passmark changed in 2013 from 40 to 45 and 2022 back to 40
[14532]474            return ('E',1)
475        return ('F',0)
476
477    @property
[14136]478    def total_score(self):
[15228]479        """Returns ca + score or imported total score.
[14136]480        """
[16755]481        if self.outstanding:
482            return None
[15226]483        # Override total_score if value has been imported
484        if getattr(self, 'imported_ts', None):
485            return self.imported_ts
[14532]486        if self.score == -1:
487            return 0
[14136]488        if not None in (self.score, self.ca):
489            return self.score + self.ca
[14532]490        return None
[14136]491
[14288]492    @property
[15804]493    def removable_by_student(self):
494        """True if student is allowed to remove the ticket.
495        """
[16042]496        if self.mandatory:
497            return False
498        if self.score:
499            return False
500        #if self.course_category == 'C':
501        #    return False
502        return True
[15804]503
504    @property
[14288]505    def editable_by_lecturer(self):
506        """True if lecturer is allowed to edit the ticket.
507        """
[15412]508        try:
509            cas = grok.getSite()[
510                'configuration'].current_academic_session
[15869]511            # Temporarily we allow students to pay for next session, so their
512            # current_session might have increased
[15876]513            if self.student.state in (
514                VALIDATED, REGISTERED, PAID, RETURNING) and \
[15869]515                self.student.current_session in (cas, cas+1):
[15412]516                return True
517        except (AttributeError, TypeError): # in unit tests
518            pass
519        return False
[14288]520
[8326]521CustomCourseTicket = attrs_to_fields(CustomCourseTicket)
522
523class CustomCourseTicketFactory(CourseTicketFactory):
524    """A factory for student study levels.
525    """
526
527    def __call__(self, *args, **kw):
528        return CustomCourseTicket()
529
530    def getInterfaces(self):
531        return implementedBy(CustomCourseTicket)
Note: See TracBrowser for help on using the repository browser.