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
Line 
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
23import pytz
24import pytz
25import decimal
26from datetime import datetime
27from zope.component.interfaces import IFactory
28from zope.component import createObject, getUtility
29from zope.interface import implementedBy
30from waeup.kofa.utils.helpers import attrs_to_fields
31from waeup.kofa.interfaces import (
32    RETURNING, VALIDATED, REGISTERED, PAID, IKofaUtils)
33from waeup.kofa.students.browser import TicketError
34from waeup.kofa.students.studylevel import (
35    StudentStudyLevel, CourseTicket,
36    CourseTicketFactory, StudentStudyLevelFactory)
37from waeup.kofa.students.interfaces import IStudentNavigation, ICourseTicket
38from waeup.aaue.students.interfaces import (
39    ICustomStudentStudyLevel, ICustomCourseTicket)
40from waeup.aaue.students.utils import MINIMUM_UNITS_THRESHOLD
41from waeup.aaue.interfaces import MessageFactory as _
42
43
44class CustomStudentStudyLevel(StudentStudyLevel):
45    """This is a container for course tickets.
46    """
47    grok.implements(ICustomStudentStudyLevel, IStudentNavigation)
48    grok.provides(ICustomStudentStudyLevel)
49
50    @property
51    def total_credits_s1(self):
52        total = 0
53        for ticket in self.values():
54            if ticket.semester == 1 and not ticket.outstanding:
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():
62            if ticket.semester == 2 and not ticket.outstanding:
63                total += ticket.credits
64        return total
65
66    @property
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():
74            if ticket.total_score is not None:
75                credits_counted += ticket.credits
76                credits_weighted += ticket.credits * ticket.weight
77        if credits_counted:
78            level_gpa = credits_weighted/credits_counted
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
83        return level_gpa, credits_counted, credits_weighted
84
85    @property
86    def gpa_params_rectified(self):
87        return self.gpa_params
88
89    @property
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
98        courses_not_taken = ''
99        courses_passed = ''
100        for ticket in self.values():
101            if ticket.total_score is not None:
102                if ticket.total_score < ticket.passmark:
103                    failed += 1
104                    credits_failed += ticket.credits
105                    if ticket.mandatory or ticket.course_category == 'C':
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
112                    courses_passed += '%s ' % ticket.code
113            else:
114                courses_not_taken += '%s ' % ticket.code
115        if not len(courses_failed):
116            courses_failed = 'Nil'
117        if not len(courses_not_taken):
118            courses_not_taken = 'Nil'
119        return (passed, failed, credits_passed,
120                credits_failed, courses_failed,
121                courses_not_taken, courses_passed)
122
123    @property
124    def course_registration_forbidden(self):
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.")
136
137
138        ######################################################
139        # Temporarily disable ug_ft course registration
140        #if self.student.current_mode == 'ug_ft':
141        #    return _("Course registration has been disabled.")
142        ######################################################
143
144
145        restitution_paid = True
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:
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.")
158        #if self.student.is_fresh:
159        #    return
160        try:
161            academic_session = grok.getSite()['configuration'][
162                str(self.level_session)]
163            if self.student.is_postgrad:
164                deadline = academic_session.coursereg_deadline_pg
165            elif self.student.current_mode.startswith('dp'):
166                deadline = academic_session.coursereg_deadline_dp
167            elif self.student.current_mode in (
168                'ug_pt', 'de_pt', 'de_dsh', 'ug_dsh'):
169                deadline = academic_session.coursereg_deadline_pt
170            elif self.student.current_mode == 'found':
171                deadline = academic_session.coursereg_deadline_found
172            elif self.student.current_mode == 'bridge':
173                deadline = academic_session.coursereg_deadline_bridge
174            else:
175                deadline = academic_session.coursereg_deadline
176        except (TypeError, KeyError):
177            return
178        if not deadline or deadline > datetime.now(pytz.utc):
179            return
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.")
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':
191                        return
192        return _("Course registration has ended. "
193                 "Please pay the late registration fee.")
194
195    # only AAUE
196    @property
197    def remark(self):
198        certificate = getattr(self.__parent__,'certificate',None)
199        end_level = getattr(certificate, 'end_level', None)
200        study_mode = getattr(certificate, 'study_mode', None)
201        value = decimal.Decimal(str(self.cumulative_params[0]))
202        cgpa = round(value,2)
203        #cgpa = self.cumulative_params[0]
204        is_dp = False
205        if study_mode and study_mode.startswith('dp'):
206            is_dp = True
207        failed_limit = 1.5
208        if self.student.entry_session < 2013:
209            failed_limit = 1.0
210        # final level student remark
211        if end_level and self.level >= end_level:
212            if self.level > end_level:
213                # spill-over level
214                if self.gpa_params[1] == 0:
215                    # no credits taken
216                    return 'NER'
217            elif self.gpa_params[1] < MINIMUM_UNITS_THRESHOLD:
218                # credits taken below limit
219                return 'NER'
220            if self.level_verdict in ('FRNS', 'NER', 'NYV'):
221                return self.level_verdict
222            if '_m' in self.passed_params[4]:
223                return 'FRNS'
224            if not self.cumulative_params[0]:
225                return 'FRNS'
226            if len(self.passed_params[5]) \
227                and not self.passed_params[5] == 'Nil':
228                return 'FRNS'
229            if self.cumulative_params[1] < 60:
230                return 'FRNS'
231            if cgpa < failed_limit:
232                return 'Fail'
233            dummy, repeat = divmod(self.level, 100)
234            if cgpa < 5.1 and repeat == 20:
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'
238            if cgpa < 1.5:
239                if is_dp:
240                    return 'Fail'
241                return 'Pass'
242            if cgpa < 2.4:
243                if is_dp:
244                    return 'Pass'
245                return '3s_rd_s'
246            if cgpa < 3.5:
247                if is_dp:
248                    return 'Merit'
249                return '2s_2_s'
250            if cgpa < 4.5:
251                if is_dp:
252                    return 'Credit'
253                return '2s_1_s'
254            if cgpa < 5.1:
255                if is_dp:
256                    return 'Distinction'
257                return '1s_st_s'
258            return 'N/A'
259        # returning student remark
260        if self.level_verdict in ('FRNS', 'NER', 'NYV'):
261            return 'Probation'
262        if self.level_verdict == 'D':
263            return 'Withdrawn'
264        if self.gpa_params[1] == 0:
265            # no credits taken
266            return 'NER'
267        if self.gpa_params[1] < MINIMUM_UNITS_THRESHOLD:
268            # credits taken below limit
269            return 'Probation'
270        if cgpa < failed_limit:
271            return 'Probation'
272        if cgpa < 5.1:
273            return 'Proceed'
274        return 'N/A'
275
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
287    def _coursePaymentsMade(self, course):
288        if self.level_session < 2016:
289            return True
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
303            if course.code in ('GST101', 'GST102') and \
304                not 'gst_text_book_1' in paid_cats and \
305                not 'gst_text_book_0' in paid_cats:
306                return False
307            if course.code in ('GST111', 'GST112') and \
308                not 'gst_text_book_2' in paid_cats and \
309                not 'gst_text_book_0' in paid_cats:
310                return False
311            if course.code in ('GST222',) and \
312                not 'gst_text_book_3' in paid_cats:
313                return False
314            if course.code in ('ENT201',) and \
315                not 'ent_registration_1' in paid_cats and \
316                not 'ent_registration_0' in paid_cats and \
317                not 'ent_combined' in paid_cats:
318                return False
319            if course.code in ('ENT211',) and \
320                not 'ent_registration_2' in paid_cats and \
321                not 'ent_registration_0' in paid_cats and \
322                not 'ent_combined' in paid_cats:
323                return False
324            if course.code in ('ENT201',) and \
325                not 'ent_text_book_1' in paid_cats and \
326                not 'ent_text_book_0' in paid_cats and \
327                not 'ent_combined' in paid_cats:
328                return False
329            if course.code in ('ENT211',) and \
330                not 'ent_text_book_2' in paid_cats and \
331                not 'ent_text_book_0' in paid_cats and \
332                not 'ent_combined' in paid_cats:
333                return False
334            return True
335        return False
336
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')
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():
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))
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))
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.
360        # If a certificate course is found, the course_category will be used
361        # for the course ticket.
362        cert = self.__parent__.certificate
363        ticket_allowed = False
364        for val in cert.values():
365            if val.course == course:
366                ticket_allowed = True
367                course_category = val.course_category
368                break
369        if not ticket_allowed:
370            raise TicketError(
371                _('%s is not part of the %s curriculum.'
372                  % (course.code, cert.code)))
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
378        ticket.course_category = course_category
379        if self.student.entry_session < 2013 or self.student.entry_session > 2021:
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
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
395                if val.course_category != 'C':
396                    continue
397                ticket = createObject(u'waeup.CourseTicket')
398                ticket.automatic = True
399                ticket.mandatory = val.mandatory
400                ticket.carry_over = False
401                #ticket.course_category = val.course_category
402                try:
403                    self.addCourseTicket(ticket, val.course)
404                except TicketError:
405                    pass
406        return
407
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
430CustomStudentStudyLevel = attrs_to_fields(
431    CustomStudentStudyLevel, omit=[
432    'total_credits', 'total_credits_s1', 'total_credits_s2', 'gpa'])
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
457    @property
458    def _getGradeWeightFromScore(self):
459        """AAUE Course Grading System
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)
473        if self.total_score >= self.passmark: # passmark changed in 2013 from 40 to 45 and 2022 back to 40
474            return ('E',1)
475        return ('F',0)
476
477    @property
478    def total_score(self):
479        """Returns ca + score or imported total score.
480        """
481        if self.outstanding:
482            return None
483        # Override total_score if value has been imported
484        if getattr(self, 'imported_ts', None):
485            return self.imported_ts
486        if self.score == -1:
487            return 0
488        if not None in (self.score, self.ca):
489            return self.score + self.ca
490        return None
491
492    @property
493    def removable_by_student(self):
494        """True if student is allowed to remove the ticket.
495        """
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
503
504    @property
505    def editable_by_lecturer(self):
506        """True if lecturer is allowed to edit the ticket.
507        """
508        try:
509            cas = grok.getSite()[
510                'configuration'].current_academic_session
511            # Temporarily we allow students to pay for next session, so their
512            # current_session might have increased
513            if self.student.state in (
514                VALIDATED, REGISTERED, PAID, RETURNING) and \
515                self.student.current_session in (cas, cas+1):
516                return True
517        except (AttributeError, TypeError): # in unit tests
518            pass
519        return False
520
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.