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

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

resolve #605, show correct student list

File size: 8.9 KB
RevLine 
[920]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"""
[2873]14try:
15    from Products.zdb import set_trace
16except:
17    def set_trace():
18        pass
[1278]19import logging
[1571]20logger = logging.getLogger('Skins.search_students')
[2249]21#from DateTime import DateTime
[1278]22#
23#with_timer = True
[2249]24#with_timer = False
[1278]25#
[920]26request = REQUEST
[1033]27form = request.form
28fget = form.get
[920]29mtool = context.portal_membership
30member = mtool.getAuthenticatedMember()
[1096]31is_anon = mtool.isAnonymousUser()
[1065]32lt = context.portal_layouts
33path_info = request.get('PATH_INFO').split('/')
[1096]34
35allowed = True
[2431]36if is_anon or context.isStudent():
[1096]37    allowed = False
[1845]38from Products.AdvancedQuery import Eq, Between, Le,In
[920]39try:
[1845]40    aq_portal = context.portal_catalog.evalAdvancedQuery
[920]41except:
[1845]42    aq_portal = context.portal_catalog_real.evalAdvancedQuery
[3022]43students_catalog = context.students_catalog
[3024]44aq_students = students_catalog.evalAdvancedQuery
[920]45
[3024]46#def cmp_id(a,b):
47#    if a.getId() > b.getId():
48#        return 1
49#    return -1
[920]50
[1065]51user_info = {}
[920]52validate = request.has_key("cpsdocument_edit_button")
[1006]53
[3024]54default_state = "all"
[1065]55user_info['member'] = str(member)
56user_info['departments'] = []
57user_info['faculties'] = []
58co_view = False
[1557]59ca_view = False
[3066]60session_data = request.SESSION
61faculties =  session_data.get('faculties',None)
62departments = session_data.get('departments',None)
63certificate_levels = session_data.get('certificate_levels',None)
[3024]64# determine local roles
[1006]65if "ClearanceOfficers" in member.getGroups():
[3024]66    default_state = "clearance_requested"
[1065]67    co_view = True
[3066]68    if faculties is None or departments is None:
[1571]69        logger.info('ClearanceOfficer %s initiated student_search' % member)
[3066]70        query = In('portal_type',('Faculty','Department')) &\
[1278]71                 In('localUsersWithRoles', ("user:%s" % member,))
[1845]72        res = aq_portal(query)
[3066]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
[3904]77if "CourseAdvisers" in member.getGroups():
[3024]78    default_state = "courses_registered"
[1557]79    ca_view = True
[3066]80    if certificate_levels is None:
81        logger.info('CourseAdviser %s initiated student_search' % member)
[1557]82        query = In('portal_type',('StudyLevel',)) &\
83                 In('localUsersWithRoles', ("user:%s" % member,))
[1845]84        res = aq_portal(query)
[3066]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
[2253]104
[1071]105default = {'search_mode': 'student_id',
[3024]106        'review_state': default_state,
[920]107        'search_string': ''
108        }
109rend,psm,ds = lt.renderLayout(layout_id= 'student_search',
110                      schema_id= 'student_search',
111                      context=context,
[1192]112                      mapping=validate and REQUEST,
[920]113                      ob=default,
114                      layout_mode='edit',
[971]115                      formaction="search_students",
116                      commit = False,
[920]117                      )
118if psm == '':
119    return context.search_students_form(rendered = rend,
120                             psm = psm,
121                             #psm = "%s, %s" % (psm,ds),
[1065]122                             info = user_info,
[971]123                             students = [],
[1096]124                             allowed = allowed,
[920]125                             )
[3024]126                             
127# return to search form  if form was not properly filled
128                             
[920]129what = ds.get('search_mode')
130state = ds.get('review_state')
131st = term = ds.get('search_string')
132err = False
[3024]133if not term and state == "all":
134    psm = "You must specify a search string when searching for students in all states!"
[920]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),
[1065]143                             info = user_info,
[3024]144                             students = [],
[1096]145                             allowed = allowed,
[920]146                             )
[3024]147
148# build query string part 1
149
[920]150query = None
151if len(term) > 0:
152    if what == "student_id":
[1065]153        students_folder = context.portal_url.getPortalObject().campus.students
[1033]154        if hasattr(students_folder,term.strip()):
[1571]155            logger.info('%s searches for student with id %s' % (member,term))
[1033]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 = [],
[1096]160                             allowed = allowed,
[3023]161                             info = user_info,
[1033]162                             )
[1034]163    elif what == "department":
[3022]164        query = Eq('department', term.strip())
[1571]165        logger.info('%s searches for student in department %s' % (member,term))
[1278]166    elif what == "matric_no":
[3022]167        query = Eq('matric_no', term.strip())
[1571]168        logger.info('%s searches for student with matric_no %s' % (member,term))
[1479]169    elif what == "jamb_reg_no":
[1500]170        st_l = "%s" % term.strip().lower()
171        st_u = "%s" % term.strip().upper()
[3022]172        query = In('jamb_reg_no',(st_l,st_u))
[1571]173        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
[1479]174    elif what == "name":
[2278]175        if len(term) < 4:
176            return context.search_students_form(rendered = rend,
[3023]177                                                psm = "Search string is too short!",
[2278]178                                                students = [],
[3023]179                                                info = user_info,
[2278]180                                                allowed = allowed,
181                                               )
[3022]182        query = Eq('name',"%s*" % term.strip())
[1571]183        logger.info('%s searches for student with name %s' % (member,term))
[1479]184
[3024]185
186# build query string part 2
187
188if state != 'all':
[3022]189    if query is not None:
190        query = Eq('review_state',state) & query
191    else:
192        query = Eq('review_state',state)
[1571]193    logger.info('%s searches for students in review_state %s' % (member,state))
[2253]194
[3024]195# build query string part 3
[3904]196if co_view and state.startswith('clear'):
[3022]197    if query is not None:
198        query = query & In('faculty',faculties) | In('department',departments)
199    else:
200        query = In('faculty',faculties) | In('department',departments)
[3904]201elif ca_view and state.startswith('courses'):
[2253]202    courses = [cl.split('/')[0] for cl in certificate_levels]
203    levels = [cl.split('/')[1] for cl in certificate_levels]
[3022]204    if query is not None:
205        query = query & In('course',courses) & In('level',levels)
[3024]206
207# search students_catalog
208
[3468]209student_records = aq_students(query,('matric_no','jamb_reg_no'))
[920]210students = []
[3022]211if student_records:
212    for student_record in student_records:
[3734]213       
214        #ensure that course/level combinations are correct (see ticket #574)
215        if ca_view:
216           course = getattr(student_record, 'course')
217           level = getattr(student_record, 'level')
218           if course+'/'+level not in certificate_levels:
219               continue
220               
[971]221        info = {}
[3022]222        for field in students_catalog.schema() + students_catalog.indexes():
223            info[field] = getattr(student_record, field)
[920]224        else:
[1011]225            students.append(info)
[920]226    return context.search_students_form(rendered = rend,
227                             psm = "",
[1065]228                             info = user_info,
[920]229                             students = students,
[1096]230                             allowed = allowed,
[3904]231                             co_view = state.startswith('clear'),
232                             ca_view = state.startswith('courses')
[920]233                             )
234return context.search_students_form(rendered = rend,
235                             psm = "No student found!",
[1065]236                             info = user_info,
[920]237                             students = students,
[1096]238                             allowed = allowed,
[920]239                             )
240
241
Note: See TracBrowser for help on using the repository browser.