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

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

possible fix #446 please test

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"
167if not co_view or not ca_view:
168    only_review = with_review and not term
169bools = "with_review = %s<br\> only_review = %s<br\>" % (with_review,only_review)
170if not term and not with_review:
171    psm = "You must specify a search string when searching 'all states'!"
172    err = True
173elif '*' in term:
174    psm = "Wildcards are not supported!"
175    err = True
176if err:
177    return context.search_students_form(rendered = rend,
178                             psm = psm,
179                             #psm = "%s, %s" % (psm,ds),
180                             info = user_info,
181                             students = items,
182                             allowed = allowed,
183                             )
184#st_queries = ('jamb_reg_no','matric_no','name')
185review_res = None
186query = None
187items = []
188res = []
189review_set = []
190search_set = []
191if len(term) > 0:
192    if what == "student_id":
193        students_folder = context.portal_url.getPortalObject().campus.students
194        if hasattr(students_folder,term.strip()):
195            logger.info('%s searches for student with id %s' % (member,term))
196            request.RESPONSE.redirect("%s/%s" % (students_folder.absolute_url(),term))
197        return context.search_students_form(rendered = rend,
198                             psm = "No student found!",
199                             students = [],
200                             allowed = allowed,
201                             )
202    elif what == "department":
203        res = context.students_catalog(department=term.strip())
204        logger.info('%s searches for student in department %s' % (member,term))
205        search_set = [r.id for r in res]
206    elif what == "matric_no":
207        res = context.students_catalog(matric_no=term.strip())
208        logger.info('%s searches for student with matric_no %s' % (member,term))
209        search_set = [r.id for r in res]
210    elif what == "jamb_reg_no":
211        st_l = "%s" % term.strip().lower()
212        st_u = "%s" % term.strip().upper()
213        res = aq_students(In('jamb_reg_no',(st_l,st_u)))
214        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
215        search_set = [r.id for r in res]
216    elif what == "name":
217        if len(term) < 4:
218            return context.search_students_form(rendered = rend,
219                                                psm = "Name too short!",
220                                                students = [],
221                                                allowed = allowed,
222                                               )
223        pt = ('StudentPersonal')
224        query = In('portal_type',pt) & Eq('SearchableText',"%s*" % term.strip())
225        logger.info('%s searches for student with name %s' % (member,term))
226        res = aq_portal(query)
227        if res:
228            for r in res:
229                pl = r.getPath().split('/')
230                search_set.append(pl[pl.index('students') + 1])
231
232if only_review or with_review or co_view:
233    #query = Eq('review_state',state)
234    #review_res = aq_portal(query)
235    #review_res = context.portal_catalog(review_state = state)
236
237    query = Eq('review_state',state)
238    review_res = aq_students(query)
239    logger.info('%s searches for students in review_state %s' % (member,state))
240
241if co_view:
242    only_review = False
243    with_review = True
244    query = In('faculty',faculties) | In('department',departments)
245    res = aq_students(query)
246    search_set = [r.id for r in res]
247elif ca_view:
248    only_review = False
249    with_review = True
250    courses = [cl.split('/')[0] for cl in certificate_levels]
251    levels = [cl.split('/')[1] for cl in certificate_levels]
252    query = In('course',courses) & In('level',levels)
253    res = aq_students(query)
254    search_set = [r.id for r in res]
255if review_res:
256    review_set = [r.id for r in review_res]
257
258#from Products.zdb import set_trace;set_trace()
259
260if only_review:
261    all = review_set
262elif with_review:
263    all = []
264    for i in search_set:
265        if i in review_set:
266            all.append(i)
267else:
268    all = search_set
269
270items = all[:500]
271students = []
272if items:
273    for item in items:
274        stcat = context.students_catalog
275        record = stcat(id = item)
276        if record:
277            record = record[0]
278        else:
279            return item+' not found in students_catalog'
280        info = {}
281        for field in stcat.schema() + stcat.indexes():
282            info[field] = getattr(record, field)
283        else:
284            students.append(info)
285    return context.search_students_form(rendered = rend,
286                             psm = "",
287                             info = user_info,
288                             students = students,
289                             allowed = allowed,
290                             co_view = co_view,
291                             ca_view = ca_view
292                             )
293return context.search_students_form(rendered = rend,
294                             psm = "No student found!",
295                             info = user_info,
296                             students = students,
297                             allowed = allowed,
298                             )
299
300
Note: See TracBrowser for help on using the repository browser.