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

Last change on this file since 3041 was 3024, checked in by Henrik Bettermann, 17 years ago

clean-up

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