source: WAeUP_SRP/trunk/Students.py @ 511

Last change on this file since 511 was 511, checked in by joachim, 18 years ago

pin checking and login for JAMB students

  • Property svn:keywords set to Id
File size: 28.6 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 511 2006-09-13 06:47:55Z joachim $
3from Globals import InitializeClass
4from AccessControl import ClassSecurityInfo
5from AccessControl.SecurityManagement import newSecurityManager
6from zExceptions import BadRequest
7from Products.ZCatalog.ZCatalog import ZCatalog
8from Products.CMFCore.utils import UniqueObject, getToolByName
9from Products.CMFCore.permissions import View
10from Products.CMFCore.permissions import ModifyPortalContent
11from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
12#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
13from Products.CPSDocument.CPSDocument import CPSDocument
14from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
15from Products.CPSCore.CPSMembershipTool import CPSUnrestrictedUser
16from Products.WAeUP_SRP.Academics import makeCertificateCode
17import logging
18import csv,re
19import Globals
20p_home = Globals.package_home(globals())
21i_home = Globals.INSTANCE_HOME
22MAX_TRANS = 1000
23
24def generateStudentId(letter):
25    import random
26    r = random
27    if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
28        letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
29    return "%c%d" % (letter,r.randint(99999,1000000))
30    #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
31
32def getStudentByRegNo(self,reg_no):
33    """search student by JAMB Reg No and return StudentFolder"""
34    search = ZCatalog.searchResults(self.portal_catalog,{'meta_type': 'StudentApplication',
35                                  'jamb_reg_no': reg_no,
36                                  })
37    if len(search) < 1:
38        return None
39    return search[0].getObject().aq_parent
40
41class StudentsFolder(CPSDocument): ###(
42    """
43    WAeUP container for the various WAeUP containers data
44    """
45    meta_type = 'StudentsFolder'
46    portal_type = meta_type
47    security = ClassSecurityInfo()
48
49    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsFromCSV")###(
50    def loadFullTimeStudentsFromCSV(self):
51        """load Fulltime Studentdata from CSV values"""
52        #return
53        import transaction
54        tr_count = 0
55        name = 'short_full_time'
56        no_import = False
57        if not no_import:
58            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
59            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')
60        logger = logging.getLogger('%s_import' % name)
61        logger.info('Start loading from %s.csv' % name)
62        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
63        try:
64            students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
65        except:
66            logger.error('Error reading %s.csv' % name)
67            return
68        l = self.portal_catalog({'meta_type': "StudentClearance",})
69        matrics = []
70        for s in l:
71            matrics.append(s.getObject().getContent().matric_no)
72        print matrics
73        l = self.portal_catalog({'meta_type': "Certificate"})
74        certs = {}
75        for c in l:
76            certs[c.id] = c.getObject()
77        for student in students:
78            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)
79            sid = student.get('MatricNo')
80            if sid == "":
81                em = 'Empty MatricNo\n'
82                logger.info(em)
83                no_import.write(em)
84                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)
85                continue
86            certcode = makeCertificateCode(student.get('CourseMajor'))
87            if certcode not in certs.keys():
88                em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
89                logger.info(em)
90                no_import.write(em)
91                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)
92                continue
93            level = student.get('StudentLevel')
94            try:
95                int(level)
96            except:
97                em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
98                logger.info(em)
99                no_import.write(em)
100                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)
101                continue
102            matric_no = student.get('MatricNo')
103            if matric_no not in matrics:
104                matrics.append(matric_no)
105                sid = generateStudentId()
106                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
107                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
108                not_created = True
109                while not_created:
110                    try:
111                        students_folder.invokeFactory('Student', sid)
112                        not_created = False
113                    except BadRequest:
114                        sid = generateStudentId()
115                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
116                s = getattr(self,sid)
117                self.portal_registration.addMember(sid,
118                                                   'uNsEt' ,
119                                                   roles=('Member',
120                                                          'Student',))
121                s.invokeFactory('StudentApplication','application')
122                da = {'Title': 'Application Data'}
123                s.invokeFactory('StudentPersonal','personal')
124                da['jamb_reg_no'] = student.get('EntryRegNo')
125                sp = s.personal
126                d = {'Title': 'Personal Data'}
127                s.invokeFactory('StudentClearance','clearance')
128                sc = s.clearance
129                dc = {'Title': 'Clearance Data'}
130                dc['matric_no'] = matric_no
131                lga = student.get('State') + ' / ' + student.get('LGA')
132                dc['lga'] = lga
133                dc['nationality'] = student.get('Nationality')
134                dc['email'] = student.get('Emailaddress')
135                d['firstname'] = student.get('FirstName')
136                d['middlename'] = student.get('MiddleName')
137                d['lastname'] = student.get('Lastname')
138                d['former_surname'] = student.get('FormerSurname')
139                d['sex'] = student.get('Sex') == 'F'
140                d['perm_address'] = student.get('PermanentAddress')
141                d['perm_city'] = student.get('PermanentAddressCity')
142                d['campus_address'] = student.get('CampusAddress')
143                d['phone'] = student.get('PhoneNumber')
144                s.application.getContent().edit(mapping=da)
145                sp.getContent().edit(mapping=d)
146                sc.getContent().edit(mapping=dc)
147                #
148                # Study Course
149                #
150                s.invokeFactory('StudentStudyCourse','study_course')
151                sc = s.study_course
152                d = {}
153                #d['matricel_no'] = student.get('MatricNo')
154                #d['entry_reg_no'] = student.get('EntryRegNo')
155                #d['faculty'] = student.get('Faculty')
156                #d['department'] = student.get('Dept')
157                d['study_course'] = certcode
158                css = student.get('CurrentSession') or '2004-2005'
159                cs = int(css.split('-')[0]) - 2000
160                cl = int(student.get('StudentLevel'))/100
161                d['entry_session'] = "200%s" % (cs - cl)
162                sc.getContent().edit(mapping=d)
163                #
164                # Level
165                #
166                l = getattr(sc,level,None)
167                if l is None:
168                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
169                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
170                    sc.invokeFactory('StudentStudyLevel', level)
171                    l = getattr(sc, level)
172                    certificate = certs[certcode]
173                    cert_level = getattr(certificate,level,None)
174                    if cert_level is None:
175                        logger.info('Level %(level)s not in %(certcode)s' % vars())
176                    l.getContent().edit(mapping={'Title': "Level %s" % level})
177                    l.invokeFactory('StudentSemester','first')
178                    l.invokeFactory('StudentSemester','second')
179                    first_s = getattr(l,'first')
180                    first_s.getContent().edit(mapping={'Title': 'First Semester'})
181                    second_s = getattr(l,'second')
182                    second_s.getContent().edit(mapping={'Title': 'Second Semester'})
183            else:
184                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
185                logger.info(em)
186                no_import.write(em)
187                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)
188            if tr_count > MAX_TRANS:
189                transaction.commit()
190                em = 'Transaction commited\n' % student
191                logger.info(em)
192                tr_count = 0
193            tr_count += 1
194        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
195        return self.students.academics_contents()
196    ###)
197
198    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
199    def loadFullTimeStudentsResultsFromCSV(self):
200        """load Fulltime Studentdata from CSV values"""
201        #return
202        import transaction
203        tr_count = 0
204        name = 'short_full_time_results_2004_2005'
205        no_import = False
206        if not no_import:
207            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
208            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
209        logger = logging.getLogger('%s_import' % name)
210        logger.info('Start loading from %s.csv' % name)
211        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
212        try:
213            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
214        except:
215            logger.error('Error reading %s.csv' % name)
216            return
217        l = self.portal_catalog({'meta_type': "Course"})
218        courses = {}
219        for c in l:
220            courses[c.id] = c.getObject()
221        for result in results:
222            sid = result.get('Matnumber')
223            res = self.portal_catalog({'meta_type': "StudentClearance",
224                                     'matric_no': sid })
225            if not res:
226                em = 'Student with ID %(Matnumber)s not found\n' % result
227                logger.info(em)
228                no_import.write(em)
229                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)
230                continue
231            sf = res[0].getObject().aq_parent
232            result['StudentId'] = sf.getId()
233            course = result.get('CosCode')
234            if course not in courses.keys():
235                em = 'Course with ID %(CosCode)s not found\n' % result
236                logger.info(em)
237                no_import.write(em)
238                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)
239                continue
240            level = result.get('Level')
241            try:
242                int(level)
243            except:
244                em = 'Result for result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
245                logger.info(em)
246                no_import.write(em)
247                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)
248                continue
249            sc = getattr(sf,'study_course')
250            l = getattr(sc,level,None)
251            if l is None:
252                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
253                logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
254                sc.invokeFactory('StudentStudyLevel', level)
255                l = getattr(sc, level)
256                l.invokeFactory('StudentSemester','first')
257                l.invokeFactory('StudentSemester','second')
258                first_s = getattr(l,'first')
259                first_s.getContent().edit(mapping={'Title': 'First Semester'})
260                second_s = getattr(l,'second')
261                second_s.getContent().edit(mapping={'Title': 'Second Semester'})
262            snr = result.get('Semster')
263            semester = getattr(l,'first')
264            if snr == "2":
265                semester = getattr(l,'second')
266            logger.info('Creating StudentCourseResult %(CosCode)s in Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
267            semester.invokeFactory('StudentCourseResult',course)
268            ct = getattr(semester,course)
269            d = {}
270            dlev = {}
271            d['ansbook'] = result.get('Ansbook')
272            d['status'] = result.get('CosStuatus')
273            d['score'] = result.get('Score')
274            dlev['session'] = result.get('Session')
275            dlev['carry_level'] = result.get('CarryLevel')
276            d['grade'] = result.get('Grade')
277            #d['weight'] = result.get('Weight')
278            dlev['verdict'] = result.get('Verdict')
279            #d['import_id'] = result.get('id')
280            #gpa = result.get('GPA').replace(',','.')
281            #d['gpa'] = float(gpa)
282            ct.getContent().edit(mapping = d)
283            l.getContent().edit(mapping = dlev)
284            if tr_count > MAX_TRANS:
285                transaction.commit()
286                tr_count = 0
287            tr_count += 1
288        return self.students.academics_contents()
289
290###)
291
292    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
293    def loadJAMBFromCSV(self):
294        """load JAMB data from CSV values"""
295        #return
296        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
297        import transaction
298        tr_count = 0
299        name = 'SampleJAMBDataII_short'
300        wftool = self.portal_workflow
301        no_import = False
302        if not no_import:
303            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
304            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')
305        logger = logging.getLogger('%s_import' % name)
306        logger.info('Start loading from %s.csv' % name)
307        try:
308            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
309        except:
310            logger.error('Error reading %s.csv' % name)
311            return
312        for jamb in result:
313            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)
314            jamb_reg_no = jamb.get('REG-NO')
315            res = self.portal_catalog({'meta_type': "StudentApplication",
316                                     'jamb_reg_no': jamb_reg_no })
317            if res:
318                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
319                logger.info(em)
320                no_import.write(em)
321                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)
322                continue
323            jamb_name = jamb.get("NAME")
324            names = jamb_name.split()
325            letter = names[-1][0].upper()
326            sid = generateStudentId(letter)
327            #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
328            not_created = True
329            while not_created:
330                try:
331                    students_folder.invokeFactory('Student', sid)
332                    not_created = False
333                except BadRequest:
334                    sid = generateStudentId(letter)
335            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
336            student = getattr(self,sid)
337            student.invokeFactory('StudentApplication','application')
338            da = {'Title': 'Application Data'}
339            da["jamb_reg_no"] = jamb.get("REG-NO")
340            da["jamb_lastname"] = jamb_name
341            da["jamb_sex"] = jamb.get("SEX")
342            da["jamb_state"] = jamb.get("STATE")
343            da["jamb_lga"] = jamb.get("LGA")
344            da["jamb_score"] = jamb.get("AGGREGATE")
345            da["jamb_first_cos"] = jamb.get("COURSE1")
346            da["jamb_second_cos"] = jamb.get("COURSE2")
347            da["jamb_first_uni"] = jamb.get("UNIV1")
348            da["jamb_second_uni"] = jamb.get("UNIV2")
349            app = student.application
350            app_doc = app.getContent()
351            app_doc.edit(mapping=da)
352            wftool.doActionFor(app,'open',dest_container=app)
353            app.manage_setLocalRoles(sid, ['Owner',])
354            student.getContent().createSubObjects()
355        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
356    ###)
357
358
359    security.declareProtected(View,"fixOwnership")
360    def fixOwnership(self):
361        """fix Ownership"""
362        for s in self.portal_catalog(meta_type = 'Student'):
363            student = s.getObject()
364            sid = s.getId
365            import pdb;pdb.set_trace()
366            student.application.manage_setLocalRoles(sid, ['Owner',])
367            student.personal.manage_setLocalRoles(sid, ['Owner',])
368           
369    security.declareProtected(View,"Title")
370    def Title(self):
371        """compose title"""
372        return "Student Section"
373
374InitializeClass(StudentsFolder)
375
376def addStudentsFolder(container, id, REQUEST=None, **kw):
377    """Add a Student."""
378    ob = StudentsFolder(id, **kw)
379    return CPSBase_adder(container, ob, REQUEST=REQUEST)
380###)
381
382class Student(CPSDocument): ###(
383    """
384    WAeUP Student container for the various student data
385    """
386    meta_type = 'Student'
387    portal_type = meta_type
388    security = ClassSecurityInfo()
389
390    security.declareProtected(View,"Title")
391    def Title(self):
392        """compose title"""
393        reg_nr = self.getId()[1:]
394        data = getattr(self,'personal',None)
395        if data:
396            content = data.getContent()
397            return "%s %s" % (content.firstname,content.lastname)
398        data = getattr(self,'application',None)
399        if data:
400            content = data.getContent()
401            return "%s" % (content.jamb_lastname)
402        return self.title
403
404    security.declarePrivate('makeStudentMember') ###(
405    def makeStudentMember(self,sid,password='uNsEt'):
406        """make the student a member"""
407        membership = self.portal_membership
408        membership.addMember(sid,
409                             password ,
410                             roles=('Member',
411                                     'Student',
412                                     'Owner'),
413                             domains='',
414                             properties = None,)
415        member = membership.getMemberById(sid)
416        self.portal_registration.afterAdd(member, sid, password, None)
417        self.manage_setLocalRoles(sid, ['Owner',])
418
419###)
420
421    security.declareProtected(View,'createSubObjects') ###(
422    def createSubObjects(self):
423        """make the student a member"""
424        dp = {'Title': 'Personal Data'}
425        names = self.application.getContent().jamb_lastname.split()
426        if len(names) == 3:
427            dp['firstname'] = names[0].capitalize()
428            dp['middlename'] = names[1].capitalize()
429            dp['lastname'] = names[2].capitalize()
430        elif len(names) == 2:
431            dp['firstname'] = names[0].capitalize()
432            dp['lastname'] = names[1].capitalize()
433        else:
434            dp['lastname'] = app_doc.jamb_lastname
435            dp['sex'] = app_doc.jamb_sex == 'F'
436            dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
437        proxy = self.aq_parent
438        proxy.invokeFactory('StudentPersonal','personal')
439        per = proxy.personal
440        per_doc = per.getContent()
441        per.manage_setLocalRoles(self.getId(), ['Owner',])
442        self.portal_workflow.doActionFor(per,'open',dest_container=per)
443        per_doc.edit(mapping = dp)
444       
445###)
446
447InitializeClass(Student)
448
449def addStudent(container, id, REQUEST=None, **kw):
450    """Add a Student."""
451    ob = Student(id, **kw)
452    return CPSBase_adder(container, ob, REQUEST=REQUEST)
453
454###)
455
456class StudentPersonal(CPSDocument): ###(
457    """
458    WAeUP Student container for the various student data
459    """
460    meta_type = 'StudentPersonal'
461    portal_type = meta_type
462    security = ClassSecurityInfo()
463
464    security.declareProtected(View,"Title")
465    def Title(self):
466        """compose title"""
467        content = self.getContent()
468        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
469        return "Personal Data"
470
471
472InitializeClass(StudentPersonal)
473
474def addStudentPersonal(container, id, REQUEST=None, **kw):
475    """Add a Students personal data."""
476    ob = StudentPersonal(id, **kw)
477    return CPSBase_adder(container, ob, REQUEST=REQUEST)
478
479###)
480
481class StudentClearance(CPSDocument): ###(
482    """
483    WAeUP Student container for the various student data
484    """
485    meta_type = 'StudentClearance'
486    portal_type = meta_type
487    security = ClassSecurityInfo()
488
489    security.declareProtected(View,"Title")
490    def Title(self):
491        """compose title"""
492        content = self.getContent()
493        #return "Clearance Data for %s %s" % (content.firstname,content.lastname)
494        return "Clearance Data"
495
496
497InitializeClass(StudentClearance)
498
499def addStudentClearance(container, id, REQUEST=None, **kw):
500    """Add a Students personal data."""
501    ob = StudentClearance(id, **kw)
502    return CPSBase_adder(container, ob, REQUEST=REQUEST)
503
504###)
505
506class StudyLevel(CPSDocument): ###(
507    """
508    WAeUP StudyLevel containing the courses and students
509    """
510    meta_type = 'StudyLevel'
511    portal_type = meta_type
512    security = ClassSecurityInfo()
513
514    security.declareProtected(View,"Title")
515    def Title(self):
516        """compose title"""
517        return "Level %s" % self.aq_parent.getId()
518
519
520InitializeClass(StudyLevel)
521
522def addStudyLevel(container, id, REQUEST=None, **kw):
523    """Add a StudyLevel."""
524    ob = StudyLevel(id, **kw)
525    return CPSBase_adder(container, ob, REQUEST=REQUEST)
526
527###)
528
529class StudentStudyLevel(CPSDocument): ###(
530    """
531    WAeUP Student container for the various student data
532    """
533    meta_type = 'StudentStudyLevel'
534    portal_type = meta_type
535    security = ClassSecurityInfo()
536
537    security.declareProtected(View,"Title")
538    def Title(self):
539        """compose title"""
540        return "Level %s" % self.aq_parent.getId()
541
542    security.declareProtected(View,"gpa")
543    def gpa(self):
544        """calculate the gpa"""
545        sum = 0
546        course_count = 0
547        for semester in ('first','second'):
548            sf=getattr(self,semester)
549            for sc in sf.objectValues():
550                result = sc.getContent()
551                res = self.portal_catalog({'meta_type': 'Course',
552                                              'id': sc.aq_parent.id})
553                if len(res) != 1:
554                    continue
555                course = res[0].getObject().getContent()
556                sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
557                course_count += 1
558        if course_count:
559            return sum/course_count
560        return 0.0
561
562InitializeClass(StudentStudyLevel)
563
564def addStudentStudyLevel(container, id, REQUEST=None, **kw):
565    """Add a Students personal data."""
566    ob = StudentStudyLevel(id, **kw)
567    return CPSBase_adder(container, ob, REQUEST=REQUEST)
568
569###)
570
571class StudentStudyCourse(CPSDocument): ###(
572    """
573    WAeUP Student container for the various student data
574    """
575    meta_type = 'StudentStudyCourse'
576    portal_type = meta_type
577    security = ClassSecurityInfo()
578
579    security.declareProtected(View,"Title")
580    def Title(self):
581        """compose title"""
582        content = self.getContent()
583        return "Study Course"
584
585
586InitializeClass(StudentStudyCourse)
587
588def addStudentStudyCourse(container, id, REQUEST=None, **kw):
589    """Add a Students personal data."""
590    ob = StudentStudyCourse(id, **kw)
591    return CPSBase_adder(container, ob, REQUEST=REQUEST)
592
593###)
594
595class StudentApplication(CPSDocument): ###(
596    """
597    WAeUP Student container for the various student data
598    """
599    meta_type = 'StudentApplication'
600    portal_type = meta_type
601    security = ClassSecurityInfo()
602
603    security.declareProtected(View,"Title")
604    def Title(self):
605        """compose title"""
606        return "Application Data"
607
608
609InitializeClass(StudentApplication)
610
611def addStudentApplication(container, id, REQUEST=None, **kw):
612    """Add a Students eligibility data."""
613    ob = StudentApplication(id, **kw)
614    return CPSBase_adder(container, ob, REQUEST=REQUEST)
615
616###)
617
618class StudentSemester(CPSDocument): ###(
619    """
620    WAeUP StudentSemester containing the courses and students
621    """
622    meta_type = 'StudentSemester'
623    portal_type = meta_type
624    security = ClassSecurityInfo()
625
626InitializeClass(StudentSemester)
627
628def addStudentSemester(container, id, REQUEST=None, **kw):
629    """Add a StudentSemester."""
630    ob = StudentSemester(id, **kw)
631    return CPSBase_adder(container, ob, REQUEST=REQUEST)
632
633###)
634
635class Semester(CPSDocument): ###(
636    """
637    WAeUP Semester containing the courses and students
638    """
639    meta_type = 'Semester'
640    portal_type = meta_type
641    security = ClassSecurityInfo()
642
643InitializeClass(Semester)
644
645def addSemester(container, id, REQUEST=None, **kw):
646    """Add a Semester."""
647    ob = Semester(id, **kw)
648    return CPSBase_adder(container, ob, REQUEST=REQUEST)
649
650###)
651
652class StudentCourseResult(CPSDocument): ###(
653    """
654    WAeUP StudentCourseResult
655    """
656    meta_type = 'StudentCourseResult'
657    portal_type = meta_type
658    security = ClassSecurityInfo()
659
660    def getCourseEntry(self,cid):
661        res = self.portal_catalog({'meta_type': "StudentCourse",
662                                           'id': cid})
663        if res:
664            return res[-1]
665        else:
666            return None
667
668    security.declareProtected(View,"Title")
669    def Title(self):
670        """compose title"""
671        cid = self.getId()
672        ce = self.getCourseEntry(cid)
673        if ce:
674            return "%s" % ce.Title
675        return "No course with id %s" % cid
676
677InitializeClass(StudentCourseResult)
678
679def addStudentCourseResult(container, id, REQUEST=None, **kw):
680    """Add a StudentCourseResult."""
681    ob = StudentCourseResult(id, **kw)
682    return CPSBase_adder(container, ob, REQUEST=REQUEST)
683###)
684
Note: See TracBrowser for help on using the repository browser.