source: WAeUP_SRP/trunk/Students.py @ 979

Last change on this file since 979 was 975, checked in by Henrik Bettermann, 18 years ago

slips changed according to Kehinde's email
passport picture no more editable by student

  • Property svn:keywords set to Id
File size: 53.0 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 975 2006-12-01 13:03:22Z henrik $
3from string import Template
4from Globals import InitializeClass
5from AccessControl import ClassSecurityInfo
6from AccessControl.SecurityManagement import newSecurityManager
7from zExceptions import BadRequest
8from Products.ZCatalog.ZCatalog import ZCatalog
9from Products.CMFCore.utils import UniqueObject, getToolByName
10from Products.CMFCore.permissions import View
11from Products.CMFCore.permissions import ModifyPortalContent
12from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
13#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
14from Products.CPSDocument.CPSDocument import CPSDocument
15from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
16from Products.CPSCore.CPSMembershipTool import CPSUnrestrictedUser
17from Products.WAeUP_SRP.Academics import makeCertificateCode
18import logging
19import csv,re,os
20import Globals
21p_home = Globals.package_home(globals())
22i_home = Globals.INSTANCE_HOME
23MAX_TRANS = 100
24import DateTime
25import PIL.Image
26from StringIO import StringIO
27
28def makeCertificateCode(code): ###(
29    code = code.replace('.','')
30    code = code.replace('(','')
31    code = code.replace(')','')
32    code = code.replace('/','')
33    code = code.replace(' ','')
34    code = code.replace('_','')
35    return code
36
37###)
38
39def getInt(s): ###(
40    try:
41        return int(s)
42    except:
43        return 0
44
45def getFloat(s):
46    try:
47        return float(s)
48    except:
49        return 0.0
50
51###)
52
53def getStudentByRegNo(self,reg_no): ###(
54    """search student by JAMB Reg No and return StudentFolder"""
55    search = ZCatalog.searchResults(self.portal_catalog,{'meta_type': 'StudentApplication',
56                                  'SearchableText': reg_no,
57                                  })
58    if len(search) < 1:
59        return None
60    return search[0].getObject().aq_parent
61
62###)
63
64class StudentsFolder(CPSDocument): ###(
65    """
66    WAeUP container for the various WAeUP containers data
67    """
68    meta_type = 'StudentsFolder'
69    portal_type = meta_type
70    security = ClassSecurityInfo()
71
72    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsFromCSV")###(
73    def loadFullTimeStudentsFromCSV(self):
74        """load Fulltime Studentdata from CSV values"""
75        import transaction
76        import random
77        tr_count = 0
78        name = 'short_full_time'
79        no_import = False
80        if not no_import:
81            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
82            no_import.write('"MatricNo","EntryRegNo","CurrentSession","StudentLevel","fullname","FirstName","MiddleName","Lastname","FormerSurname","Sex","Nationality","State","LGA","PermanentAddress","PermanentAddressCity","CampusAddress","PhoneNumber","Emailaddress","Mode","CourseMajor","Faculty","Dept"\n')
83        logger = logging.getLogger('%s_import' % name)
84        logger.info('Start loading from %s.csv' % name)
85        pwlist  = []
86        pwlist.append('"student_id","firstname","middlename","lastname","matric_no","jamb_reg_no","access_code"')
87        pwl_template = Template('"$student_id","$firstname","$middlename","$lastname","$matric_no","$jamb_reg_no","$access_code"')
88        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
89        try:
90            students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
91        except:
92            logger.error('Error reading %s.csv' % name)
93            return
94        l = self.portal_catalog({'meta_type': "StudentClearance",})
95        matrics = []
96        for s in l:
97            matrics.append(s.getObject().getContent().matric_no)
98        print matrics
99        l = self.portal_catalog({'meta_type': "Certificate"})
100        certs = {}
101        for c in l:
102            ca,ac,fa,dep_id,co,certcode = c.relative_path.split('/')
103            cid = "%(dep_id)s_%(certcode)s" % vars()
104            certs[cid] = c.getObject()
105        for student in students:
106            logger.info('processing "%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
107            sid = student.get('MatricNo')
108            if sid == "":
109                em = 'Empty MatricNo\n'
110                logger.info(em)
111                no_import.write(em)
112                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
113                continue
114            certcode = makeCertificateCode(student.get('CourseMajor'))
115            dep_id = student.get('Dept')
116            fac_id = student.get('Faculty')
117            cid = "%(dep_id)s_%(certcode)s" % vars()
118            if cid not in certs.keys():
119                em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
120                logger.info(em)
121                no_import.write(em)
122                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
123                continue
124            certificate_doc = certs[cid].getContent()
125            level = student.get('StudentLevel')
126            try:
127                int(level)
128            except:
129                em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
130                logger.info(em)
131                no_import.write(em)
132                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
133                continue
134            matric_no = student.get('MatricNo')
135            if matric_no not in matrics:
136                matrics.append(matric_no)
137                sid = self.generateStudentId(student.get('Lastname')[0])
138                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
139                students_folder.invokeFactory('Student', sid)
140                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
141                student_obj = getattr(self,sid)
142                access_code = "%d" % random.randint(1000000000,9999999999)
143                student_obj.getContent().makeStudentMember(sid,access_code,)
144                pwl_dict = {'student_id': sid,'access_code':access_code}
145                student_obj.invokeFactory('StudentApplication','application')
146                application = student_obj.application
147                da = {'Title': 'Application Data'}
148                student_obj.invokeFactory('StudentPersonal','personal')
149                da['jamb_reg_no'] = student.get('EntryRegNo')
150                personal = student_obj.personal
151                dp = {'Title': 'Personal Data'}
152                student_obj.invokeFactory('StudentClearance','clearance')
153                clearance = student_obj.clearance
154                dc = {'Title': 'Clearance/Eligibility Record'}
155                dc['matric_no'] = matric_no
156                state = student.get('State')
157                lga = student.get('LGA')
158                if state and lga:
159                    lga =  state + ' / ' + lga
160                else:
161                    lga = "None"
162                dc['lga'] = lga
163                dc['nationality'] = student.get('Nationality')
164                dc['email'] = student.get('Emailaddress')
165                dp['firstname'] = student.get('FirstName')
166                dp['middlename'] = student.get('MiddleName')
167                dp['lastname'] = student.get('Lastname')
168                dp['former_surname'] = student.get('FormerSurname')
169                dp['sex'] = student.get('Sex') == 'F'
170                dp['perm_address'] = student.get('PermanentAddress')
171                dp['perm_city'] = student.get('PermanentAddressCity')
172                dp['campus_address'] = student.get('CampusAddress')
173                dp['phone'] = student.get('PhoneNumber')
174                application.getContent().edit(mapping=da)
175                personal.getContent().edit(mapping=dp)
176                clearance.getContent().edit(mapping=dc)
177                #
178                # Study Course
179                #
180                student_obj.invokeFactory('StudentStudyCourse','study_course')
181                studycourse = student_obj.study_course
182                dsc = {}
183                from_certificate = ['title',
184                                   'max_elect',
185                                   'max_pass',
186                                   'n_core',
187                                   'nr_years',
188                                   'probation_credits',
189                                   'promotion_credits',
190                                   'start_level',
191                                  ]
192                for f in from_certificate:
193                    dsc[f] = getattr(certificate_doc,f)
194                dsc['faculty'] = fac_id
195                dsc['department'] = dep_id
196                dsc['study_course'] = certcode
197                css = student.get('CurrentSession') or '2004-2005'
198                cs = int(css.split('-')[0]) - 2000
199                cl = int(student.get('StudentLevel') or '100')/100
200                dsc['entry_session'] = "200%s" % (cs - cl)
201                dsc['clr_ac_pin'] = access_code
202                studycourse.getContent().edit(mapping=dsc)
203                #
204                # Level
205                #
206##                l = getattr(studycourse,level,None)
207##                if 0 and l is None:
208##                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
209##                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
210##                    studycourse.invokeFactory('StudentStudyLevel', level)
211##                    l = getattr(studycourse, level)
212##                    certificate = certs[certcode]
213##                    cert_level = getattr(certificate,level,None)
214##                    if cert_level is None:
215##                        logger.info('Level %(level)s not in %(certcode)s' % vars())
216##                    l.getContent().edit(mapping={'Title': "Level %s" % level})
217            else:
218                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
219                logger.info(em)
220                no_import.write(em)
221                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
222                continue
223            if tr_count > MAX_TRANS:
224                transaction.commit()
225                em = 'Transaction commited\n' % student
226                logger.info(em)
227                tr_count = 0
228            tr_count += 1
229            pwl_dict.update(dc)
230            pwl_dict.update(da)
231            pwl_dict.update(dp)
232            wftool = self.portal_workflow
233            pwlist.append(pwl_template.substitute(pwl_dict))
234            wftool.doActionFor(student_obj,'clear_and_validate')
235            student_obj.manage_setLocalRoles(sid, ['Owner',])
236            wftool.doActionFor(application,'close')
237            application.manage_setLocalRoles(sid, ['Owner',])
238            wftool.doActionFor(clearance,'close')
239            clearance.manage_setLocalRoles(sid, ['Owner',])
240            wftool.doActionFor(personal,'close')
241            personal.manage_setLocalRoles(sid, ['Owner',])
242            wftool.doActionFor(studycourse,'close_for_edit')
243            studycourse.manage_setLocalRoles(sid, ['Owner',])
244        open("%s/import/pwlist-%s.csv" % (i_home,name),"w+").write('\n'.join(pwlist))
245        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
246    ###)
247
248    security.declareProtected(ModifyPortalContent,"loadPumeResultsFromCSV")###(
249    def loadPumeResultsFromCSV(self):
250        """load Fulltime Studentdata from CSV values into pumeresults catalog"""
251        import transaction
252        import random
253        from pdb import set_trace
254        csv_d = {'jamb_reg_no': "RegNumber",
255                 'status': "Admission Status",
256                 'name': "Name",
257                 'score': "Score",
258                 'sex': "Sex",
259                 'faculty': "Faculty",
260                 'department': "Dept",
261                 'course': "Course",
262                 'course_code_org': "Course Code",
263                 }
264        csv_fields = [f[1] for f in csv_d.items()]
265        tr_count = 0
266        total = 0
267        #name = 'pup_new'
268        name = 'pup_update'
269        update = name.endswith('update')
270        no_import = []
271        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
272        no_import.append('%s' % s)
273        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
274                    '\n'.join(no_import))
275        no_import = []
276        logger = logging.getLogger('%s_import' % name)
277        starttime = DateTime.now()
278        logger.info('Start loading from %s.csv' % name)
279        try:
280            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
281        except:
282            logger.error('Error reading %s.csv' % name)
283            return
284        pume = self.portal_pumeresults
285        format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
286        eduplicate = '"dupplicate",%s' % format
287        for jamb in result:
288            dict = {}
289            #set_trace()
290            for f,fn in csv_d.items():
291                dict[f] = jamb.get(csv_d[f])
292            res = pume(jamb_reg_no=jamb.get(csv_d['jamb_reg_no']))
293            if len(res) > 0:
294                if update:
295                    pume.modifyRecord(**dict)
296                else:
297                    data = res[0]
298                    if data.name != jamb.get(csv_d['name']):
299                        #set_trace()
300                        logger.info(eduplicate % jamb)
301                        #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
302                        #logger.info(em)
303                        dd = {}
304                        for f,fn in csv_d.items():
305                            dd[fn] = getattr(data,f)
306                        no_import.append(eduplicate % dd)
307                        no_import.append(eduplicate % jamb)
308                    continue
309            try:
310                pume.addRecord(**dict)
311            except ValueError:
312                logger.info(eduplicate % jamb)
313                #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
314                #logger.info(em)
315                no_import.append(eduplicate % jamb)
316        logger.info('End loading from %s.csv' % name)
317        if len(no_import) > 1:
318            open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
319            '\n'.join(no_import))
320        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
321    ###)
322
323    security.declareProtected(ModifyPortalContent,"createNewStudents")###(
324    def createNewStudents(self):
325        """load Fulltime Studentdata from CSV values"""
326        import transaction
327        import random
328        #from pdb import set_trace
329        wftool = self.portal_workflow
330        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
331        csv_d = {'jamb_reg_no': "RegNumber",
332                 'jamb_lastname': "Name",
333                 'session': "Session",
334                 'pume_tot_score': "PUME SCORE",
335                 'jamb_score': "JambScore",
336                 'jamb_sex': "Sex",
337                 'jamb_state': "State",
338                 'jamb_first_cos': "AdminCourse",
339                 'faculty': "AdminFaculty",
340                 'course_code': "AdmitCoscode",
341                 'stud_status':"AdmitStatus",
342                 'department': "AdmitDept",
343                 'jamb_lga': "LGA",
344                 'app_email': "email",
345                 }
346        csv_fields = [f[1] for f in csv_d.items()]
347        tr_count = 0
348        total = 0
349        #name = 'pume_results'
350        name = 'Admitted'
351        no_import = []
352        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
353        no_import.append('"Error",%s' % s)
354        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
355        no_certificate = "no certificate %s" % format
356        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
357                    '\n'.join(no_import))
358        logger = logging.getLogger('%s_import' % name)
359        logger.info('Start loading from %s.csv' % name)
360        l = self.portal_catalog({'meta_type': "Certificate"})
361        certs = {}
362        cert_docs = {}
363        for f in l:
364            certs[f.getId] = f.getObject().getContent()
365        try:
366            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
367        except:
368            logger.error('Error reading %s.csv' % name)
369            return
370        for jamb in result:
371            jamb['Error'] = "Processing "
372            logger.info(format % jamb)
373            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
374            res = self.portal_catalog({'portal_type': "StudentApplication",
375                                     'SearchableText': jamb_reg_no })
376            if res:
377                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
378                logger.info(em)
379                jamb['Error'] = "Student exists"
380                no_import.append(format % jamb)
381                continue
382            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
383            if cert_id not in certs.keys():
384                em = 'No Certificate with ID %s \n' % cert_id
385                logger.info(em)
386                jamb['Error'] = "No Certificate %s" % cert_id
387                no_import.append( format % jamb)
388                continue
389            cert_doc = certs[cert_id]
390            catalog_entry = {}
391            catalog_entry['jamb_reg_no'] = jamb_reg_no
392            jamb_name = jamb.get(csv_d['jamb_lastname'])
393            jamb_name.replace('>','')
394            jamb_name.replace('<','')
395            names = jamb_name.split()
396            letter = names[-1][0].upper()
397            sid = self.generateStudentId(letter)
398            not_created = True
399            while not_created:
400                try:
401                    students_folder.invokeFactory('Student', sid)
402                    not_created = False
403                except BadRequest:
404                    sid = self.generateStudentId(letter)
405            catalog_entry['id'] = sid
406            tr_count += 1
407            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
408            student = getattr(self,sid)
409            student.manage_setLocalRoles(sid, ['Owner',])
410            student.invokeFactory('StudentPume','pume')
411            dp = {'Title': 'Pume Data'}
412            student.invokeFactory('StudentApplication','application')
413            da = {'Title': 'Application Data'}
414            da["jamb_lastname"] = jamb_name
415            da_fields = ('jamb_reg_no',
416                         'jamb_sex',
417                         #'jamb_state',
418                         'jamb_score',
419                         'jamb_first_cos',
420                         'jamb_sex',
421                         'jamb_state',
422                         'jamb_lga',
423                         'app_email',
424                         )
425            for f in da_fields:
426                da[f] = jamb.get(csv_d[f])
427            catalog_entry['email'] = jamb.get(csv_d['app_email'])
428            app = student.application
429            app_doc = app.getContent()
430            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
431            #import pdb;pdb.set_trace()
432            if os.path.exists(picture):
433                file = open(picture)
434                if False:
435                    img = PIL.Image.open(file)
436                    img.thumbnail((150,200),
437                                  resample=PIL.Image.ANTIALIAS)
438                    # We now need a buffer to write to. It can't be the same
439                    # as the inbuffer as the PNG writer will write over itself.
440                    outfile = StringIO()
441                    img.save(outfile, format=img.format)
442                else:
443                    outfile = file.read()
444                app_doc.manage_addFile('passport',
445                                       file=outfile,
446                                       title="%s.jpg" % jamb_reg_no)
447            app.getContent().edit(mapping=da)
448            app.manage_setLocalRoles(sid, ['Owner',])
449            #wftool.doActionFor(app,'close')
450            dp_fields = (
451                         #'pume_eng_score',
452                         #'pume_gen_score',
453                         'pume_tot_score',
454                         )
455            dp['pume_tot_score'] = jamb.get(csv_d['pume_tot_score']) or "No Option Shaded"
456            pume = student.pume
457            pume.getContent().edit(mapping=dp)
458            #wftool.doActionFor(pume,'close')
459            pume.manage_setLocalRoles(sid, ['Owner',])
460            #student.getContent().createSubObjects()
461            dp = {}
462            if len(names) == 3:
463                dp['firstname'] = names[0].capitalize()
464                dp['middlename'] = names[1].capitalize()
465                dp['lastname'] = names[2].capitalize()
466            elif len(names) == 2:
467                dp['firstname'] = names[0].capitalize()
468                dp['middlename'] = ''
469                dp['lastname'] = names[1].capitalize()
470            else:
471                dp['firstname'] = ''
472                dp['middlename'] = ''
473                dp['lastname'] = jamb_name
474            dp['sex'] = jamb.get(csv_d['jamb_sex']) == 'F'
475            catalog_entry['sex'] = dp['sex']
476            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
477            student.invokeFactory('StudentPersonal','personal')
478            per = student.personal
479            per_doc = per.getContent()
480            per_doc.edit(mapping = dp)
481            per.manage_setLocalRoles(sid, ['Owner',])
482            if jamb.get(csv_d['stud_status']) == "Admitted":
483                wftool.doActionFor(student,'pume_pass')
484                wftool.doActionFor(student,'admit')
485            else:
486                wftool.doActionFor(student,'pume_fail')
487                wftool.doActionFor(student,'reject_admission')
488                continue
489            #
490            # Clearance
491            #
492            student.invokeFactory('StudentClearance','clearance')
493            #wftool.doActionFor(student.clearance,'open')
494            dp = {'Title': 'Clearance/Eligibility Record'}
495            student.clearance.manage_setLocalRoles(sid, ['Owner',])
496            #
497            # Study Course
498            #
499            student.invokeFactory('StudentStudyCourse','study_course')
500            study_course = student.study_course
501            dsc = {}
502            from_certificate = ['title',
503                               'max_elect',
504                               'max_pass',
505                               'n_core',
506                               'nr_years',
507                               'probation_credits',
508                               'promotion_credits',
509                               'start_level',
510                              ]
511            for f in from_certificate:
512                dsc[f] = getattr(cert_doc,f)
513            dsc['faculty'] = jamb.get(csv_d['faculty'])
514            dsc['department'] = jamb.get(csv_d['department'])
515            catalog_entry['faculty'] = jamb.get(csv_d['faculty'])
516            catalog_entry['department'] = jamb.get(csv_d['department'])
517            catalog_entry['course'] = cert_id
518            catalog_entry['level'] = getattr(cert_doc,'start_level')
519            dsc['study_course'] = cert_id
520            dsc['entry_session'] = jamb.get(csv_d['session'])
521            study_course.getContent().edit(mapping=dsc)
522            self.students_catalog.addRecord(**catalog_entry)
523            if tr_count > 1000:
524                if len(no_import) > 1:
525                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
526                             '\n'.join(no_import))
527                    no_import = []
528                em = '%d transactions commited\n' % tr_count
529                transaction.commit()
530                logger.info(em)
531                total += tr_count
532                tr_count = 0
533        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
534    ###)
535
536    security.declareProtected(ModifyPortalContent,"OLDloadPumeResultsFromCSV")###(
537    def OLDloadPumeResultsFromCSV(self):
538        """load Fulltime Studentdata from CSV values"""
539        import transaction
540        import random
541        wftool = self.portal_workflow
542        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
543        csv_d = {'jamb_reg_no': "JAMBRegno",
544                 'jamb_lastname': "Name",
545                 'pume_options': "Options",
546                 'session': "Session",
547                 'days': "Days",
548                 'response': "Responce",
549                 'wrong': "Wrong",
550                 'pume_eng_score': "EngScore",
551                 'pume_gen_score': "GenScore",
552                 'pume_tot_score': "Score",
553                 'batch': "Batch",
554                 'serial': "SerialNo",
555                 'jamb_score': "JambScore",
556                 'omitted':"Omitted",
557                 'search_key': "SearchKey",
558                 'jamb_sex': "Sex",
559                 'fac1': "Fac1",
560                 'fac2': "Fac2",
561                 'jamb_first_cos': "CourseofStudy",
562                 'stud_status':"StudStatus",
563                 'registered': "Registered",
564                 'jamb_state': "State",
565                 'eng_fail': "EngFail",
566                 'gen_fail': "GenFail",
567                 'un_ans_eng': "UnAnsEng",
568                 'un_ans_eng': "UnAnsGen",
569                 'total_ans': "TotalUnAns",
570                 'dept': "Dept",
571                 'jamb_second_cos': "Course2",
572                 'jamb_third_cos': "course3",
573                 }
574        csv_fields = [f[1] for f in csv_d.items()]
575        tr_count = 0
576        name = 'pume_results'
577        no_import = []
578        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
579        no_import.append('%s\n' % s)
580        logger = logging.getLogger('%s_import' % name)
581        logger.info('Start loading from %s.csv' % name)
582        try:
583            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
584        except:
585            logger.error('Error reading %s.csv' % name)
586            return
587        for jamb in result:
588            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
589            processing = "processing %s" % format
590            logger.info(processing % jamb)
591            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
592            #import pdb;pdb.set_trace()
593            res = self.portal_catalog({'portal_type': "StudentApplication",
594                                     'jamb_reg_no': jamb_reg_no })
595            if res:
596                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
597                logger.info(em)
598                no_import.append(em)
599                no_import.append(format % jamb)
600                continue
601            cert_id = jamb.get(csv_d['jamb_first_cos']).upper()
602            res = self.portal_catalog({'portal_type': "Certificate",
603                                     'id': cert_id })
604            if len(res) < 1:
605                em = 'No Certificate with ID %s \n' % cert_id
606                logger.info(em)
607                no_import.append(em)
608                no_import.append(format % jamb)
609                continue
610            cert = res[0].getObject()
611            cert_path = res[0].getPath()
612            cert_doc = cert.getContent()
613            jamb_name = jamb.get(csv_d['jamb_lastname'])
614            jamb_name.replace('>','')
615            names = jamb_name.split()
616            letter = names[-1][0].upper()
617            sid = self.generateStudentId(letter)
618            not_created = True
619            while not_created:
620                try:
621                    students_folder.invokeFactory('Student', sid)
622                    not_created = False
623                except BadRequest:
624                    sid = self.generateStudentId(letter)
625            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
626            student = getattr(self,sid)
627            student.manage_setLocalRoles(sid, ['Owner',])
628            student.invokeFactory('StudentClearance','clearance')
629            #wftool.doActionFor(student.clearance,'open')
630            dp = {'Title': 'Clearance/Eligibility Record'}
631            student.clearance.manage_setLocalRoles(sid, ['Owner',])
632            student.invokeFactory('StudentPume','pume')
633            dp = {'Title': 'Pume Data'}
634            student.invokeFactory('StudentApplication','application')
635            da = {'Title': 'Application Data'}
636            da["jamb_lastname"] = jamb_name
637            da_fields = ('jamb_reg_no',
638                         'jamb_sex',
639                         'jamb_state',
640                         'jamb_score',
641                         'jamb_first_cos',
642                         'jamb_sex',
643                         'jamb_state',
644                         'jamb_first_cos',
645                         'jamb_second_cos',
646                         )
647            for f in da_fields:
648                da[f] = jamb.get(csv_d[f])
649            app = student.application
650            app.getContent().edit(mapping=da)
651            app.manage_setLocalRoles(sid, ['Owner',])
652            #wftool.doActionFor(app,'close')
653            dp_fields = (
654                         'pume_eng_score',
655                         'pume_gen_score',
656                         'pume_tot_score',
657                         )
658            for f in dp_fields:
659                dp[f] = float(jamb.get(csv_d[f]))
660            pume = student.pume
661            pume.getContent().edit(mapping=dp)
662            #wftool.doActionFor(pume,'close')
663            pume.manage_setLocalRoles(sid, ['Owner',])
664            #
665            # Study Course
666            #
667            student.invokeFactory('StudentStudyCourse','study_course')
668            study_course = student.study_course
669            dsc = {}
670            from_certificate = ['title',
671                               'max_elect',
672                               'max_pass',
673                               'n_core',
674                               'nr_years',
675                               'probation_credits',
676                               'promotion_credits',
677                               'start_level',
678                              ]
679            for f in from_certificate:
680                dsc[f] = getattr(cert_doc,f)
681            cpl = cert_path.split('/')
682            dsc['faculty'] = cpl[-4]
683            dsc['department'] = cpl[-3]
684            dsc['study_course'] = cert_id
685            dsc['entry_session'] = jamb.get(csv_d['session'])
686            study_course.getContent().edit(mapping=dsc)
687            student.getContent().createSubObjects()
688            if dp['pume_tot_score']>49:
689                wftool.doActionFor(student,'pume_pass')
690                wftool.doActionFor(student,'admit')
691            else:
692                wftool.doActionFor(student,'pume_fail')
693                wftool.doActionFor(student,'reject_admission')
694            if len(no_import) > 1:
695                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
696                     '\n'.join(no_import))
697        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
698    ###)
699
700    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
701    def loadFullTimeStudentsResultsFromCSV(self):
702        """load Fulltime Studentdata from CSV values"""
703        #return
704        level_wf_actions = {}
705        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
706        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
707        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
708        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
709        import transaction
710        wftool = self.portal_workflow
711        tr_count = 0
712        name = 'short_full_time_results_2004_2005'
713        no_import = False
714        if not no_import:
715            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
716            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
717        logger = logging.getLogger('%s_import' % name)
718        logger.info('Start loading from %s.csv' % name)
719        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
720        try:
721            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
722        except:
723            logger.error('Error reading %s.csv' % name)
724            return
725        l = self.portal_catalog({'meta_type': "Course"})
726        courses = {}
727        for c in l:
728            courses[c.id] = c.getObject()
729        level_changed = False
730        student_changed = False
731        sid = ''
732        #import pdb;pdb.set_trace()
733        for result in results:
734            temp_sid = result.get('Matnumber')
735            if temp_sid != sid:
736                student_changed = True
737                res = self.portal_catalog({'meta_type': "StudentClearance",
738                                         'SearchableText': temp_sid })
739                if not res:
740                    em = 'Student with ID %(Matnumber)s not found\n' % result
741                    logger.info(em)
742                    no_import.write(em)
743                    no_import.write('"%(Matnumber)s","%(CosCode)s","%(Ansbook)s","%(CosStuatus)s","%(Session)s","%(Mat_Cos)s","%(Score)s","%(CarryLevel)s","%(Grade)s","%(Weight)s","%(Semster)s","%(Verdict)s","%(Level)s","%(id)s","%(GPA)s"\n' % result)
744                    continue
745                elif len(res) > 1:
746                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
747                    logger.info(em)
748                    no_import.write(em)
749                    no_import.write('"%(Matnumber)s","%(CosCode)s","%(Ansbook)s","%(CosStuatus)s","%(Session)s","%(Mat_Cos)s","%(Score)s","%(CarryLevel)s","%(Grade)s","%(Weight)s","%(Semster)s","%(Verdict)s","%(Level)s","%(id)s","%(GPA)s"\n' % result)
750                    continue
751                sid = temp_sid
752                sf = res[0].getObject().aq_parent
753                sc = getattr(sf,'study_course')
754                level = ''
755            else:
756                student_changed = False
757            course = result.get('CosCode')
758            if course not in courses.keys():
759                em = 'Course with ID %(CosCode)s not found\n' % result
760                logger.info(em)
761                no_import.write(em)
762                no_import.write('"%(Matnumber)s","%(CosCode)s","%(Ansbook)s","%(CosStuatus)s","%(Session)s","%(Mat_Cos)s","%(Score)s","%(CarryLevel)s","%(Grade)s","%(Weight)s","%(Semster)s","%(Verdict)s","%(Level)s","%(id)s","%(GPA)s"\n' % result)
763                continue
764            course_doc = courses[course].getContent()
765            temp_level = result.get('Level')
766            student_id = sf.getId()
767            result['StudentId'] = student_id
768            if temp_level != level:
769                try:
770                    int(temp_level)
771                except:
772                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
773                    logger.info(em)
774                    no_import.write(em)
775                    no_import.write('"%(Matnumber)s","%(CosCode)s","%(Ansbook)s","%(CosStuatus)s","%(Session)s","%(Mat_Cos)s","%(Score)s","%(CarryLevel)s","%(Grade)s","%(Weight)s","%(Semster)s","%(Verdict)s","%(Level)s","%(id)s","%(GPA)s"\n' % result)
776                    continue
777                level_changed = True
778                if 'dlev' in vars().keys():
779                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
780                level = temp_level
781                l = getattr(sc,level,None)
782                if l is None:
783                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
784                    sc.invokeFactory('StudentStudyLevel', level)
785                    l = getattr(sc, level)
786                    l.manage_setLocalRoles(student_id, ['Owner',])
787            else:
788                level_changed = False
789            cr = getattr(l,course,None)
790            if cr is None:
791                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
792                l.invokeFactory('StudentCourseResult',course)
793            cr = getattr(l,course)
794            dcr = {}
795            from_course = ['title',
796                           'credits',
797                           'passmark',
798                           ]
799            for f in from_course:
800                dcr[f] = getattr(course_doc,f)
801            dlev = {}
802            dcr['ansbook'] = result.get('Ansbook')
803            dcr['semester'] = getInt(result.get('Semster'))
804            dcr['status'] = result.get('CosStuatus')
805            dcr['score'] = getInt(result.get('Score'))
806            dlev['session'] = result.get('Session')
807            dcr['carry_level'] = result.get('CarryLevel')
808            dcr['grade'] = result.get('Grade')
809            dcr['weight'] = result.get('Weight')
810            dlev['verdict'] = result.get('Verdict')
811            dcr['import_id'] = result.get('id')
812            gpa = result.get('GPA').replace(',','.')
813            dlev['imported_gpa'] = getFloat(gpa)
814            cr.getContent().edit(mapping = dcr)
815            cr.manage_setLocalRoles(student_id, ['Owner',])
816            l.getContent().edit(mapping = dlev)
817            if tr_count > MAX_TRANS:
818                transaction.commit()
819                tr_count = 0
820            tr_count += 1
821            wftool.doActionFor(cr,'close')
822        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
823        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
824
825###)
826
827    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
828    def loadJAMBFromCSV(self):
829        """load JAMB data from CSV values"""
830        #return
831        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
832        import transaction
833        tr_count = 0
834        name = 'SampleJAMBDataII'
835        wftool = self.portal_workflow
836        no_import = False
837        if not no_import:
838            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
839            no_import.write('REG-NO,NAME,SEX,STATE,LGA,ENG-SCORE,SUBJ1,SUBJ1-SCORE,SUBJ2,SUBJ2-SCORE,SUBJ3,SUBJ3-SCORE,AGGREGATE,UNIV1,FACULTY1,COURSE1,UNIV2,FACULTY2,COURSE2')
840        logger = logging.getLogger('%s_import' % name)
841        logger.info('Start loading from %s.csv' % name)
842        try:
843            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
844        except:
845            logger.error('Error reading %s.csv' % name)
846            return
847        for jamb in result:
848            logger.info('processing %(REG-NO)s,%(NAME)s,%(SEX)s,%(STATE)s,%(LGA)s,%(ENG-SCORE)s,%(SUBJ1)s,%(SUBJ1-SCORE)s,%(SUBJ2)s,%(SUBJ2-SCORE)s,%(SUBJ3)s,%(SUBJ3-SCORE)s,%(AGGREGATE)s,%(UNIV1)s,%(FACULTY1)s,%(COURSE1)s,%(UNIV2)s,%(FACULTY2)s,%(COURSE2)s\n' % jamb)
849            jamb_reg_no = jamb.get('REG-NO')
850            res = self.portal_catalog({'meta_type': "StudentApplication",
851                                     'jamb_reg_no': jamb_reg_no })
852            if res:
853                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
854                logger.info(em)
855                no_import.write(em)
856                no_import.write('%(REG-NO)s,%(NAME)s,%(SEX)s,%(STATE)s,%(LGA)s,%(ENG-SCORE)s,%(SUBJ1)s,%(SUBJ1-SCORE)s,%(SUBJ2)s,%(SUBJ2-SCORE)s,%(SUBJ3)s,%(SUBJ3-SCORE)s,%(AGGREGATE)s,%(UNIV1)s,%(FACULTY1)s,%(COURSE1)s,%(UNIV2)s,%(FACULTY2)s,%(COURSE2)s\n' % jamb)
857                continue
858            jamb_name = jamb.get("NAME")
859            jamb_name.replace('>','')
860            names = jamb_name.split()
861            letter = names[-1][0].upper()
862            sid = self.generateStudentId(letter)
863            not_created = True
864            while not_created:
865                try:
866                    students_folder.invokeFactory('Student', sid)
867                    not_created = False
868                except BadRequest:
869                    sid = self.generateStudentId(letter)
870            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
871            student = getattr(self,sid)
872            student.manage_setLocalRoles(sid, ['Owner',])
873            student.invokeFactory('StudentApplication','application')
874            da = {'Title': 'Application Data'}
875            da["jamb_reg_no"] = jamb.get("REG-NO")
876            da["jamb_lastname"] = jamb_name
877            da["jamb_sex"] = jamb.get("SEX")
878            da["jamb_state"] = jamb.get("STATE")
879            da["jamb_lga"] = jamb.get("LGA")
880            da["jamb_score"] = jamb.get("AGGREGATE")
881            da["jamb_first_cos"] = jamb.get("COURSE1")
882            da["jamb_second_cos"] = jamb.get("COURSE2")
883            da["jamb_first_uni"] = jamb.get("UNIV1")
884            da["jamb_second_uni"] = jamb.get("UNIV2")
885            app = student.application
886            app_doc = app.getContent()
887            app_doc.edit(mapping=da)
888            #wftool.doActionFor(app,'open',dest_container=app)
889            app.manage_setLocalRoles(sid, ['Owner',])
890            student.getContent().createSubObjects()
891        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
892    ###)
893
894
895    security.declareProtected(View,"fixOwnership")
896    def fixOwnership(self):
897        """fix Ownership"""
898        for s in self.portal_catalog(meta_type = 'Student'):
899            student = s.getObject()
900            sid = s.getId
901            import pdb;pdb.set_trace()
902            student.application.manage_setLocalRoles(sid, ['Owner',])
903            student.personal.manage_setLocalRoles(sid, ['Owner',])
904
905    security.declareProtected(View,"Title")
906    def Title(self):
907        """compose title"""
908        return "Student Section"
909
910    def generateStudentId(self,letter): ###(
911        import random
912        r = random
913        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
914            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
915        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
916        sid = "%c%d" % (letter,r.randint(99999,1000000))
917        while hasattr(students, sid):
918            sid = "%c%d" % (letter,r.randint(99999,1000000))
919        return sid
920        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
921    ###)
922
923InitializeClass(StudentsFolder)
924
925def addStudentsFolder(container, id, REQUEST=None, **kw):
926    """Add a Student."""
927    ob = StudentsFolder(id, **kw)
928    return CPSBase_adder(container, ob, REQUEST=REQUEST)
929###)
930
931class Student(CPSDocument): ###(
932    """
933    WAeUP Student container for the various student data
934    """
935    meta_type = 'Student'
936    portal_type = meta_type
937    security = ClassSecurityInfo()
938
939    security.declareProtected(View,"Title")
940    def Title(self):
941        """compose title"""
942        reg_nr = self.getId()[1:]
943        data = getattr(self,'personal',None)
944        if data:
945            content = data.getContent()
946            return "%s %s" % (content.firstname,content.lastname)
947        data = getattr(self,'application',None)
948        if data:
949            content = data.getContent()
950            return "%s" % (content.jamb_lastname)
951        return self.title
952
953    security.declarePrivate('makeStudentMember') ###(
954    def makeStudentMember(self,sid,password='uNsEt'):
955        """make the student a member"""
956        membership = self.portal_membership
957        membership.addMember(sid,
958                             password ,
959                             roles=('Member',
960                                     'Student',
961                                     ),
962                             domains='',
963                             properties = {'memberareaCreationFlag': False,
964                                           'homeless': True},)
965        member = membership.getMemberById(sid)
966        self.portal_registration.afterAdd(member, sid, password, None)
967        self.manage_setLocalRoles(sid, ['Owner',])
968
969###)
970
971    security.declareProtected(View,'createSubObjects') ###(
972    def createSubObjects(self):
973        """make the student a member"""
974        dp = {'Title': 'Personal Data'}
975        app_doc = self.application.getContent()
976        names = app_doc.jamb_lastname.split()
977        if len(names) == 3:
978            dp['firstname'] = names[0].capitalize()
979            dp['middlename'] = names[1].capitalize()
980            dp['lastname'] = names[2].capitalize()
981        elif len(names) == 2:
982            dp['firstname'] = names[0].capitalize()
983            dp['lastname'] = names[1].capitalize()
984        else:
985            dp['lastname'] = app_doc.jamb_lastname
986        dp['sex'] = app_doc.jamb_sex == 'F'
987        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
988        proxy = self.aq_parent
989        proxy.invokeFactory('StudentPersonal','personal')
990        per = proxy.personal
991        per_doc = per.getContent()
992        per_doc.edit(mapping = dp)
993        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
994        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
995
996###)
997
998InitializeClass(Student)
999
1000def addStudent(container, id, REQUEST=None, **kw):
1001    """Add a Student."""
1002    ob = Student(id, **kw)
1003    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1004
1005###)
1006
1007class StudentAccommodation(CPSDocument): ###(
1008    """
1009    WAeUP Student container for the various student data
1010    """
1011    meta_type = 'StudentAccommodation'
1012    portal_type = meta_type
1013    security = ClassSecurityInfo()
1014
1015    security.declareProtected(View,"Title")
1016    def Title(self):
1017        """compose title"""
1018        content = self.getContent()
1019        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
1020        return "Accommodation Data for Session %s" % content.session
1021
1022
1023InitializeClass(StudentAccommodation)
1024
1025def addStudentAccommodation(container, id, REQUEST=None, **kw):
1026    """Add a Students personal data."""
1027    ob = StudentAccommodation(id, **kw)
1028    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1029
1030###)
1031
1032class StudentPersonal(CPSDocument): ###(
1033    """
1034    WAeUP Student container for the various student data
1035    """
1036    meta_type = 'StudentPersonal'
1037    portal_type = meta_type
1038    security = ClassSecurityInfo()
1039
1040    security.declareProtected(View,"Title")
1041    def Title(self):
1042        """compose title"""
1043        content = self.getContent()
1044        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
1045        return "Personal Data"
1046
1047
1048InitializeClass(StudentPersonal)
1049
1050def addStudentPersonal(container, id, REQUEST=None, **kw):
1051    """Add a Students personal data."""
1052    ob = StudentPersonal(id, **kw)
1053    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1054
1055###)
1056
1057class StudentClearance(CPSDocument): ###(
1058    """
1059    WAeUP Student container for the various student data
1060    """
1061    meta_type = 'StudentClearance'
1062    portal_type = meta_type
1063    security = ClassSecurityInfo()
1064
1065    security.declareProtected(View,"Title")
1066    def Title(self):
1067        """compose title"""
1068        content = self.getContent()
1069        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
1070        return "Clearance/Eligibility Record"
1071
1072
1073InitializeClass(StudentClearance)
1074
1075def addStudentClearance(container, id, REQUEST=None, **kw):
1076    """Add a Students personal data."""
1077    ob = StudentClearance(id, **kw)
1078    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1079
1080###)
1081
1082class StudentStudyLevel(CPSDocument): ###(
1083    """
1084    WAeUP Student container for the various student data
1085    """
1086    meta_type = 'StudentStudyLevel'
1087    portal_type = meta_type
1088    security = ClassSecurityInfo()
1089
1090    security.declareProtected(View,"Title")
1091    def Title(self):
1092        """compose title"""
1093        return "Level %s" % self.aq_parent.getId()
1094
1095##    security.declarePublic("gpa")
1096##    def gpa(self):
1097##        """calculate the gpa"""
1098##        sum = 0
1099##        course_count = 0
1100##        for sc in self.objectValues():
1101##            result = sc.getContent()
1102##            if not result.grade:
1103##                continue
1104##            res = self.portal_catalog({'meta_type': 'Course',
1105##                                          'id': sc.aq_parent.id})
1106##            if len(res) != 1:
1107##                continue
1108##            course = res[0].getObject().getContent()
1109##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
1110##            course_count += 1
1111##        if course_count:
1112##            return sum/course_count
1113##        return 0.0
1114
1115InitializeClass(StudentStudyLevel)
1116
1117def addStudentStudyLevel(container, id, REQUEST=None, **kw):
1118    """Add a Students personal data."""
1119    ob = StudentStudyLevel(id, **kw)
1120    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1121
1122###)
1123
1124class StudentStudyCourse(CPSDocument): ###(
1125    """
1126    WAeUP Student container for the various student data
1127    """
1128    meta_type = 'StudentStudyCourse'
1129    portal_type = meta_type
1130    security = ClassSecurityInfo()
1131
1132    security.declareProtected(View,"Title")
1133    def Title(self):
1134        """compose title"""
1135        content = self.getContent()
1136        return "Study Course"
1137
1138
1139InitializeClass(StudentStudyCourse)
1140
1141def addStudentStudyCourse(container, id, REQUEST=None, **kw):
1142    """Add a Students personal data."""
1143    ob = StudentStudyCourse(id, **kw)
1144    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1145
1146###)
1147
1148class StudentApplication(CPSDocument): ###(
1149    """
1150    WAeUP Student container for the various student data
1151    """
1152    meta_type = 'StudentApplication'
1153    portal_type = meta_type
1154    security = ClassSecurityInfo()
1155
1156    security.declareProtected(View,"Title")
1157    def Title(self):
1158        """compose title"""
1159        return "Application Data"
1160
1161
1162InitializeClass(StudentApplication)
1163
1164def addStudentApplication(container, id, REQUEST=None, **kw):
1165    """Add a Students eligibility data."""
1166    ob = StudentApplication(id, **kw)
1167    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1168###)
1169
1170
1171class StudentPume(CPSDocument): ###(
1172    """
1173    WAeUP Student container for the various student data
1174    """
1175    meta_type = 'StudentPume'
1176    portal_type = meta_type
1177    security = ClassSecurityInfo()
1178
1179    security.declareProtected(View,"Title")
1180    def Title(self):
1181        """compose title"""
1182        return "PUME Results"
1183
1184
1185InitializeClass(StudentPume)
1186
1187def addStudentPume(container, id, REQUEST=None, **kw):
1188    """Add a Students PUME data."""
1189    ob = StudentPume(id, **kw)
1190    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1191###)
1192
1193##class StudentSemester(CPSDocument): ###(
1194##    """
1195##    WAeUP StudentSemester containing the courses and students
1196##    """
1197##    meta_type = 'StudentSemester'
1198##    portal_type = meta_type
1199##    security = ClassSecurityInfo()
1200##
1201##InitializeClass(StudentSemester)
1202##
1203##def addStudentSemester(container, id, REQUEST=None, **kw):
1204##    """Add a StudentSemester."""
1205##    ob = StudentSemester(id, **kw)
1206##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1207##
1208#####)
1209
1210##class Semester(CPSDocument): ###(
1211##    """
1212##    WAeUP Semester containing the courses and students
1213##    """
1214##    meta_type = 'Semester'
1215##    portal_type = meta_type
1216##    security = ClassSecurityInfo()
1217##
1218##InitializeClass(Semester)
1219##
1220##def addSemester(container, id, REQUEST=None, **kw):
1221##    """Add a Semester."""
1222##    ob = Semester(id, **kw)
1223##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1224##
1225#####)
1226
1227class StudentCourseResult(CPSDocument): ###(
1228    """
1229    WAeUP StudentCourseResult
1230    """
1231    meta_type = 'StudentCourseResult'
1232    portal_type = meta_type
1233    security = ClassSecurityInfo()
1234
1235    def getCourseEntry(self,cid):
1236        res = self.portal_catalog({'meta_type': "Course",
1237                                           'id': cid})
1238        if res:
1239            return res[-1]
1240        else:
1241            return None
1242
1243    security.declareProtected(View,"Title")
1244    def Title(self):
1245        """compose title"""
1246        cid = self.aq_parent.getId()
1247        ce = self.getCourseEntry(cid)
1248        if ce:
1249            return "%s" % ce.Title
1250        return "No course with id %s" % cid
1251
1252InitializeClass(StudentCourseResult)
1253
1254def addStudentCourseResult(container, id, REQUEST=None, **kw):
1255    """Add a StudentCourseResult."""
1256    ob = StudentCourseResult(id, **kw)
1257    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1258###)
1259
1260# Backward Compatibility StudyLevel
1261
1262from Products.WAeUP_SRP.Academics import StudyLevel
1263
1264from Products.WAeUP_SRP.Academics import addStudyLevel
1265
Note: See TracBrowser for help on using the repository browser.