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

Last change on this file since 16761 was 16757, checked in by Henrik Bettermann, 3 years ago

When adding a course ticket, use course category of first certificate course found in certificate.

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