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

Last change on this file since 14309 was 5701, checked in by Henrik Bettermann, 14 years ago

Course Advisers shall also see second spill-over students (in custom).

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'] = []
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                certificate_levels += "%s/%s" % (c,int(l) + 110),
108    user_info['certificate_levels'] = session_data['certificate_levels'] = certificate_levels
109
110default = {'search_mode': 'student_id',
111        'review_state': default_state,
112        'search_string': ''
113        }
114rend,psm,ds = lt.renderLayout(layout_id= 'student_search',
115                      schema_id= 'student_search',
116                      context=context,
117                      mapping=validate and REQUEST,
118                      ob=default,
119                      layout_mode='edit',
120                      formaction="search_students",
121                      commit = False,
122                      )
123if psm == '':
124    return context.search_students_form(rendered = rend,
125                             psm = psm,
126                             #psm = "%s, %s" % (psm,ds),
127                             info = user_info,
128                             students = [],
129                             allowed = allowed,
130                             )
131                             
132# return to search form  if form was not properly filled
133                             
134what = ds.get('search_mode')
135state = ds.get('review_state')
136st = term = ds.get('search_string')
137err = False
138if not term and state == "all":
139    psm = "You must specify a search string when searching for students in all states!"
140    err = True
141elif '*' in term:
142    psm = "Wildcards are not supported!"
143    err = True
144if err:
145    return context.search_students_form(rendered = rend,
146                             psm = psm,
147                             #psm = "%s, %s" % (psm,ds),
148                             info = user_info,
149                             students = [],
150                             allowed = allowed,
151                             )
152
153# build query string part 1
154
155query = None
156if len(term) > 0:
157    if what == "student_id":
158        students_folder = context.portal_url.getPortalObject().campus.students
159        if hasattr(students_folder,term.strip()):
160            logger.info('%s searches for student with id %s' % (member,term))
161            request.RESPONSE.redirect("%s/%s" % (students_folder.absolute_url(),term))
162        return context.search_students_form(rendered = rend,
163                             psm = "No student found!",
164                             students = [],
165                             allowed = allowed,
166                             info = user_info,
167                             )
168    elif what == "department":
169        query = Eq('department', term.strip())
170        logger.info('%s searches for student in department %s' % (member,term))
171    elif what == "matric_no":
172        query = Eq('matric_no', term.strip())
173        logger.info('%s searches for student with matric_no %s' % (member,term))
174    elif what == "jamb_reg_no":
175        st_l = "%s" % term.strip().lower()
176        st_u = "%s" % term.strip().upper()
177        query = In('jamb_reg_no',(st_l,st_u))
178        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
179    elif what == "name":
180        if len(term) < 4:
181            return context.search_students_form(rendered = rend,
182                                                psm = "Search string is too short!",
183                                                students = [],
184                                                info = user_info,
185                                                allowed = allowed,
186                                               )
187        query = Eq('name',"%s*" % term.strip())
188        logger.info('%s searches for student with name %s' % (member,term))
189
190
191# build query string part 2
192
193if state != 'all':
194    if query is not None:
195        query = Eq('review_state',state) & query
196    else:
197        query = Eq('review_state',state)
198    logger.info('%s searches for students in review_state %s' % (member,state))
199
200# build query string part 3
201if co_view and state.startswith('clear'):
202    if query is not None:
203        query = query & (In('faculty',faculties) | In('department',departments) | In('course',certificates))
204    else:
205        query = In('faculty',faculties) | In('department',departments) | In('course',certificates)
206elif ca_view and state.startswith('courses'):
207    courses = [cl.split('/')[0] for cl in certificate_levels]
208    levels = [cl.split('/')[1] for cl in certificate_levels]
209    if query is not None:
210        query = query & In('course',courses) & In('level',levels)
211
212# search students_catalog
213
214#return query
215
216student_records = aq_students(query,('matric_no','jamb_reg_no'))
217students = []
218if student_records:
219    for student_record in student_records:
220       
221        #ensure that course/level combinations are correct (see ticket #574)
222        if ca_view:
223           course = getattr(student_record, 'course')
224           level = getattr(student_record, 'level')
225           if course+'/'+level not in certificate_levels:
226               continue
227               
228        info = {}
229        for field in students_catalog.schema() + students_catalog.indexes():
230            info[field] = getattr(student_record, field)
231        else:
232            students.append(info)
233    return context.search_students_form(rendered = rend,
234                             psm = "",
235                             info = user_info,
236                             students = students,
237                             allowed = allowed,
238                             co_view = state.startswith('clear'),
239                             ca_view = state.startswith('courses')
240                             )
241return context.search_students_form(rendered = rend,
242                             psm = "No student found!",
243                             info = user_info,
244                             students = students,
245                             allowed = allowed,
246                             )
247
248
Note: See TracBrowser for help on using the repository browser.