source: main/waeup.sirp/trunk/src/waeup/sirp/students/student.py @ 7206

Last change on this file since 7206 was 7203, checked in by Henrik Bettermann, 13 years ago

Add indexes faccode, depcode and certcode to students_catalog.

  • Property svn:keywords set to Id
File size: 9.0 KB
Line 
1## $Id: student.py 7203 2011-11-25 20:54:14Z 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 for the various objects owned by students.
20"""
21import os
22import grok
23from grok import index
24from zope.component.interfaces import IFactory
25from zope.interface import implementedBy
26from hurry.workflow.interfaces import IWorkflowState, IWorkflowInfo
27from zope.securitypolicy.interfaces import IPrincipalRoleManager
28from waeup.sirp.interfaces import (
29    IObjectHistory, IUserAccount, IFileStoreNameChooser, IFileStoreHandler)
30from waeup.sirp.image import WAeUPImageFile
31from waeup.sirp.imagestorage import DefaultFileStoreHandler
32from waeup.sirp.students.interfaces import (
33    IStudent, IStudentNavigation, IStudentClearanceEdit,
34    IStudentPersonalEdit)
35from waeup.sirp.students.studycourse import StudentStudyCourse
36from waeup.sirp.students.payments import StudentPaymentsContainer
37from waeup.sirp.students.accommodation import StudentAccommodation
38from waeup.sirp.utils.helpers import attrs_to_fields, get_current_principal
39from waeup.sirp.students.utils import generate_student_id
40
41class Student(grok.Container):
42    """This is a student container for the various objects
43    owned by students.
44    """
45    grok.implements(IStudent, IStudentNavigation,
46        IStudentPersonalEdit, IStudentClearanceEdit)
47    grok.provides(IStudent)
48
49    def __init__(self):
50        super(Student, self).__init__()
51        # The site doesn't exist in unit tests
52        try:
53            students = grok.getSite()['students']
54            self.student_id = generate_student_id(students,'?')
55        except TypeError:
56            self.student_id = u'Z654321'
57        self.password = None
58        return
59
60    def loggerInfo(self, ob_class, comment=None):
61        target = self.__name__
62        return grok.getSite()['students'].logger_info(ob_class,target,comment)
63
64    @property
65    def state(self):
66        state = IWorkflowState(self).getState()
67        return state
68
69    @property
70    def history(self):
71        history = IObjectHistory(self)
72        return history
73
74    def getStudent(self):
75        return self
76
77    @property
78    def certcode(self):
79        cert = getattr(self.get('studycourse', None), 'certificate', None)
80        if cert is not None:
81            return cert.code
82        return
83
84    @property
85    def faccode(self):
86        cert = getattr(self.get('studycourse', None), 'certificate', None)
87        if cert is not None:
88            return cert.__parent__.__parent__.__parent__.code
89        return
90
91    @property
92    def depcode(self):
93        cert = getattr(self.get('studycourse', None), 'certificate', None)
94        if cert is not None:
95            return cert.__parent__.__parent__.code
96        return
97
98    @property
99    def current_session(self):
100        cert = getattr(self.get('studycourse', None), 'current_session', None)
101        return cert
102
103# Set all attributes of Student required in IStudent as field
104# properties. Doing this, we do not have to set initial attributes
105# ourselves and as a bonus we get free validation when an attribute is
106# set.
107Student = attrs_to_fields(Student)
108
109class StudentFactory(grok.GlobalUtility):
110    """A factory for students.
111    """
112    grok.implements(IFactory)
113    grok.name(u'waeup.Student')
114    title = u"Create a new student.",
115    description = u"This factory instantiates new student instances."
116
117    def __call__(self, *args, **kw):
118        return Student()
119
120    def getInterfaces(self):
121        return implementedBy(Student)
122
123@grok.subscribe(IStudent, grok.IObjectAddedEvent)
124def handle_student_added(student, event):
125    """If a student is added all subcontainers are automatically added
126    and the transition create is fired. The latter produces a logging message.
127    """
128    student.clearance_locked = True
129    studycourse = StudentStudyCourse()
130    student['studycourse'] = studycourse
131    payments = StudentPaymentsContainer()
132    student['payments'] = payments
133    accommodation = StudentAccommodation()
134    student['accommodation'] = accommodation
135    # Assign global student role for new student
136    account = IUserAccount(student)
137    account.roles = ['waeup.Student']
138    # Assign local StudentRecordOwner role
139    role_manager = IPrincipalRoleManager(student)
140    role_manager.assignRoleToPrincipal(
141        'waeup.local.StudentRecordOwner', student.student_id)
142    IWorkflowInfo(student).fireTransition('create')
143    return
144
145@grok.subscribe(IStudent, grok.IObjectRemovedEvent)
146def handle_student_removed(student, event):
147    """If a student is removed a message is logged.
148    """
149    comment = 'Student record removed'
150    target = student.student_id
151    # In some tests we don't have a principal
152    try:
153        user = get_current_principal().id
154    except (TypeError, AttributeError):
155        return
156    grok.getSite()['students'].logger.info('%s - %s - %s' % (
157        user, target, comment))
158    return
159
160#: The file id marker for student files
161STUDENT_FILE_STORE_NAME = 'file-student'
162
163class StudentFileNameChooser(grok.Adapter):
164    """A file id chooser for :class:`Student` objects.
165
166    `context` is an :class:`Student` instance.
167
168    The :class:`StudentImageNameChooser` can build/check file ids for
169    :class:`Student` objects suitable for use with
170    :class:`ExtFileStore` instances. The delivered file_id contains
171    the file id marker for :class:`Student` object and the student id
172    of the context student.
173
174    This chooser is registered as an adapter providing
175    :class:`waeup.sirp.interfaces.IFileStoreNameChooser`.
176
177    File store name choosers like this one are only convenience
178    components to ease the task of creating file ids for student
179    objects. You are nevertheless encouraged to use them instead of
180    manually setting up filenames for students.
181
182    .. seealso:: :mod:`waeup.sirp.imagestorage`
183
184    """
185    grok.context(IStudent)
186    grok.implements(IFileStoreNameChooser)
187
188    def checkName(self, name=None, attr=None):
189        """Check whether the given name is a valid file id for the context.
190
191        Returns ``True`` only if `name` equals the result of
192        :meth:`chooseName`.
193
194        """
195        return name == self.chooseName()
196
197    def chooseName(self, attr, name=None):
198        """Get a valid file id for student context.
199
200        *Example:*
201
202        For a student with student id ``'A123456'`` and
203        with attr ``'nice_image.jpeg'`` stored in
204        the students container this chooser would create:
205
206          ``'__file-student__students/A/A123456/nice_image_A123456.jpeg'``
207
208        meaning that the nice image of this applicant would be
209        stored in the site-wide file storage in path:
210
211          ``students/A/A123456/nice_image_A123456.jpeg``
212
213        """
214        basename, ext = os.path.splitext(attr)
215        stud_id = self.context.student_id
216        marked_filename = '__%s__%s/%s/%s_%s%s' % (
217            STUDENT_FILE_STORE_NAME, stud_id[0], stud_id, basename, stud_id, ext)
218        return marked_filename
219
220
221class StudentFileStoreHandler(DefaultFileStoreHandler, grok.GlobalUtility):
222    """Student specific file handling.
223
224    This handler knows in which path in a filestore to store student
225    files and how to turn this kind of data into some (browsable)
226    file object.
227
228    It is called from the global file storage, when it wants to
229    get/store a file with a file id starting with
230    ``__file-student__`` (the marker string for student files).
231
232    Like each other file store handler it does not handle the files
233    really (this is done by the global file store) but only computes
234    paths and things like this.
235    """
236    grok.implements(IFileStoreHandler)
237    grok.name(STUDENT_FILE_STORE_NAME)
238
239    def pathFromFileID(self, store, root, file_id):
240        """All student files are put in directory ``students``.
241        """
242        marker, filename, basename, ext = store.extractMarker(file_id)
243        sub_root = os.path.join(root, 'students')
244        return super(StudentFileStoreHandler, self).pathFromFileID(
245            store, sub_root, basename)
246
247    def createFile(self, store, root, filename, file_id, file):
248        """Create a browsable file-like object.
249        """
250        ext = os.path.splitext(filename)[1].lower()
251        # call super method to ensure that any old files with
252        # different filename extension are deleted.
253        file, path, file_obj =  super(
254            StudentFileStoreHandler, self).createFile(
255            store, root,  filename, file_id, file)
256        return file, path, WAeUPImageFile(
257            file_obj.filename, file_obj.data)
Note: See TracBrowser for help on using the repository browser.