source: WAeUP_SRP/trunk/Students.py @ 1000

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

MAX_TRANS = 1000

  • Property svn:keywords set to Id
File size: 53.1 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 981 2006-12-02 07:22:17Z 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 = 1000
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                 'app_mobile': "PhoneNumbers",
346                 }
347        csv_fields = [f[1] for f in csv_d.items()]
348        tr_count = 0
349        total = 0
350        #name = 'pume_results'
351        name = 'Admitted'
352        no_import = []
353        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
354        no_import.append('"Error",%s' % s)
355        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
356        no_certificate = "no certificate %s" % format
357        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
358                    '\n'.join(no_import))
359        logger = logging.getLogger('%s_import' % name)
360        logger.info('Start loading from %s.csv' % name)
361        l = self.portal_catalog({'meta_type': "Certificate"})
362        certs = {}
363        cert_docs = {}
364        for f in l:
365            certs[f.getId] = f.getObject().getContent()
366        try:
367            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
368        except:
369            logger.error('Error reading %s.csv' % name)
370            return
371        for jamb in result:
372            jamb['Error'] = "Processing "
373            logger.info(format % jamb)
374            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
375            res = self.portal_catalog({'portal_type': "StudentApplication",
376                                     'SearchableText': jamb_reg_no })
377            if res:
378                em = 'Student with RegNo %s already exists\n' % jamb_reg_no
379                logger.info(em)
380                jamb['Error'] = "Student exists"
381                no_import.append(format % jamb)
382                continue
383            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
384            if cert_id not in certs.keys():
385                em = 'No Certificate with ID %s \n' % cert_id
386                logger.info(em)
387                jamb['Error'] = "No Certificate %s" % cert_id
388                no_import.append( format % jamb)
389                continue
390            cert_doc = certs[cert_id]
391            catalog_entry = {}
392            catalog_entry['jamb_reg_no'] = jamb_reg_no
393            jamb_name = jamb.get(csv_d['jamb_lastname'])
394            jamb_name.replace('>','')
395            jamb_name.replace('<','')
396            names = jamb_name.split()
397            letter = names[-1][0].upper()
398            sid = self.generateStudentId(letter)
399            not_created = True
400            while not_created:
401                try:
402                    students_folder.invokeFactory('Student', sid)
403                    not_created = False
404                except BadRequest:
405                    sid = self.generateStudentId(letter)
406            catalog_entry['id'] = sid
407            tr_count += 1
408            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
409            student = getattr(self,sid)
410            student.manage_setLocalRoles(sid, ['Owner',])
411            student.invokeFactory('StudentPume','pume')
412            dp = {'Title': 'Pume Data'}
413            student.invokeFactory('StudentApplication','application')
414            da = {'Title': 'Application Data'}
415            da["jamb_lastname"] = jamb_name
416            da_fields = ('jamb_reg_no',
417                         'jamb_sex',
418                         #'jamb_state',
419                         'jamb_score',
420##                         'jamb_first_cos',
421                         'jamb_sex',
422                         'jamb_state',
423                         'jamb_lga',
424                         'app_email',
425                         'app_mobile',
426                         )
427            for f in da_fields:
428                da[f] = jamb.get(csv_d[f])
429            catalog_entry['email'] = jamb.get(csv_d['app_email'])
430            app = student.application
431            app_doc = app.getContent()
432            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
433            #import pdb;pdb.set_trace()
434            if os.path.exists(picture):
435                file = open(picture)
436                if False:
437                    img = PIL.Image.open(file)
438                    img.thumbnail((150,200),
439                                  resample=PIL.Image.ANTIALIAS)
440                    # We now need a buffer to write to. It can't be the same
441                    # as the inbuffer as the PNG writer will write over itself.
442                    outfile = StringIO()
443                    img.save(outfile, format=img.format)
444                else:
445                    outfile = file.read()
446                app_doc.manage_addFile('passport',
447                                       file=outfile,
448                                       title="%s.jpg" % jamb_reg_no)
449            app.getContent().edit(mapping=da)
450            app.manage_setLocalRoles(sid, ['Owner',])
451            #wftool.doActionFor(app,'close')
452            dp_fields = (
453                         #'pume_eng_score',
454                         #'pume_gen_score',
455                         'pume_tot_score',
456                         )
457            dp['pume_tot_score'] = jamb.get(csv_d['pume_tot_score']) or "No Option Shaded"
458            pume = student.pume
459            pume.getContent().edit(mapping=dp)
460            #wftool.doActionFor(pume,'close')
461            pume.manage_setLocalRoles(sid, ['Owner',])
462            #student.getContent().createSubObjects()
463            dp = {}
464            if len(names) == 3:
465                dp['firstname'] = names[0].capitalize()
466                dp['middlename'] = names[1].capitalize()
467                dp['lastname'] = names[2].capitalize()
468            elif len(names) == 2:
469                dp['firstname'] = names[0].capitalize()
470                dp['middlename'] = ''
471                dp['lastname'] = names[1].capitalize()
472            else:
473                dp['firstname'] = ''
474                dp['middlename'] = ''
475                dp['lastname'] = jamb_name
476            dp['sex'] = jamb.get(csv_d['jamb_sex']) == 'F'
477            catalog_entry['sex'] = dp['sex']
478            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
479            student.invokeFactory('StudentPersonal','personal')
480            per = student.personal
481            per_doc = per.getContent()
482            per_doc.edit(mapping = dp)
483            per.manage_setLocalRoles(sid, ['Owner',])
484            if jamb.get(csv_d['stud_status']) == "Admitted":
485                wftool.doActionFor(student,'pume_pass')
486                wftool.doActionFor(student,'admit')
487            else:
488                wftool.doActionFor(student,'pume_fail')
489                wftool.doActionFor(student,'reject_admission')
490                continue
491            #
492            # Clearance
493            #
494            student.invokeFactory('StudentClearance','clearance')
495            #wftool.doActionFor(student.clearance,'open')
496            dp = {'Title': 'Clearance/Eligibility Record'}
497            student.clearance.manage_setLocalRoles(sid, ['Owner',])
498            #
499            # Study Course
500            #
501            student.invokeFactory('StudentStudyCourse','study_course')
502            study_course = student.study_course
503            dsc = {}
504            from_certificate = ['title',
505                               'max_elect',
506                               'max_pass',
507                               'n_core',
508                               'nr_years',
509                               'probation_credits',
510                               'promotion_credits',
511                               'start_level',
512                              ]
513            for f in from_certificate:
514                dsc[f] = getattr(cert_doc,f)
515            dsc['faculty'] = jamb.get(csv_d['faculty'])
516            dsc['department'] = jamb.get(csv_d['department'])
517            catalog_entry['faculty'] = jamb.get(csv_d['faculty'])
518            catalog_entry['department'] = jamb.get(csv_d['department'])
519            catalog_entry['course'] = cert_id
520            catalog_entry['level'] = getattr(cert_doc,'start_level')
521            dsc['study_course'] = cert_id
522            dsc['entry_session'] = jamb.get(csv_d['session'])
523            study_course.getContent().edit(mapping=dsc)
524            self.students_catalog.addRecord(**catalog_entry)
525            if tr_count > MAX_TRANS:
526                if len(no_import) > 1:
527                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
528                             '\n'.join(no_import))
529                    no_import = []
530                em = '%d transactions commited\n' % tr_count
531                transaction.commit()
532                logger.info(em)
533                total += tr_count
534                tr_count = 0
535        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
536    ###)
537
538    security.declareProtected(ModifyPortalContent,"OLDloadPumeResultsFromCSV")###(
539    def OLDloadPumeResultsFromCSV(self):
540        """load Fulltime Studentdata from CSV values"""
541        import transaction
542        import random
543        wftool = self.portal_workflow
544        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
545        csv_d = {'jamb_reg_no': "JAMBRegno",
546                 'jamb_lastname': "Name",
547                 'pume_options': "Options",
548                 'session': "Session",
549                 'days': "Days",
550                 'response': "Responce",
551                 'wrong': "Wrong",
552                 'pume_eng_score': "EngScore",
553                 'pume_gen_score': "GenScore",
554                 'pume_tot_score': "Score",
555                 'batch': "Batch",
556                 'serial': "SerialNo",
557                 'jamb_score': "JambScore",
558                 'omitted':"Omitted",
559                 'search_key': "SearchKey",
560                 'jamb_sex': "Sex",
561                 'fac1': "Fac1",
562                 'fac2': "Fac2",
563                 'jamb_first_cos': "CourseofStudy",
564                 'stud_status':"StudStatus",
565                 'registered': "Registered",
566                 'jamb_state': "State",
567                 'eng_fail': "EngFail",
568                 'gen_fail': "GenFail",
569                 'un_ans_eng': "UnAnsEng",
570                 'un_ans_eng': "UnAnsGen",
571                 'total_ans': "TotalUnAns",
572                 'dept': "Dept",
573                 'jamb_second_cos': "Course2",
574                 'jamb_third_cos': "course3",
575                 }
576        csv_fields = [f[1] for f in csv_d.items()]
577        tr_count = 0
578        name = 'pume_results'
579        no_import = []
580        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
581        no_import.append('%s\n' % s)
582        logger = logging.getLogger('%s_import' % name)
583        logger.info('Start loading from %s.csv' % name)
584        try:
585            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
586        except:
587            logger.error('Error reading %s.csv' % name)
588            return
589        for jamb in result:
590            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
591            processing = "processing %s" % format
592            logger.info(processing % jamb)
593            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
594            #import pdb;pdb.set_trace()
595            res = self.portal_catalog({'portal_type': "StudentApplication",
596                                     'jamb_reg_no': jamb_reg_no })
597            if res:
598                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
599                logger.info(em)
600                no_import.append(em)
601                no_import.append(format % jamb)
602                continue
603            cert_id = jamb.get(csv_d['jamb_first_cos']).upper()
604            res = self.portal_catalog({'portal_type': "Certificate",
605                                     'id': cert_id })
606            if len(res) < 1:
607                em = 'No Certificate with ID %s \n' % cert_id
608                logger.info(em)
609                no_import.append(em)
610                no_import.append(format % jamb)
611                continue
612            cert = res[0].getObject()
613            cert_path = res[0].getPath()
614            cert_doc = cert.getContent()
615            jamb_name = jamb.get(csv_d['jamb_lastname'])
616            jamb_name.replace('>','')
617            names = jamb_name.split()
618            letter = names[-1][0].upper()
619            sid = self.generateStudentId(letter)
620            not_created = True
621            while not_created:
622                try:
623                    students_folder.invokeFactory('Student', sid)
624                    not_created = False
625                except BadRequest:
626                    sid = self.generateStudentId(letter)
627            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
628            student = getattr(self,sid)
629            student.manage_setLocalRoles(sid, ['Owner',])
630            student.invokeFactory('StudentClearance','clearance')
631            #wftool.doActionFor(student.clearance,'open')
632            dp = {'Title': 'Clearance/Eligibility Record'}
633            student.clearance.manage_setLocalRoles(sid, ['Owner',])
634            student.invokeFactory('StudentPume','pume')
635            dp = {'Title': 'Pume Data'}
636            student.invokeFactory('StudentApplication','application')
637            da = {'Title': 'Application Data'}
638            da["jamb_lastname"] = jamb_name
639            da_fields = ('jamb_reg_no',
640                         'jamb_sex',
641                         'jamb_state',
642                         'jamb_score',
643                         'jamb_first_cos',
644                         'jamb_sex',
645                         'jamb_state',
646                         'jamb_first_cos',
647                         'jamb_second_cos',
648                         )
649            for f in da_fields:
650                da[f] = jamb.get(csv_d[f])
651            app = student.application
652            app.getContent().edit(mapping=da)
653            app.manage_setLocalRoles(sid, ['Owner',])
654            #wftool.doActionFor(app,'close')
655            dp_fields = (
656                         'pume_eng_score',
657                         'pume_gen_score',
658                         'pume_tot_score',
659                         )
660            for f in dp_fields:
661                dp[f] = float(jamb.get(csv_d[f]))
662            pume = student.pume
663            pume.getContent().edit(mapping=dp)
664            #wftool.doActionFor(pume,'close')
665            pume.manage_setLocalRoles(sid, ['Owner',])
666            #
667            # Study Course
668            #
669            student.invokeFactory('StudentStudyCourse','study_course')
670            study_course = student.study_course
671            dsc = {}
672            from_certificate = ['title',
673                               'max_elect',
674                               'max_pass',
675                               'n_core',
676                               'nr_years',
677                               'probation_credits',
678                               'promotion_credits',
679                               'start_level',
680                              ]
681            for f in from_certificate:
682                dsc[f] = getattr(cert_doc,f)
683            cpl = cert_path.split('/')
684            dsc['faculty'] = cpl[-4]
685            dsc['department'] = cpl[-3]
686            dsc['study_course'] = cert_id
687            dsc['entry_session'] = jamb.get(csv_d['session'])
688            study_course.getContent().edit(mapping=dsc)
689            student.getContent().createSubObjects()
690            if dp['pume_tot_score']>49:
691                wftool.doActionFor(student,'pume_pass')
692                wftool.doActionFor(student,'admit')
693            else:
694                wftool.doActionFor(student,'pume_fail')
695                wftool.doActionFor(student,'reject_admission')
696            if len(no_import) > 1:
697                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
698                     '\n'.join(no_import))
699        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
700    ###)
701
702    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
703    def loadFullTimeStudentsResultsFromCSV(self):
704        """load Fulltime Studentdata from CSV values"""
705        #return
706        level_wf_actions = {}
707        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
708        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
709        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
710        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
711        import transaction
712        wftool = self.portal_workflow
713        tr_count = 0
714        name = 'short_full_time_results_2004_2005'
715        no_import = False
716        if not no_import:
717            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
718            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
719        logger = logging.getLogger('%s_import' % name)
720        logger.info('Start loading from %s.csv' % name)
721        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
722        try:
723            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
724        except:
725            logger.error('Error reading %s.csv' % name)
726            return
727        l = self.portal_catalog({'meta_type': "Course"})
728        courses = {}
729        for c in l:
730            courses[c.id] = c.getObject()
731        level_changed = False
732        student_changed = False
733        sid = ''
734        #import pdb;pdb.set_trace()
735        for result in results:
736            temp_sid = result.get('Matnumber')
737            if temp_sid != sid:
738                student_changed = True
739                res = self.portal_catalog({'meta_type': "StudentClearance",
740                                         'SearchableText': temp_sid })
741                if not res:
742                    em = 'Student with ID %(Matnumber)s not found\n' % result
743                    logger.info(em)
744                    no_import.write(em)
745                    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)
746                    continue
747                elif len(res) > 1:
748                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
749                    logger.info(em)
750                    no_import.write(em)
751                    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)
752                    continue
753                sid = temp_sid
754                sf = res[0].getObject().aq_parent
755                sc = getattr(sf,'study_course')
756                level = ''
757            else:
758                student_changed = False
759            course = result.get('CosCode')
760            if course not in courses.keys():
761                em = 'Course with ID %(CosCode)s not found\n' % result
762                logger.info(em)
763                no_import.write(em)
764                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)
765                continue
766            course_doc = courses[course].getContent()
767            temp_level = result.get('Level')
768            student_id = sf.getId()
769            result['StudentId'] = student_id
770            if temp_level != level:
771                try:
772                    int(temp_level)
773                except:
774                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
775                    logger.info(em)
776                    no_import.write(em)
777                    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)
778                    continue
779                level_changed = True
780                if 'dlev' in vars().keys():
781                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
782                level = temp_level
783                l = getattr(sc,level,None)
784                if l is None:
785                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
786                    sc.invokeFactory('StudentStudyLevel', level)
787                    l = getattr(sc, level)
788                    l.manage_setLocalRoles(student_id, ['Owner',])
789            else:
790                level_changed = False
791            cr = getattr(l,course,None)
792            if cr is None:
793                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
794                l.invokeFactory('StudentCourseResult',course)
795            cr = getattr(l,course)
796            dcr = {}
797            from_course = ['title',
798                           'credits',
799                           'passmark',
800                           ]
801            for f in from_course:
802                dcr[f] = getattr(course_doc,f)
803            dlev = {}
804            dcr['ansbook'] = result.get('Ansbook')
805            dcr['semester'] = getInt(result.get('Semster'))
806            dcr['status'] = result.get('CosStuatus')
807            dcr['score'] = getInt(result.get('Score'))
808            dlev['session'] = result.get('Session')
809            dcr['carry_level'] = result.get('CarryLevel')
810            dcr['grade'] = result.get('Grade')
811            dcr['weight'] = result.get('Weight')
812            dlev['verdict'] = result.get('Verdict')
813            dcr['import_id'] = result.get('id')
814            gpa = result.get('GPA').replace(',','.')
815            dlev['imported_gpa'] = getFloat(gpa)
816            cr.getContent().edit(mapping = dcr)
817            cr.manage_setLocalRoles(student_id, ['Owner',])
818            l.getContent().edit(mapping = dlev)
819            if tr_count > MAX_TRANS:
820                transaction.commit()
821                tr_count = 0
822            tr_count += 1
823            wftool.doActionFor(cr,'close')
824        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
825        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
826
827###)
828
829    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
830    def loadJAMBFromCSV(self):
831        """load JAMB data from CSV values"""
832        #return
833        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
834        import transaction
835        tr_count = 0
836        name = 'SampleJAMBDataII'
837        wftool = self.portal_workflow
838        no_import = False
839        if not no_import:
840            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
841            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')
842        logger = logging.getLogger('%s_import' % name)
843        logger.info('Start loading from %s.csv' % name)
844        try:
845            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
846        except:
847            logger.error('Error reading %s.csv' % name)
848            return
849        for jamb in result:
850            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)
851            jamb_reg_no = jamb.get('REG-NO')
852            res = self.portal_catalog({'meta_type': "StudentApplication",
853                                     'jamb_reg_no': jamb_reg_no })
854            if res:
855                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
856                logger.info(em)
857                no_import.write(em)
858                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)
859                continue
860            jamb_name = jamb.get("NAME")
861            jamb_name.replace('>','')
862            names = jamb_name.split()
863            letter = names[-1][0].upper()
864            sid = self.generateStudentId(letter)
865            not_created = True
866            while not_created:
867                try:
868                    students_folder.invokeFactory('Student', sid)
869                    not_created = False
870                except BadRequest:
871                    sid = self.generateStudentId(letter)
872            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
873            student = getattr(self,sid)
874            student.manage_setLocalRoles(sid, ['Owner',])
875            student.invokeFactory('StudentApplication','application')
876            da = {'Title': 'Application Data'}
877            da["jamb_reg_no"] = jamb.get("REG-NO")
878            da["jamb_lastname"] = jamb_name
879            da["jamb_sex"] = jamb.get("SEX")
880            da["jamb_state"] = jamb.get("STATE")
881            da["jamb_lga"] = jamb.get("LGA")
882            da["jamb_score"] = jamb.get("AGGREGATE")
883            da["jamb_first_cos"] = jamb.get("COURSE1")
884            da["jamb_second_cos"] = jamb.get("COURSE2")
885            da["jamb_first_uni"] = jamb.get("UNIV1")
886            da["jamb_second_uni"] = jamb.get("UNIV2")
887            app = student.application
888            app_doc = app.getContent()
889            app_doc.edit(mapping=da)
890            #wftool.doActionFor(app,'open',dest_container=app)
891            app.manage_setLocalRoles(sid, ['Owner',])
892            student.getContent().createSubObjects()
893        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
894    ###)
895
896
897    security.declareProtected(View,"fixOwnership")
898    def fixOwnership(self):
899        """fix Ownership"""
900        for s in self.portal_catalog(meta_type = 'Student'):
901            student = s.getObject()
902            sid = s.getId
903            import pdb;pdb.set_trace()
904            student.application.manage_setLocalRoles(sid, ['Owner',])
905            student.personal.manage_setLocalRoles(sid, ['Owner',])
906
907    security.declareProtected(View,"Title")
908    def Title(self):
909        """compose title"""
910        return "Student Section"
911
912    def generateStudentId(self,letter): ###(
913        import random
914        r = random
915        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
916            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
917        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
918        sid = "%c%d" % (letter,r.randint(99999,1000000))
919        while hasattr(students, sid):
920            sid = "%c%d" % (letter,r.randint(99999,1000000))
921        return sid
922        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
923    ###)
924
925InitializeClass(StudentsFolder)
926
927def addStudentsFolder(container, id, REQUEST=None, **kw):
928    """Add a Student."""
929    ob = StudentsFolder(id, **kw)
930    return CPSBase_adder(container, ob, REQUEST=REQUEST)
931###)
932
933class Student(CPSDocument): ###(
934    """
935    WAeUP Student container for the various student data
936    """
937    meta_type = 'Student'
938    portal_type = meta_type
939    security = ClassSecurityInfo()
940
941    security.declareProtected(View,"Title")
942    def Title(self):
943        """compose title"""
944        reg_nr = self.getId()[1:]
945        data = getattr(self,'personal',None)
946        if data:
947            content = data.getContent()
948            return "%s %s" % (content.firstname,content.lastname)
949        data = getattr(self,'application',None)
950        if data:
951            content = data.getContent()
952            return "%s" % (content.jamb_lastname)
953        return self.title
954
955    security.declarePrivate('makeStudentMember') ###(
956    def makeStudentMember(self,sid,password='uNsEt'):
957        """make the student a member"""
958        membership = self.portal_membership
959        membership.addMember(sid,
960                             password ,
961                             roles=('Member',
962                                     'Student',
963                                     ),
964                             domains='',
965                             properties = {'memberareaCreationFlag': False,
966                                           'homeless': True},)
967        member = membership.getMemberById(sid)
968        self.portal_registration.afterAdd(member, sid, password, None)
969        self.manage_setLocalRoles(sid, ['Owner',])
970
971###)
972
973    security.declareProtected(View,'createSubObjects') ###(
974    def createSubObjects(self):
975        """make the student a member"""
976        dp = {'Title': 'Personal Data'}
977        app_doc = self.application.getContent()
978        names = app_doc.jamb_lastname.split()
979        if len(names) == 3:
980            dp['firstname'] = names[0].capitalize()
981            dp['middlename'] = names[1].capitalize()
982            dp['lastname'] = names[2].capitalize()
983        elif len(names) == 2:
984            dp['firstname'] = names[0].capitalize()
985            dp['lastname'] = names[1].capitalize()
986        else:
987            dp['lastname'] = app_doc.jamb_lastname
988        dp['sex'] = app_doc.jamb_sex == 'F'
989        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
990        proxy = self.aq_parent
991        proxy.invokeFactory('StudentPersonal','personal')
992        per = proxy.personal
993        per_doc = per.getContent()
994        per_doc.edit(mapping = dp)
995        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
996        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
997
998###)
999
1000InitializeClass(Student)
1001
1002def addStudent(container, id, REQUEST=None, **kw):
1003    """Add a Student."""
1004    ob = Student(id, **kw)
1005    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1006
1007###)
1008
1009class StudentAccommodation(CPSDocument): ###(
1010    """
1011    WAeUP Student container for the various student data
1012    """
1013    meta_type = 'StudentAccommodation'
1014    portal_type = meta_type
1015    security = ClassSecurityInfo()
1016
1017    security.declareProtected(View,"Title")
1018    def Title(self):
1019        """compose title"""
1020        content = self.getContent()
1021        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
1022        return "Accommodation Data for Session %s" % content.session
1023
1024
1025InitializeClass(StudentAccommodation)
1026
1027def addStudentAccommodation(container, id, REQUEST=None, **kw):
1028    """Add a Students personal data."""
1029    ob = StudentAccommodation(id, **kw)
1030    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1031
1032###)
1033
1034class StudentPersonal(CPSDocument): ###(
1035    """
1036    WAeUP Student container for the various student data
1037    """
1038    meta_type = 'StudentPersonal'
1039    portal_type = meta_type
1040    security = ClassSecurityInfo()
1041
1042    security.declareProtected(View,"Title")
1043    def Title(self):
1044        """compose title"""
1045        content = self.getContent()
1046        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
1047        return "Personal Data"
1048
1049
1050InitializeClass(StudentPersonal)
1051
1052def addStudentPersonal(container, id, REQUEST=None, **kw):
1053    """Add a Students personal data."""
1054    ob = StudentPersonal(id, **kw)
1055    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1056
1057###)
1058
1059class StudentClearance(CPSDocument): ###(
1060    """
1061    WAeUP Student container for the various student data
1062    """
1063    meta_type = 'StudentClearance'
1064    portal_type = meta_type
1065    security = ClassSecurityInfo()
1066
1067    security.declareProtected(View,"Title")
1068    def Title(self):
1069        """compose title"""
1070        content = self.getContent()
1071        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
1072        return "Clearance/Eligibility Record"
1073
1074
1075InitializeClass(StudentClearance)
1076
1077def addStudentClearance(container, id, REQUEST=None, **kw):
1078    """Add a Students personal data."""
1079    ob = StudentClearance(id, **kw)
1080    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1081
1082###)
1083
1084class StudentStudyLevel(CPSDocument): ###(
1085    """
1086    WAeUP Student container for the various student data
1087    """
1088    meta_type = 'StudentStudyLevel'
1089    portal_type = meta_type
1090    security = ClassSecurityInfo()
1091
1092    security.declareProtected(View,"Title")
1093    def Title(self):
1094        """compose title"""
1095        return "Level %s" % self.aq_parent.getId()
1096
1097##    security.declarePublic("gpa")
1098##    def gpa(self):
1099##        """calculate the gpa"""
1100##        sum = 0
1101##        course_count = 0
1102##        for sc in self.objectValues():
1103##            result = sc.getContent()
1104##            if not result.grade:
1105##                continue
1106##            res = self.portal_catalog({'meta_type': 'Course',
1107##                                          'id': sc.aq_parent.id})
1108##            if len(res) != 1:
1109##                continue
1110##            course = res[0].getObject().getContent()
1111##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
1112##            course_count += 1
1113##        if course_count:
1114##            return sum/course_count
1115##        return 0.0
1116
1117InitializeClass(StudentStudyLevel)
1118
1119def addStudentStudyLevel(container, id, REQUEST=None, **kw):
1120    """Add a Students personal data."""
1121    ob = StudentStudyLevel(id, **kw)
1122    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1123
1124###)
1125
1126class StudentStudyCourse(CPSDocument): ###(
1127    """
1128    WAeUP Student container for the various student data
1129    """
1130    meta_type = 'StudentStudyCourse'
1131    portal_type = meta_type
1132    security = ClassSecurityInfo()
1133
1134    security.declareProtected(View,"Title")
1135    def Title(self):
1136        """compose title"""
1137        content = self.getContent()
1138        return "Study Course"
1139
1140
1141InitializeClass(StudentStudyCourse)
1142
1143def addStudentStudyCourse(container, id, REQUEST=None, **kw):
1144    """Add a Students personal data."""
1145    ob = StudentStudyCourse(id, **kw)
1146    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1147
1148###)
1149
1150class StudentApplication(CPSDocument): ###(
1151    """
1152    WAeUP Student container for the various student data
1153    """
1154    meta_type = 'StudentApplication'
1155    portal_type = meta_type
1156    security = ClassSecurityInfo()
1157
1158    security.declareProtected(View,"Title")
1159    def Title(self):
1160        """compose title"""
1161        return "Application Data"
1162
1163
1164InitializeClass(StudentApplication)
1165
1166def addStudentApplication(container, id, REQUEST=None, **kw):
1167    """Add a Students eligibility data."""
1168    ob = StudentApplication(id, **kw)
1169    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1170###)
1171
1172
1173class StudentPume(CPSDocument): ###(
1174    """
1175    WAeUP Student container for the various student data
1176    """
1177    meta_type = 'StudentPume'
1178    portal_type = meta_type
1179    security = ClassSecurityInfo()
1180
1181    security.declareProtected(View,"Title")
1182    def Title(self):
1183        """compose title"""
1184        return "PUME Results"
1185
1186
1187InitializeClass(StudentPume)
1188
1189def addStudentPume(container, id, REQUEST=None, **kw):
1190    """Add a Students PUME data."""
1191    ob = StudentPume(id, **kw)
1192    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1193###)
1194
1195##class StudentSemester(CPSDocument): ###(
1196##    """
1197##    WAeUP StudentSemester containing the courses and students
1198##    """
1199##    meta_type = 'StudentSemester'
1200##    portal_type = meta_type
1201##    security = ClassSecurityInfo()
1202##
1203##InitializeClass(StudentSemester)
1204##
1205##def addStudentSemester(container, id, REQUEST=None, **kw):
1206##    """Add a StudentSemester."""
1207##    ob = StudentSemester(id, **kw)
1208##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1209##
1210#####)
1211
1212##class Semester(CPSDocument): ###(
1213##    """
1214##    WAeUP Semester containing the courses and students
1215##    """
1216##    meta_type = 'Semester'
1217##    portal_type = meta_type
1218##    security = ClassSecurityInfo()
1219##
1220##InitializeClass(Semester)
1221##
1222##def addSemester(container, id, REQUEST=None, **kw):
1223##    """Add a Semester."""
1224##    ob = Semester(id, **kw)
1225##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1226##
1227#####)
1228
1229class StudentCourseResult(CPSDocument): ###(
1230    """
1231    WAeUP StudentCourseResult
1232    """
1233    meta_type = 'StudentCourseResult'
1234    portal_type = meta_type
1235    security = ClassSecurityInfo()
1236
1237    def getCourseEntry(self,cid):
1238        res = self.portal_catalog({'meta_type': "Course",
1239                                           'id': cid})
1240        if res:
1241            return res[-1]
1242        else:
1243            return None
1244
1245    security.declareProtected(View,"Title")
1246    def Title(self):
1247        """compose title"""
1248        cid = self.aq_parent.getId()
1249        ce = self.getCourseEntry(cid)
1250        if ce:
1251            return "%s" % ce.Title
1252        return "No course with id %s" % cid
1253
1254InitializeClass(StudentCourseResult)
1255
1256def addStudentCourseResult(container, id, REQUEST=None, **kw):
1257    """Add a StudentCourseResult."""
1258    ob = StudentCourseResult(id, **kw)
1259    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1260###)
1261
1262# Backward Compatibility StudyLevel
1263
1264from Products.WAeUP_SRP.Academics import StudyLevel
1265
1266from Products.WAeUP_SRP.Academics import addStudyLevel
1267
Note: See TracBrowser for help on using the repository browser.