source: WAeUP_SRP/trunk/skins/waeup_student/search_students.py @ 4011

Last change on this file since 4011 was 4006, checked in by Henrik Bettermann, 16 years ago

resolve ticket aaue #16

Enable assigment of clearance officer role on certificate level. Do not show local roles on search student page.

File size: 9.2 KB
Line 
1## Script (Python) "search_students"
2##bind container=container
3##bind context=context
4##bind namespace=
5##bind script=script
6##bind subpath=traverse_subpath
7##parameters=REQUEST
8##title=
9##
10# $Id: search_students.py 911 2006-11-20 15:11:29Z henrik $
11"""
12list Students for ClearanceOfficers
13"""
14try:
15    from Products.zdb import set_trace
16except:
17    def set_trace():
18        pass
19import logging
20logger = logging.getLogger('Skins.search_students')
21#from DateTime import DateTime
22#
23#with_timer = True
24#with_timer = False
25#
26request = REQUEST
27form = request.form
28fget = form.get
29mtool = context.portal_membership
30member = mtool.getAuthenticatedMember()
31is_anon = mtool.isAnonymousUser()
32lt = context.portal_layouts
33path_info = request.get('PATH_INFO').split('/')
34
35allowed = True
36if is_anon or context.isStudent():
37    allowed = False
38from Products.AdvancedQuery import Eq, Between, Le,In
39try:
40    aq_portal = context.portal_catalog.evalAdvancedQuery
41except:
42    aq_portal = context.portal_catalog_real.evalAdvancedQuery
43students_catalog = context.students_catalog
44aq_students = students_catalog.evalAdvancedQuery
45
46#def cmp_id(a,b):
47#    if a.getId() > b.getId():
48#        return 1
49#    return -1
50
51user_info = {}
52validate = request.has_key("cpsdocument_edit_button")
53
54default_state = "all"
55user_info['member'] = str(member)
56user_info['departments'] = []
57user_info['faculties'] = []
58user_info['certificates'] = []
59co_view = False
60ca_view = False
61session_data = request.SESSION
62faculties =  session_data.get('faculties',None)
63departments = session_data.get('departments',None)
64certificates = session_data.get('certificates',None)
65certificate_levels = session_data.get('certificate_levels',None)
66# determine local roles
67if "ClearanceOfficers" in member.getGroups():
68    default_state = "clearance_requested"
69    co_view = True
70    if faculties is None or departments is None or certificates is None:
71        logger.info('ClearanceOfficer %s initiated student_search' % member)
72        query = In('portal_type',('Faculty','Department','Certificate')) &\
73                 In('localUsersWithRoles', ("user:%s" % member,))
74        res = aq_portal(query)
75        faculties = [f.getId for f in res if f.portal_type == 'Faculty']
76        departments = [f.getId for f in res if f.portal_type == 'Department']
77        certificates = [f.getId for f in res if f.portal_type == 'Certificate']
78    user_info['faculties'] = session_data['faculties'] = faculties
79    user_info['departments'] = session_data['departments'] =  departments
80    user_info['certificates'] = session_data['certificates'] =  certificates
81if "CourseAdvisers" in member.getGroups():
82    default_state = "courses_registered"
83    ca_view = True
84    if certificate_levels is None:
85        logger.info('CourseAdviser %s initiated student_search' % member)
86        query = In('portal_type',('StudyLevel',)) &\
87                 In('localUsersWithRoles', ("user:%s" % member,))
88        res = aq_portal(query)
89        certificate_levels = ['/'.join(f.getPath().split('/')[-2:]) for f in res]
90        cert_ids = []
91        level_ids = []
92        for cl in certificate_levels:
93            c,l = cl.split('/')
94            level_ids += l,
95            if c not in cert_ids:
96                cert_ids += c,
97        cert_brains = aq_portal(In("id",cert_ids))
98        end_levels = {}
99        for cert_brain in cert_brains:
100            end_levels[cert_brain.getId] = cert_brain.getObject().getContent().end_level
101        for cl in certificate_levels[:]:
102            c,l = cl.split('/')
103            for prob in (10,20):
104                certificate_levels += "%s/%s" % (c,int(l) + prob),
105            if l == end_levels[c]:
106                certificate_levels += "%s/%s" % (c,int(l) + 100),
107    user_info['certificate_levels'] = session_data['certificate_levels'] = certificate_levels
108
109default = {'search_mode': 'student_id',
110        'review_state': default_state,
111        'search_string': ''
112        }
113rend,psm,ds = lt.renderLayout(layout_id= 'student_search',
114                      schema_id= 'student_search',
115                      context=context,
116                      mapping=validate and REQUEST,
117                      ob=default,
118                      layout_mode='edit',
119                      formaction="search_students",
120                      commit = False,
121                      )
122if psm == '':
123    return context.search_students_form(rendered = rend,
124                             psm = psm,
125                             #psm = "%s, %s" % (psm,ds),
126                             info = user_info,
127                             students = [],
128                             allowed = allowed,
129                             )
130                             
131# return to search form  if form was not properly filled
132                             
133what = ds.get('search_mode')
134state = ds.get('review_state')
135st = term = ds.get('search_string')
136err = False
137if not term and state == "all":
138    psm = "You must specify a search string when searching for students in all states!"
139    err = True
140elif '*' in term:
141    psm = "Wildcards are not supported!"
142    err = True
143if err:
144    return context.search_students_form(rendered = rend,
145                             psm = psm,
146                             #psm = "%s, %s" % (psm,ds),
147                             info = user_info,
148                             students = [],
149                             allowed = allowed,
150                             )
151
152# build query string part 1
153
154query = None
155if len(term) > 0:
156    if what == "student_id":
157        students_folder = context.portal_url.getPortalObject().campus.students
158        if hasattr(students_folder,term.strip()):
159            logger.info('%s searches for student with id %s' % (member,term))
160            request.RESPONSE.redirect("%s/%s" % (students_folder.absolute_url(),term))
161        return context.search_students_form(rendered = rend,
162                             psm = "No student found!",
163                             students = [],
164                             allowed = allowed,
165                             info = user_info,
166                             )
167    elif what == "department":
168        query = Eq('department', term.strip())
169        logger.info('%s searches for student in department %s' % (member,term))
170    elif what == "matric_no":
171        query = Eq('matric_no', term.strip())
172        logger.info('%s searches for student with matric_no %s' % (member,term))
173    elif what == "jamb_reg_no":
174        st_l = "%s" % term.strip().lower()
175        st_u = "%s" % term.strip().upper()
176        query = In('jamb_reg_no',(st_l,st_u))
177        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
178    elif what == "name":
179        if len(term) < 4:
180            return context.search_students_form(rendered = rend,
181                                                psm = "Search string is too short!",
182                                                students = [],
183                                                info = user_info,
184                                                allowed = allowed,
185                                               )
186        query = Eq('name',"%s*" % term.strip())
187        logger.info('%s searches for student with name %s' % (member,term))
188
189
190# build query string part 2
191
192if state != 'all':
193    if query is not None:
194        query = Eq('review_state',state) & query
195    else:
196        query = Eq('review_state',state)
197    logger.info('%s searches for students in review_state %s' % (member,state))
198
199# build query string part 3
200if co_view and state.startswith('clear'):
201    if query is not None:
202        query = query & (In('faculty',faculties) | In('department',departments) | In('course',certificates))
203    else:
204        query = In('faculty',faculties) | In('department',departments) | In('course',certificates)
205elif ca_view and state.startswith('courses'):
206    courses = [cl.split('/')[0] for cl in certificate_levels]
207    levels = [cl.split('/')[1] for cl in certificate_levels]
208    if query is not None:
209        query = query & In('course',courses) & In('level',levels)
210
211# search students_catalog
212
213#return query
214
215student_records = aq_students(query,('matric_no','jamb_reg_no'))
216students = []
217if student_records:
218    for student_record in student_records:
219       
220        #ensure that course/level combinations are correct (see ticket #574)
221        if ca_view:
222           course = getattr(student_record, 'course')
223           level = getattr(student_record, 'level')
224           if course+'/'+level not in certificate_levels:
225               continue
226               
227        info = {}
228        for field in students_catalog.schema() + students_catalog.indexes():
229            info[field] = getattr(student_record, field)
230        else:
231            students.append(info)
232    return context.search_students_form(rendered = rend,
233                             psm = "",
234                             info = user_info,
235                             students = students,
236                             allowed = allowed,
237                             co_view = state.startswith('clear'),
238                             ca_view = state.startswith('courses')
239                             )
240return context.search_students_form(rendered = rend,
241                             psm = "No student found!",
242                             info = user_info,
243                             students = students,
244                             allowed = allowed,
245                             )
246
247
Note: See TracBrowser for help on using the repository browser.