source: WAeUP_SRP/trunk/Students.py @ 726

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

study-level import improvements

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