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

Last change on this file since 14254 was 14252, checked in by Henrik Bettermann, 8 years ago

Raise error message if TicketError? occurs.

  • Property svn:keywords set to Id
File size: 10.2 KB
Line 
1## $Id: studylevel.py 14252 2016-11-02 17:00:57Z 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 CREATED
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.interfaces import MessageFactory as _
38
39
40def getGradeWeightFromScore(total, student):
41    if total is None:
42        return (None, None)
43    if total >= 70:
44        return ('A',5)
45    if total >= 60:
46        return ('B',4)
47    if total >= 50:
48        return ('C',3)
49    if total >= 45:
50        return ('D',2)
51    if total >= 40 and student.entry_session < 2013:
52        return ('E',1)
53    return ('F',0)
54
55
56class CustomStudentStudyLevel(StudentStudyLevel):
57    """This is a container for course tickets.
58    """
59    grok.implements(ICustomStudentStudyLevel, IStudentNavigation)
60    grok.provides(ICustomStudentStudyLevel)
61
62    @property
63    def total_credits_s1(self):
64        total = 0
65        for ticket in self.values():
66            if ticket.semester == 1:
67                total += ticket.credits
68        return total
69
70    @property
71    def total_credits_s2(self):
72        total = 0
73        for ticket in self.values():
74            if ticket.semester == 2:
75                total += ticket.credits
76        return total
77
78    @property
79    def gpa_params(self):
80        """Calculate gpa parameters for this level.
81        """
82        credits_weighted = 0.0
83        credits_counted = 0
84        level_gpa = 0.0
85        for ticket in self.values():
86            if None not in (ticket.score, ticket.ca):
87                credits_counted += ticket.credits
88                credits_weighted += ticket.credits * ticket.weight
89        if credits_counted:
90            level_gpa = round(credits_weighted/credits_counted, 3)
91        # Override level_gpa if value has been imported
92        imported_gpa = getattr(self, 'imported_gpa', None)
93        if imported_gpa:
94            level_gpa = imported_gpa
95        return level_gpa, credits_counted, credits_weighted
96
97    @property
98    def gpa_params_rectified(self):
99        return self.gpa_params
100
101    @property
102    def course_registration_forbidden(self):
103        fac_dep_paid = True
104        if self.student.entry_session >= 2016:
105            fac_dep_paid = False
106            for ticket in self.student['payments'].values():
107                if ticket.p_category == 'fac_dep' and \
108                    ticket.p_session == self.level_session and \
109                    ticket.p_state == 'paid':
110                        fac_dep_paid = True
111                        continue
112        if not fac_dep_paid:
113            return _("Please pay faculty and departmental dues first.")
114        if self.student.is_fresh:
115            return
116        try:
117            if self.student.is_postgrad:
118                deadline = grok.getSite()['configuration'][
119                        str(self.level_session)].coursereg_deadline_pg
120            elif self.student.current_mode.startswith('dp'):
121                deadline = grok.getSite()['configuration'][
122                        str(self.level_session)].coursereg_deadline_dp
123            elif self.student.current_mode.endswith('_pt'):
124                deadline = grok.getSite()['configuration'][
125                        str(self.level_session)].coursereg_deadline_pt
126            elif self.student.current_mode == 'found':
127                deadline = grok.getSite()['configuration'][
128                        str(self.level_session)].coursereg_deadline_found
129            else:
130                deadline = grok.getSite()['configuration'][
131                        str(self.level_session)].coursereg_deadline
132        except (TypeError, KeyError):
133            return
134        if not deadline or deadline > datetime.now(pytz.utc):
135            return
136        if len(self.student['payments']):
137            for ticket in self.student['payments'].values():
138                if ticket.p_category == 'late_registration' and \
139                    ticket.p_session == self.level_session and \
140                    ticket.p_state == 'paid':
141                        return
142        return _("Course registration has ended. "
143                 "Please pay the late registration fee.")
144
145    # only AAUE
146    @property
147    def remark(self):
148        certificate = getattr(self.__parent__,'certificate',None)
149        end_level = getattr(certificate, 'end_level', None)
150        # final student remark
151        if end_level and self.student.current_level >= end_level:
152            failed_courses = self.passed_params[4]
153            if '_m' in failed_courses:
154                return 'FRNS'
155            if self.cumulative_params[0] < 1.5:
156                return 'Fail'
157            if self.cumulative_params[0] < 2.4:
158                return '3rd'
159            if self.cumulative_params[0] < 3.5:
160                return '2nd Lower'
161            if self.cumulative_params[0] < 4.5:
162                return '2nd Upper'
163            if self.cumulative_params[0] < 5.1:
164                return '1st'
165            return 'N/A'
166        # returning student remark
167        if self.cumulative_params[0] < 1.5:
168            return 'Probation'
169        if self.cumulative_params[0] < 5.1:
170            return 'Proceed'
171        return 'N/A'
172
173    def _schoolfeePaymentMade(self):
174        if len(self.student['payments']):
175            for ticket in self.student['payments'].values():
176                if ticket.p_state == 'paid' and \
177                    ticket.p_category in (
178                        'schoolfee', 'schoolfee_incl', 'schoolfee_2',)  and \
179                    ticket.p_session == self.student[
180                        'studycourse'].current_session:
181                    return True
182        return False
183
184    def addCourseTicket(self, ticket, course):
185        """Add a course ticket object.
186        """
187        if not ICourseTicket.providedBy(ticket):
188            raise TypeError(
189                'StudentStudyLeves contain only ICourseTicket instances')
190        # Raise TicketError if course is in 2nd semester but
191        # schoolfee has not yet been fully paid.
192        if course.semester == 2 and not self._schoolfeePaymentMade():
193            raise TicketError(
194                _('%s is a 2nd semester course which can only be added '
195                  'if school fees have been fully paid.' % course.code))
196        ticket.code = course.code
197        ticket.title = course.title
198        ticket.fcode = course.__parent__.__parent__.__parent__.code
199        ticket.dcode = course.__parent__.__parent__.code
200        ticket.credits = course.credits
201        if self.student.entry_session < 2013:
202            ticket.passmark = course.passmark - 5
203        else:
204            ticket.passmark = course.passmark
205        ticket.semester = course.semester
206        self[ticket.code] = ticket
207        return
208
209    def addCertCourseTickets(self, cert):
210        """Collect all certificate courses and create course
211        tickets automatically.
212        """
213        if cert is not None:
214            for key, val in cert.items():
215                if val.level != self.level:
216                    continue
217                ticket = createObject(u'waeup.CourseTicket')
218                ticket.automatic = True
219                ticket.mandatory = val.mandatory
220                ticket.carry_over = False
221                try:
222                    self.addCourseTicket(ticket, val.course)
223                except TicketError:
224                    pass
225        return
226
227CustomStudentStudyLevel = attrs_to_fields(
228    CustomStudentStudyLevel, omit=[
229    'total_credits', 'total_credits_s1', 'total_credits_s2', 'gpa'])
230
231class CustomStudentStudyLevelFactory(StudentStudyLevelFactory):
232    """A factory for student study levels.
233    """
234
235    def __call__(self, *args, **kw):
236        return CustomStudentStudyLevel()
237
238    def getInterfaces(self):
239        return implementedBy(CustomStudentStudyLevel)
240
241class CustomCourseTicket(CourseTicket):
242    """This is a course ticket which allows the
243    student to attend the course. Lecturers will enter scores and more at
244    the end of the term.
245
246    A course ticket contains a copy of the original course and
247    course referrer data. If the courses and/or their referrers are removed, the
248    corresponding tickets remain unchanged. So we do not need any event
249    triggered actions on course tickets.
250    """
251    grok.implements(ICustomCourseTicket, IStudentNavigation)
252    grok.provides(ICustomCourseTicket)
253
254    @property
255    def grade(self):
256        """Returns the grade calculated from score.
257        """
258        return getGradeWeightFromScore(self.total_score, self.student)[0]
259
260    @property
261    def weight(self):
262        """Returns the weight calculated from score.
263        """
264        return getGradeWeightFromScore(self.total_score, self.student)[1]
265
266    @property
267    def total_score(self):
268        """Returns ca + score.
269        """
270        if not None in (self.score, self.ca):
271            return self.score + self.ca
272
273CustomCourseTicket = attrs_to_fields(CustomCourseTicket)
274
275class CustomCourseTicketFactory(CourseTicketFactory):
276    """A factory for student study levels.
277    """
278
279    def __call__(self, *args, **kw):
280        return CustomCourseTicket()
281
282    def getInterfaces(self):
283        return implementedBy(CustomCourseTicket)
Note: See TracBrowser for help on using the repository browser.