source: main/waeup.kofa/branches/uli-zc-async/src/waeup/kofa/students/vocabularies.py @ 9110

Last change on this file since 9110 was 8766, checked in by uli, 12 years ago

Make test error disappear.

  • Property svn:keywords set to Id
File size: 7.6 KB
Line 
1## $Id: vocabularies.py 8766 2012-06-20 09:13:49Z uli $
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"""Vocabularies and sources for the student section.
19"""
20from zope.component import getUtility, queryUtility
21from zope.catalog.interfaces import ICatalog
22from zope.interface import implements, directlyProvides
23from zope.schema.interfaces import ISource, IContextSourceBinder
24from zope.schema.interfaces import ValidationError
25from zc.sourcefactory.basic import BasicSourceFactory
26from zc.sourcefactory.contextual import BasicContextualSourceFactory
27from waeup.kofa.interfaces import SimpleKofaVocabulary
28from waeup.kofa.interfaces import MessageFactory as _
29from waeup.kofa.utils.helpers import get_sorted_preferred
30from waeup.kofa.utils.countries import COUNTRIES
31from waeup.kofa.university.vocabularies import course_levels
32
33
34#: a tuple of tuples (<COUNTRY-NAME>, <ISO-CODE>) with Nigeria first.
35COUNTRIES = get_sorted_preferred(COUNTRIES, ['NG'])
36nats_vocab = SimpleKofaVocabulary(*COUNTRIES)
37
38def study_levels(studycourse):
39    if studycourse.certificate is not None:
40        start_level = int(studycourse.certificate.start_level)
41        end_level = int(studycourse.certificate.end_level)
42        if start_level == 999 or end_level == 999:
43            levels = [999]
44        elif start_level == 10:
45            levels = [10,] + [level for level in range(100,end_level+200,10)
46                if level % 100 < 30]
47        else:
48            levels = [level for level in range(start_level,end_level+200,10)
49                if level % 100 < 30]
50    else:
51        # default level range
52        levels = [level for level in range(100,1000,10) if level % 100 < 30]
53    return levels
54
55
56class StudyLevelSource(BasicContextualSourceFactory):
57    """The StudyLevelSource is based on and extends the
58    course_levels vocabulary defined in the university package.
59    Repeating study levels are denoted by increments of 10, the
60    first spillover level by the certificate's end level plus 100
61    and the second spillover level by the end level plus 110.
62    """
63    def getValues(self, context):
64        return study_levels(context)
65
66    def getToken(self, context, value):
67        return str(value)
68
69    def getTitle(self, context, value):
70        if context.certificate is not None:
71            start_level = int(context.certificate.start_level)
72            end_level = int(context.certificate.end_level)
73        else:
74            # default level range
75            start_level = 100
76            end_level = 1000
77        if start_level == 999 or end_level == 999:
78            if value != 999:
79                return _('Error: wrong level id ${value}',
80                    mapping={'value': value})
81            return course_levels.by_value[999].title
82        if value < start_level or value > end_level + 120:
83            return _('Error: level id ${value} out of range',
84                mapping={'value': value})
85        # Special treatment for pre-studies level
86        if value == 10:
87            return course_levels.by_value[value].title
88        level,repeat = divmod(value, 100)
89        level = level * 100
90        repeat = repeat//10
91        title = course_levels.by_value[level].title
92        if level > end_level and repeat == 1:
93            title = course_levels.by_value[level - 100].title
94            return _('${title} 2nd spillover', mapping={'title': title})
95        if level > end_level and repeat == 2:
96            title = course_levels.by_value[level - 100].title
97            return _('${title} 3rd spillover', mapping={'title': title})
98        if level > end_level:
99            title = course_levels.by_value[level - 100].title
100            return  _('${title} 1st spillover', mapping={'title': title})
101        if repeat == 1:
102            return _('${title} on 1st probation', mapping={'title': title})
103        if repeat == 2:
104            return _('${title} on 2nd probation', mapping={'title': title})
105        return title
106
107class GenderSource(BasicSourceFactory):
108    """A gender source delivers basically a mapping
109       ``{'m': 'Male', 'f': 'Female'}``
110
111       Using a source, we make sure that the tokens (which are
112       stored/expected for instance from CSV files) are something one
113       can expect and not cryptic IntIDs.
114    """
115    def getValues(self):
116        return ['m', 'f']
117
118    def getToken(self, value):
119        return value[0].lower()
120
121    def getTitle(self, value):
122        if value == 'm':
123            return _('male')
124        if value == 'f':
125            return _('female')
126
127class RegNumNotInSource(ValidationError):
128    """Registration number exists already
129    """
130    # The docstring of ValidationErrors is used as error description
131    # by zope.formlib.
132    pass
133
134class MatNumNotInSource(ValidationError):
135    """Matriculation number exists already
136    """
137    # The docstring of ValidationErrors is used as error description
138    # by zope.formlib.
139    pass
140
141class RegNumberSource(object):
142    """A source that accepts any entry for a certain field if not used
143    already.
144
145    Using this kind of source means a way of setting an invariant.
146
147    We accept a value iff:
148    - the value cannot be found in catalog or
149    - the value can be found as part of some item but the bound item
150      is the context object itself.
151    """
152    implements(ISource)
153    cat_name = 'students_catalog'
154    field_name = 'reg_number'
155    validation_error = RegNumNotInSource
156    comp_field = 'student_id'
157    def __init__(self, context):
158        self.context = context
159        return
160
161    def __contains__(self, value):
162        """We accept all values not already given to other students.
163        """
164        cat = queryUtility(ICatalog, self.cat_name)
165        if cat is None:
166            return True
167        kw = {self.field_name: (value, value)}
168        results = cat.searchResults(**kw)
169        for entry in results:
170            if not hasattr(self.context, self.comp_field):
171                # we have no context with comp_field (most probably
172                # while adding a new object, where the container is
173                # the context) which means that the value was given
174                # already to another object (as _something_ was found in
175                # the catalog with that value). Fail on first round.
176                raise self.validation_error(value)
177            if getattr(entry, self.comp_field) != getattr(
178                self.context, self.comp_field):
179                # An entry already given to another student is not in our
180                # range of acceptable values.
181                raise self.validation_error(value)
182                #return False
183        return True
184
185def contextual_reg_num_source(context):
186    source = RegNumberSource(context)
187    return source
188directlyProvides(contextual_reg_num_source, IContextSourceBinder)
189
190class MatNumberSource(RegNumberSource):
191    field_name = 'matric_number'
192    validation_error = MatNumNotInSource
193
194def contextual_mat_num_source(context):
195    source = MatNumberSource(context)
196    return source
197directlyProvides(contextual_mat_num_source, IContextSourceBinder)
Note: See TracBrowser for help on using the repository browser.