source: WAeUP_SRP/trunk/Students.py @ 733

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

improved student import,
renamed layout/schema student_course_results to student_course_result

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