source: WAeUP_SRP/trunk/Students.py @ 709

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

should fix error traceback when accessing pins on server.

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