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

Last change on this file since 2944 was 2873, checked in by joachim, 17 years ago

fix for #428

File size: 10.4 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
43aq_students = context.students_catalog.evalAdvancedQuery
44
45def cmp_id(a,b):
46    if a.getId() > b.getId():
47        return 1
48    return -1
49
50student_subobjects = ("StudentApplication",
51                      "StudentPersonal",
52                      "StudentStudyCourse",
53                      "StudentAccommodation",
54                      "StudentStudyLevel",)
55
56#student_objects = student_subobjects + ("Student",)
57student_objects = ("Student",)
58
59user_info = {}
60items = []
61validate = request.has_key("cpsdocument_edit_button")
62
63state = "all"
64user_info['member'] = str(member)
65user_info['departments'] = []
66user_info['faculties'] = []
67co_view = False
68ca_view = False
69faculties =  fget('faculties')
70departments = fget('departments')
71certificate_levels = fget('certificate_levels')
72dep_str = fac_str = certificate_levels_str = ''
73if "ClearanceOfficers" in member.getGroups():
74    state = "clearance_requested"
75    only_review = False
76    co_view = True
77    if faculties or departments:
78        #from Products.zdb import set_trace;set_trace()
79        if faculties:
80            fac_str = faculties
81            faculties = faculties.split()
82        if departments:
83            dep_str = departments
84            departments = departments.split()
85    else:
86        query = In('portal_type',('Faculty',)) &\
87                 In('localUsersWithRoles', ("user:%s" % member,))
88        res = aq_portal(query)
89        logger.info('ClearanceOfficer %s initiated student_search' % member)
90        faculties = []
91        if res:
92            faculties = [f.getId for f in res]
93        user_info['faculties'] = faculties
94        fac_str = " ".join(faculties)
95        query = In('portal_type',('Department',)) &\
96                 In('localUsersWithRoles', ("user:%s" % member,))
97        res = aq_portal(query)
98        departments = []
99        if res:
100            departments = [f.getId for f in res]
101        user_info['departments'] = departments
102        dep_str = " ".join(departments)
103elif "CourseAdvisers" in member.getGroups():
104    state = "courses_registered"
105    only_review = False
106    ca_view = True
107    if certificate_levels:
108        certificate_levels_str = certificate_levels
109        certificate_levels = certificate_levels.split()
110    else:
111        query = In('portal_type',('StudyLevel',)) &\
112                 In('localUsersWithRoles', ("user:%s" % member,))
113        res = aq_portal(query)
114        logger.info('CourseAdviser %s initiated student_search' % member)
115        certificate_levels = []
116        if res:
117            certificate_levels = ['/'.join(f.getPath().split('/')[-2:]) for f in res]
118            cert_ids = []
119            level_ids = []
120            for cl in certificate_levels:
121                c,l = cl.split('/')
122                level_ids += l,
123                if c not in cert_ids:
124                    cert_ids += c,
125            cert_brains = aq_portal(In("id",cert_ids))
126            end_levels = {}
127            for cert_brain in cert_brains:
128                end_levels[cert_brain.getId] = cert_brain.getObject().getContent().end_level
129            for cl in certificate_levels[:]:
130                c,l = cl.split('/')
131                for prob in (10,20):
132                    certificate_levels += "%s/%s" % (c,int(l) + prob),
133                if l == end_levels[c]:
134                    certificate_levels += "%s/%s" % (c,int(l) + 100),
135        user_info['certificate_levels'] = certificate_levels
136        certificate_levels_str = " ".join(certificate_levels)
137
138default = {'search_mode': 'student_id',
139        'review_state': state,
140        'search_string': ''
141        }
142rend,psm,ds = lt.renderLayout(layout_id= 'student_search',
143                      schema_id= 'student_search',
144                      context=context,
145                      mapping=validate and REQUEST,
146                      ob=default,
147                      layout_mode='edit',
148                      formaction="search_students",
149                      faculties = fac_str,
150                      departments = dep_str,
151                      certificate_levels = certificate_levels_str,
152                      commit = False,
153                      )
154if psm == '':
155    return context.search_students_form(rendered = rend,
156                             psm = psm,
157                             #psm = "%s, %s" % (psm,ds),
158                             info = user_info,
159                             students = [],
160                             allowed = allowed,
161                             )
162what = ds.get('search_mode')
163state = ds.get('review_state')
164st = term = ds.get('search_string')
165err = False
166with_review = state != "all"
167only_review = with_review and not term
168bools = "with_review = %s<br\> only_review = %s<br\>" % (with_review,only_review)
169if not term and not with_review:
170    psm = "You must specify a search string when searching 'all states'!"
171    err = True
172elif '*' in term:
173    psm = "Wildcards are not supported!"
174    err = True
175if err:
176    return context.search_students_form(rendered = rend,
177                             psm = psm,
178                             #psm = "%s, %s" % (psm,ds),
179                             info = user_info,
180                             students = items,
181                             allowed = allowed,
182                             )
183#st_queries = ('jamb_reg_no','matric_no','name')
184review_res = None
185query = None
186items = []
187res = []
188review_set = []
189search_set = []
190if len(term) > 0:
191    if what == "student_id":
192        students_folder = context.portal_url.getPortalObject().campus.students
193        if hasattr(students_folder,term.strip()):
194            logger.info('%s searches for student with id %s' % (member,term))
195            request.RESPONSE.redirect("%s/%s" % (students_folder.absolute_url(),term))
196        return context.search_students_form(rendered = rend,
197                             psm = "No student found!",
198                             students = [],
199                             allowed = allowed,
200                             )
201    elif what == "department":
202        res = context.students_catalog(department=term.strip())
203        logger.info('%s searches for student in department %s' % (member,term))
204        search_set = [r.id for r in res]
205    elif what == "matric_no":
206        res = context.students_catalog(matric_no=term.strip())
207        logger.info('%s searches for student with matric_no %s' % (member,term))
208        search_set = [r.id for r in res]
209    elif what == "jamb_reg_no":
210        st_l = "%s" % term.strip().lower()
211        st_u = "%s" % term.strip().upper()
212        res = aq_students(In('jamb_reg_no',(st_l,st_u)))
213        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
214        search_set = [r.id for r in res]
215    elif what == "name":
216        if len(term) < 4:
217            return context.search_students_form(rendered = rend,
218                                                psm = "Name too short!",
219                                                students = [],
220                                                allowed = allowed,
221                                               )
222        pt = ('StudentPersonal')
223        query = In('portal_type',pt) & Eq('SearchableText',"%s*" % term.strip())
224        logger.info('%s searches for student with name %s' % (member,term))
225        res = aq_portal(query)
226        if res:
227            for r in res:
228                pl = r.getPath().split('/')
229                search_set.append(pl[pl.index('students') + 1])
230
231if only_review or with_review or co_view:
232    #query = Eq('review_state',state)
233    #review_res = aq_portal(query)
234    #review_res = context.portal_catalog(review_state = state)
235
236    query = Eq('review_state',state)
237    review_res = aq_students(query)
238    logger.info('%s searches for students in review_state %s' % (member,state))
239
240if co_view:
241    only_review = False
242    with_review = True
243    query = In('faculty',faculties) | In('department',departments)
244    res = aq_students(query)
245    search_set = [r.id for r in res]
246elif ca_view:
247    only_review = False
248    with_review = True
249    courses = [cl.split('/')[0] for cl in certificate_levels]
250    levels = [cl.split('/')[1] for cl in certificate_levels]
251    query = In('course',courses) & In('level',levels)
252    res = aq_students(query)
253    search_set = [r.id for r in res]
254if review_res:
255    review_set = [r.id for r in review_res]
256
257#from Products.zdb import set_trace;set_trace()
258
259if only_review:
260    all = review_set
261elif with_review:
262    all = []
263    for i in search_set:
264        if i in review_set:
265            all.append(i)
266else:
267    all = search_set
268
269items = all[:500]
270students = []
271if items:
272    for item in items:
273        stcat = context.students_catalog
274        record = stcat(id = item)
275        if record:
276            record = record[0]
277        else:
278            return item+' not found in students_catalog'
279        info = {}
280        for field in stcat.schema() + stcat.indexes():
281            info[field] = getattr(record, field)
282        else:
283            students.append(info)
284    return context.search_students_form(rendered = rend,
285                             psm = "",
286                             info = user_info,
287                             students = students,
288                             allowed = allowed,
289                             co_view = co_view,
290                             ca_view = ca_view
291                             )
292return context.search_students_form(rendered = rend,
293                             psm = "No student found!",
294                             info = user_info,
295                             students = students,
296                             allowed = allowed,
297                             )
298
299
Note: See TracBrowser for help on using the repository browser.