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

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