source: WAeUP_SRP/trunk/Students.py @ 724

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

Import and Manager view for full-time students + results

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