source: main/waeup.kofa/trunk/src/waeup/kofa/students/studylevel.py @ 14642

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

Add course_category attribute to course tickets. In the base package,
this attribute is omitted from display and manage pages.

  • Property svn:keywords set to Id
File size: 14.1 KB
Line 
1## $Id: studylevel.py 14642 2017-03-22 10:24:10Z 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##
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.catalog.interfaces import ICatalog
27from zope.component import createObject, queryUtility, getUtility
28from zope.interface import implementedBy
29from waeup.kofa.interfaces import academic_sessions_vocab, VALIDATED, IKofaUtils
30from waeup.kofa.students.interfaces import (
31    IStudentStudyLevel, IStudentNavigation, ICourseTicket)
32from waeup.kofa.utils.helpers import attrs_to_fields
33from waeup.kofa.students.vocabularies import StudyLevelSource
34from waeup.kofa.interfaces import MessageFactory as _
35
36def find_carry_over(ticket):
37    studylevel = ticket.__parent__
38    studycourse = ticket.__parent__.__parent__
39    levels = sorted(studycourse.keys())
40    index = levels.index(str(studylevel.level))
41    try:
42        next_level = levels[index+1]
43    except IndexError:
44        return None
45    next_studylevel = studycourse[next_level]
46    co_ticket = next_studylevel.get(ticket.code, None)
47    return co_ticket
48
49class StudentStudyLevel(grok.Container):
50    """This is a container for course tickets.
51    """
52    grok.implements(IStudentStudyLevel, IStudentNavigation)
53    grok.provides(IStudentStudyLevel)
54
55    def __init__(self):
56        super(StudentStudyLevel, self).__init__()
57        return
58
59    @property
60    def student(self):
61        try:
62            return self.__parent__.__parent__
63        except AttributeError:
64            return None
65
66    @property
67    def certcode(self):
68        try:
69            return self.__parent__.certificate.code
70        except AttributeError:
71            return None
72
73    @property
74    def number_of_tickets(self):
75        return len(self)
76
77    @property
78    def total_credits(self):
79        total = 0
80        for ticket in self.values():
81            if not ticket.outstanding:
82                total += ticket.credits
83        return total
84
85    @property
86    def getSessionString(self):
87        try:
88            session_string = academic_sessions_vocab.getTerm(
89                self.level_session).title
90        except LookupError:
91            return None
92        return session_string
93
94    @property
95    def gpa_params_rectified(self):
96        """Calculate corrected level (sessional) gpa parameters.
97        The corrected gpa is displayed on transcripts only.
98        """
99        credits_weighted = 0.0
100        credits_counted = 0
101        level_gpa = 0.0
102        for ticket in self.values():
103            if ticket.carry_over is False and ticket.total_score:
104                if ticket.total_score < ticket.passmark:
105                    co_ticket = find_carry_over(ticket)
106                    if co_ticket is not None and co_ticket.weight is not None:
107                        credits_counted += co_ticket.credits
108                        credits_weighted += co_ticket.credits * co_ticket.weight
109                    continue
110                credits_counted += ticket.credits
111                credits_weighted += ticket.credits * ticket.weight
112        if credits_counted:
113            level_gpa = credits_weighted/credits_counted
114        return level_gpa, credits_counted, credits_weighted
115
116    @property
117    def gpa_params(self):
118        """Calculate gpa parameters for this level.
119        """
120        credits_weighted = 0.0
121        credits_counted = 0
122        level_gpa = 0.0
123        for ticket in self.values():
124            if ticket.total_score is not None:
125                credits_counted += ticket.credits
126                credits_weighted += ticket.credits * ticket.weight
127        if credits_counted:
128            level_gpa = credits_weighted/credits_counted
129        # Override level_gpa if value has been imported
130        # (not implemented in base package)
131        imported_gpa = getattr(self, 'imported_gpa', None)
132        if imported_gpa:
133            level_gpa = imported_gpa
134        return level_gpa, credits_counted, credits_weighted
135
136    @property
137    def gpa(self):
138        """Return string formatted gpa value.
139        """
140        format_float = getUtility(IKofaUtils).format_float
141        return format_float(self.gpa_params[0], 2)
142
143    @property
144    def passed_params(self):
145        """Determine the number and credits of passed and failed courses.
146        Count the number of courses registered but not taken.
147        This method is used for level reports.
148        """
149        passed = failed = 0
150        courses_failed = ''
151        credits_failed = 0
152        credits_passed = 0
153        courses_not_taken = ''
154        for ticket in self.values():
155            if ticket.total_score is not None:
156                if ticket.total_score < ticket.passmark:
157                    failed += 1
158                    credits_failed += ticket.credits
159                    if ticket.mandatory:
160                        courses_failed += 'm_%s_m ' % ticket.code
161                    else:
162                        courses_failed += '%s ' % ticket.code
163                else:
164                    passed += 1
165                    credits_passed += ticket.credits
166            else:
167                courses_not_taken += '%s ' % ticket.code
168        return (passed, failed, credits_passed,
169                credits_failed, courses_failed,
170                courses_not_taken)
171
172    @property
173    def cumulative_params(self):
174        """Calculate the cumulative gpa and other cumulative parameters
175        for this level.
176        All levels below this level are taken under consideration
177        (including repeating levels).
178        This method is used for level reports and meanwhile also
179        for session results presentations.
180        """
181        credits_passed = 0
182        total_credits = 0
183        total_credits_counted = 0
184        total_credits_weighted = 0
185        cgpa = 0.0
186        if self.__parent__:
187            for level in self.__parent__.values():
188                if level.level > self.level:
189                    continue
190                credits_passed += level.passed_params[2]
191                total_credits += level.total_credits
192                gpa_params = level.gpa_params
193                total_credits_counted += gpa_params[1]
194                total_credits_weighted += gpa_params[2]
195            if total_credits_counted:
196                cgpa = total_credits_weighted/total_credits_counted
197            # Override cgpa if value has been imported
198            # (not implemented in base package)
199            imported_cgpa = getattr(self, 'imported_cgpa', None)
200            if imported_cgpa:
201                cgpa = imported_cgpa
202        return (cgpa, total_credits_counted, total_credits_weighted,
203               total_credits, credits_passed)
204
205    @property
206    def is_current_level(self):
207        try:
208            return self.__parent__.current_level == self.level
209        except AttributeError:
210            return False
211
212    def writeLogMessage(self, view, message):
213        return self.__parent__.__parent__.writeLogMessage(view, message)
214
215    @property
216    def level_title(self):
217        studylevelsource = StudyLevelSource()
218        return studylevelsource.factory.getTitle(self.__parent__, self.level)
219
220    @property
221    def course_registration_forbidden(self):
222        try:
223            deadline = grok.getSite()['configuration'][
224                str(self.level_session)].coursereg_deadline
225        except (TypeError, KeyError):
226            return
227        if not deadline or deadline > datetime.now(pytz.utc):
228            return
229        if len(self.student['payments']):
230            for ticket in self.student['payments'].values():
231                if ticket.p_category == 'late_registration' and \
232                    ticket.p_session == self.level_session and \
233                    ticket.p_state == 'paid':
234                        return
235        return _("Course registration has ended. "
236                 "Please pay the late registration fee.")
237
238    def addCourseTicket(self, ticket, course):
239        """Add a course ticket object.
240        """
241        if not ICourseTicket.providedBy(ticket):
242            raise TypeError(
243                'StudentStudyLeves contain only ICourseTicket instances')
244        ticket.code = course.code
245        ticket.title = course.title
246        ticket.fcode = course.__parent__.__parent__.__parent__.code
247        ticket.dcode = course.__parent__.__parent__.code
248        ticket.credits = course.credits
249        ticket.passmark = course.passmark
250        ticket.semester = course.semester
251        self[ticket.code] = ticket
252        return
253
254    def addCertCourseTickets(self, cert):
255        """Collect all certificate courses and create course
256        tickets automatically.
257        """
258        if cert is not None:
259            for key, val in cert.items():
260                if val.level != self.level:
261                    continue
262                ticket = createObject(u'waeup.CourseTicket')
263                ticket.automatic = True
264                ticket.mandatory = val.mandatory
265                ticket.carry_over = False
266                ticket.course_category = val.course_category
267                self.addCourseTicket(ticket, val.course)
268        return
269
270StudentStudyLevel = attrs_to_fields(
271    StudentStudyLevel, omit=['total_credits', 'gpa'])
272
273class StudentStudyLevelFactory(grok.GlobalUtility):
274    """A factory for student study levels.
275    """
276    grok.implements(IFactory)
277    grok.name(u'waeup.StudentStudyLevel')
278    title = u"Create a new student study level.",
279    description = u"This factory instantiates new student study level instances."
280
281    def __call__(self, *args, **kw):
282        return StudentStudyLevel()
283
284    def getInterfaces(self):
285        return implementedBy(StudentStudyLevel)
286
287class CourseTicket(grok.Model):
288    """This is a course ticket which allows the
289    student to attend the course. Lecturers will enter scores and more at
290    the end of the term.
291
292    A course ticket contains a copy of the original course and
293    certificate course data. If the courses and/or the referring certificate
294    courses are removed, the corresponding tickets remain unchanged.
295    So we do not need any event triggered actions on course tickets.
296    """
297    grok.implements(ICourseTicket, IStudentNavigation)
298    grok.provides(ICourseTicket)
299
300    def __init__(self):
301        super(CourseTicket, self).__init__()
302        self.code = None
303        return
304
305    @property
306    def student(self):
307        """Get the associated student object.
308        """
309        try:
310            return self.__parent__.__parent__.__parent__
311        except AttributeError: # in unit tests
312            return None
313
314    @property
315    def certcode(self):
316        try:
317            return self.__parent__.__parent__.certificate.code
318        except AttributeError: # in unit tests
319            return None
320
321    @property
322    def removable_by_student(self):
323        """True if student is allowed to remove the ticket.
324        """
325        return not self.mandatory
326
327    @property
328    def editable_by_lecturer(self):
329        """True if lecturer is allowed to edit the ticket.
330        """
331        try:
332            cas = grok.getSite()[
333                'configuration'].current_academic_session
334            if self.student.state == VALIDATED and \
335                self.student.current_session == cas:
336                return True
337        except (AttributeError, TypeError): # in unit tests
338            pass
339        return False
340
341    def writeLogMessage(self, view, message):
342        return self.__parent__.__parent__.__parent__.writeLogMessage(
343            view, message)
344
345    @property
346    def level(self):
347        """Returns the id of the level the ticket has been added to.
348        """
349        try:
350            return self.__parent__.level
351        except AttributeError: # in unit tests
352            return None
353
354    @property
355    def level_session(self):
356        """Returns the session of the level the ticket has been added to.
357        """
358        try:
359            return self.__parent__.level_session
360        except AttributeError: # in unit tests
361            return None
362
363    @property
364    def total_score(self):
365        """Returns the total score of this ticket. In the base package
366        this is simply the score. In customized packages this could be
367        something else.
368        """
369        return self.score
370
371    @property
372    def _getGradeWeightFromScore(self):
373        """Nigerian Course Grading System
374        """
375        if self.total_score is None:
376            return (None, None)
377        if self.total_score >= 70:
378            return ('A',5)
379        if self.total_score >= 60:
380            return ('B',4)
381        if self.total_score >= 50:
382            return ('C',3)
383        if self.total_score >= 45:
384            return ('D',2)
385        if self.total_score >= self.passmark: # passmark changed in 2013 from 40 to 45
386            return ('E',1)
387        return ('F',0)
388
389    @property
390    def grade(self):
391        """Returns the grade calculated from total score.
392        """
393        return self._getGradeWeightFromScore[0]
394
395    @property
396    def weight(self):
397        """Returns the weight calculated from total score.
398        """
399        return self._getGradeWeightFromScore[1]
400
401CourseTicket = attrs_to_fields(CourseTicket)
402
403class CourseTicketFactory(grok.GlobalUtility):
404    """A factory for student study levels.
405    """
406    grok.implements(IFactory)
407    grok.name(u'waeup.CourseTicket')
408    title = u"Create a new course ticket.",
409    description = u"This factory instantiates new course ticket instances."
410
411    def __call__(self, *args, **kw):
412        return CourseTicket()
413
414    def getInterfaces(self):
415        return implementedBy(CourseTicket)
Note: See TracBrowser for help on using the repository browser.