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

Last change on this file since 5162 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
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'] = []
[4006]58user_info['certificates'] = []
[1065]59co_view = False
[1557]60ca_view = False
[3066]61session_data = request.SESSION
62faculties =  session_data.get('faculties',None)
63departments = session_data.get('departments',None)
[4006]64certificates = session_data.get('certificates',None)
[3066]65certificate_levels = session_data.get('certificate_levels',None)
[3024]66# determine local roles
[1006]67if "ClearanceOfficers" in member.getGroups():
[3024]68    default_state = "clearance_requested"
[1065]69    co_view = True
[4006]70    if faculties is None or departments is None or certificates is None:
[1571]71        logger.info('ClearanceOfficer %s initiated student_search' % member)
[4006]72        query = In('portal_type',('Faculty','Department','Certificate')) &\
[1278]73                 In('localUsersWithRoles', ("user:%s" % member,))
[1845]74        res = aq_portal(query)
[3066]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']
[4006]77        certificates = [f.getId for f in res if f.portal_type == 'Certificate']
[3066]78    user_info['faculties'] = session_data['faculties'] = faculties
79    user_info['departments'] = session_data['departments'] =  departments
[4006]80    user_info['certificates'] = session_data['certificates'] =  certificates
[3904]81if "CourseAdvisers" in member.getGroups():
[3024]82    default_state = "courses_registered"
[1557]83    ca_view = True
[3066]84    if certificate_levels is None:
85        logger.info('CourseAdviser %s initiated student_search' % member)
[1557]86        query = In('portal_type',('StudyLevel',)) &\
87                 In('localUsersWithRoles', ("user:%s" % member,))
[1845]88        res = aq_portal(query)
[3066]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
[2253]108
[1071]109default = {'search_mode': 'student_id',
[3024]110        'review_state': default_state,
[920]111        'search_string': ''
112        }
113rend,psm,ds = lt.renderLayout(layout_id= 'student_search',
114                      schema_id= 'student_search',
115                      context=context,
[1192]116                      mapping=validate and REQUEST,
[920]117                      ob=default,
118                      layout_mode='edit',
[971]119                      formaction="search_students",
120                      commit = False,
[920]121                      )
122if psm == '':
123    return context.search_students_form(rendered = rend,
124                             psm = psm,
125                             #psm = "%s, %s" % (psm,ds),
[1065]126                             info = user_info,
[971]127                             students = [],
[1096]128                             allowed = allowed,
[920]129                             )
[3024]130                             
131# return to search form  if form was not properly filled
132                             
[920]133what = ds.get('search_mode')
134state = ds.get('review_state')
135st = term = ds.get('search_string')
136err = False
[3024]137if not term and state == "all":
138    psm = "You must specify a search string when searching for students in all states!"
[920]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),
[1065]147                             info = user_info,
[3024]148                             students = [],
[1096]149                             allowed = allowed,
[920]150                             )
[3024]151
152# build query string part 1
153
[920]154query = None
155if len(term) > 0:
156    if what == "student_id":
[1065]157        students_folder = context.portal_url.getPortalObject().campus.students
[1033]158        if hasattr(students_folder,term.strip()):
[1571]159            logger.info('%s searches for student with id %s' % (member,term))
[1033]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 = [],
[1096]164                             allowed = allowed,
[3023]165                             info = user_info,
[1033]166                             )
[1034]167    elif what == "department":
[3022]168        query = Eq('department', term.strip())
[1571]169        logger.info('%s searches for student in department %s' % (member,term))
[1278]170    elif what == "matric_no":
[3022]171        query = Eq('matric_no', term.strip())
[1571]172        logger.info('%s searches for student with matric_no %s' % (member,term))
[1479]173    elif what == "jamb_reg_no":
[1500]174        st_l = "%s" % term.strip().lower()
175        st_u = "%s" % term.strip().upper()
[3022]176        query = In('jamb_reg_no',(st_l,st_u))
[1571]177        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
[1479]178    elif what == "name":
[2278]179        if len(term) < 4:
180            return context.search_students_form(rendered = rend,
[3023]181                                                psm = "Search string is too short!",
[2278]182                                                students = [],
[3023]183                                                info = user_info,
[2278]184                                                allowed = allowed,
185                                               )
[3022]186        query = Eq('name',"%s*" % term.strip())
[1571]187        logger.info('%s searches for student with name %s' % (member,term))
[1479]188
[3024]189
190# build query string part 2
191
192if state != 'all':
[3022]193    if query is not None:
194        query = Eq('review_state',state) & query
195    else:
196        query = Eq('review_state',state)
[1571]197    logger.info('%s searches for students in review_state %s' % (member,state))
[2253]198
[3024]199# build query string part 3
[3904]200if co_view and state.startswith('clear'):
[3022]201    if query is not None:
[4006]202        query = query & (In('faculty',faculties) | In('department',departments) | In('course',certificates))
[3022]203    else:
[4006]204        query = In('faculty',faculties) | In('department',departments) | In('course',certificates)
[3904]205elif ca_view and state.startswith('courses'):
[2253]206    courses = [cl.split('/')[0] for cl in certificate_levels]
207    levels = [cl.split('/')[1] for cl in certificate_levels]
[3022]208    if query is not None:
209        query = query & In('course',courses) & In('level',levels)
[3024]210
211# search students_catalog
212
[4006]213#return query
214
[3468]215student_records = aq_students(query,('matric_no','jamb_reg_no'))
[920]216students = []
[3022]217if student_records:
218    for student_record in student_records:
[3734]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               
[971]227        info = {}
[3022]228        for field in students_catalog.schema() + students_catalog.indexes():
229            info[field] = getattr(student_record, field)
[920]230        else:
[1011]231            students.append(info)
[920]232    return context.search_students_form(rendered = rend,
233                             psm = "",
[1065]234                             info = user_info,
[920]235                             students = students,
[1096]236                             allowed = allowed,
[3904]237                             co_view = state.startswith('clear'),
238                             ca_view = state.startswith('courses')
[920]239                             )
240return context.search_students_form(rendered = rend,
241                             psm = "No student found!",
[1065]242                             info = user_info,
[920]243                             students = students,
[1096]244                             allowed = allowed,
[920]245                             )
246
247
Note: See TracBrowser for help on using the repository browser.