source: WAeUP_SRP/base/skins/waeup_student/search_students.py @ 3381

Last change on this file since 3381 was 3066, checked in by joachim, 17 years ago

store faculties, departments and certificate_levels in SESSION for
ClearanceOfficers? and CourseAdvisers?

File size: 8.5 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'] = []
58co_view = False
59ca_view = False
60session_data = request.SESSION
61faculties =  session_data.get('faculties',None)
62departments = session_data.get('departments',None)
63certificate_levels = session_data.get('certificate_levels',None)
64# determine local roles
65if "ClearanceOfficers" in member.getGroups():
66    default_state = "clearance_requested"
67    co_view = True
68    if faculties is None or departments is None:
69        logger.info('ClearanceOfficer %s initiated student_search' % member)
70        query = In('portal_type',('Faculty','Department')) &\
71                 In('localUsersWithRoles', ("user:%s" % member,))
72        res = aq_portal(query)
73        faculties = [f.getId for f in res if f.portal_type == 'Faculty']
74        departments = [f.getId for f in res if f.portal_type == 'Department']
75    user_info['faculties'] = session_data['faculties'] = faculties
76    user_info['departments'] = session_data['departments'] =  departments
77elif "CourseAdvisers" in member.getGroups():
78    default_state = "courses_registered"
79    ca_view = True
80    if certificate_levels is None:
81        logger.info('CourseAdviser %s initiated student_search' % member)
82        query = In('portal_type',('StudyLevel',)) &\
83                 In('localUsersWithRoles', ("user:%s" % member,))
84        res = aq_portal(query)
85        certificate_levels = ['/'.join(f.getPath().split('/')[-2:]) for f in res]
86        cert_ids = []
87        level_ids = []
88        for cl in certificate_levels:
89            c,l = cl.split('/')
90            level_ids += l,
91            if c not in cert_ids:
92                cert_ids += c,
93        cert_brains = aq_portal(In("id",cert_ids))
94        end_levels = {}
95        for cert_brain in cert_brains:
96            end_levels[cert_brain.getId] = cert_brain.getObject().getContent().end_level
97        for cl in certificate_levels[:]:
98            c,l = cl.split('/')
99            for prob in (10,20):
100                certificate_levels += "%s/%s" % (c,int(l) + prob),
101            if l == end_levels[c]:
102                certificate_levels += "%s/%s" % (c,int(l) + 100),
103    user_info['certificate_levels'] = session_data['certificate_levels'] = certificate_levels
104
105default = {'search_mode': 'student_id',
106        'review_state': default_state,
107        'search_string': ''
108        }
109rend,psm,ds = lt.renderLayout(layout_id= 'student_search',
110                      schema_id= 'student_search',
111                      context=context,
112                      mapping=validate and REQUEST,
113                      ob=default,
114                      layout_mode='edit',
115                      formaction="search_students",
116                      commit = False,
117                      )
118if psm == '':
119    return context.search_students_form(rendered = rend,
120                             psm = psm,
121                             #psm = "%s, %s" % (psm,ds),
122                             info = user_info,
123                             students = [],
124                             allowed = allowed,
125                             )
126                             
127# return to search form  if form was not properly filled
128                             
129what = ds.get('search_mode')
130state = ds.get('review_state')
131st = term = ds.get('search_string')
132err = False
133if not term and state == "all":
134    psm = "You must specify a search string when searching for students in all states!"
135    err = True
136elif '*' in term:
137    psm = "Wildcards are not supported!"
138    err = True
139if err:
140    return context.search_students_form(rendered = rend,
141                             psm = psm,
142                             #psm = "%s, %s" % (psm,ds),
143                             info = user_info,
144                             students = [],
145                             allowed = allowed,
146                             )
147
148# build query string part 1
149
150query = None
151if len(term) > 0:
152    if what == "student_id":
153        students_folder = context.portal_url.getPortalObject().campus.students
154        if hasattr(students_folder,term.strip()):
155            logger.info('%s searches for student with id %s' % (member,term))
156            request.RESPONSE.redirect("%s/%s" % (students_folder.absolute_url(),term))
157        return context.search_students_form(rendered = rend,
158                             psm = "No student found!",
159                             students = [],
160                             allowed = allowed,
161                             info = user_info,
162                             )
163    elif what == "department":
164        query = Eq('department', term.strip())
165        logger.info('%s searches for student in department %s' % (member,term))
166    elif what == "matric_no":
167        query = Eq('matric_no', term.strip())
168        logger.info('%s searches for student with matric_no %s' % (member,term))
169    elif what == "jamb_reg_no":
170        st_l = "%s" % term.strip().lower()
171        st_u = "%s" % term.strip().upper()
172        query = In('jamb_reg_no',(st_l,st_u))
173        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
174    elif what == "name":
175        if len(term) < 4:
176            return context.search_students_form(rendered = rend,
177                                                psm = "Search string is too short!",
178                                                students = [],
179                                                info = user_info,
180                                                allowed = allowed,
181                                               )
182        query = Eq('name',"%s*" % term.strip())
183        logger.info('%s searches for student with name %s' % (member,term))
184
185
186# build query string part 2
187
188if state != 'all':
189    if query is not None:
190        query = Eq('review_state',state) & query
191    else:
192        query = Eq('review_state',state)
193    logger.info('%s searches for students in review_state %s' % (member,state))
194
195# build query string part 3
196
197if co_view:
198    if query is not None:
199        query = query & In('faculty',faculties) | In('department',departments)
200    else:
201        query = In('faculty',faculties) | In('department',departments)
202elif ca_view:
203    courses = [cl.split('/')[0] for cl in certificate_levels]
204    levels = [cl.split('/')[1] for cl in certificate_levels]
205    if query is not None:
206        query = query & In('course',courses) & In('level',levels)
207
208# search students_catalog
209
210student_records = aq_students(query)
211students = []
212if student_records:
213    for student_record in student_records:
214        info = {}
215        for field in students_catalog.schema() + students_catalog.indexes():
216            info[field] = getattr(student_record, field)
217        else:
218            students.append(info)
219    return context.search_students_form(rendered = rend,
220                             psm = "",
221                             info = user_info,
222                             students = students,
223                             allowed = allowed,
224                             co_view = co_view,
225                             ca_view = ca_view
226                             )
227return context.search_students_form(rendered = rend,
228                             psm = "No student found!",
229                             info = user_info,
230                             students = students,
231                             allowed = allowed,
232                             )
233
234
Note: See TracBrowser for help on using the repository browser.