source: WAeUP_SRP/trunk/Students.py @ 722

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

implemented new reserved room procedure as described in ticket #50
also made a WAeUPReservedRoomsWidget, to check the validity of the reserved
rooms form entry.

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