source: WAeUP_SRP/trunk/Students.py @ 929

Last change on this file since 929 was 927, checked in by joachim, 18 years ago

localrole owner was set with the id of the real_object instead of the id of
the proxy.

  • Property svn:keywords set to Id
File size: 40.2 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 927 2006-11-23 13:16:26Z 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)
[746]127                student_obj.getContent().makeStudentMember(sid,access_code,)
[708]128                pwl_dict = {'student_id': sid,'access_code':access_code}
[714]129                student_obj.invokeFactory('StudentApplication','application')
130                application = student_obj.application
[472]131                da = {'Title': 'Application Data'}
[714]132                student_obj.invokeFactory('StudentPersonal','personal')
[446]133                da['jamb_reg_no'] = student.get('EntryRegNo')
[714]134                personal = student_obj.personal
[708]135                dp = {'Title': 'Personal Data'}
[714]136                student_obj.invokeFactory('StudentClearance','clearance')
137                clearance = student_obj.clearance
[840]138                dc = {'Title': 'Clearance/Eligibility Record'}
[422]139                dc['matric_no'] = matric_no
[714]140                state = student.get('State')
141                lga = student.get('LGA')
142                if state and lga:
143                    lga =  state + ' / ' + lga
144                else:
145                    lga = "None"
[427]146                dc['lga'] = lga
[422]147                dc['nationality'] = student.get('Nationality')
148                dc['email'] = student.get('Emailaddress')
[708]149                dp['firstname'] = student.get('FirstName')
150                dp['middlename'] = student.get('MiddleName')
151                dp['lastname'] = student.get('Lastname')
152                dp['former_surname'] = student.get('FormerSurname')
153                dp['sex'] = student.get('Sex') == 'F'
154                dp['perm_address'] = student.get('PermanentAddress')
155                dp['perm_city'] = student.get('PermanentAddressCity')
156                dp['campus_address'] = student.get('CampusAddress')
157                dp['phone'] = student.get('PhoneNumber')
[714]158                application.getContent().edit(mapping=da)
159                personal.getContent().edit(mapping=dp)
160                clearance.getContent().edit(mapping=dc)
[362]161                #
162                # Study Course
163                #
[714]164                student_obj.invokeFactory('StudentStudyCourse','study_course')
165                studycourse = student_obj.study_course
[708]166                dsc = {}
[727]167                from_certificate = ['title',
168                                   'max_elect',
169                                   'max_pass',
170                                   'n_core',
171                                   'nr_years',
172                                   'probation_credits',
173                                   'promotion_credits',
174                                   'start_level',
175                                  ]
176                for f in from_certificate:
177                    dsc[f] = getattr(certificate_doc,f)
178                dsc['faculty'] = fac_id
179                dsc['department'] = dep_id
[708]180                dsc['study_course'] = certcode
[454]181                css = student.get('CurrentSession') or '2004-2005'
182                cs = int(css.split('-')[0]) - 2000
[714]183                cl = int(student.get('StudentLevel') or '100')/100
[708]184                dsc['entry_session'] = "200%s" % (cs - cl)
185                dsc['clr_ac_pin'] = access_code
[714]186                studycourse.getContent().edit(mapping=dsc)
[364]187                #
188                # Level
189                #
[723]190##                l = getattr(studycourse,level,None)
191##                if 0 and l is None:
192##                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
193##                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
194##                    studycourse.invokeFactory('StudentStudyLevel', level)
195##                    l = getattr(studycourse, level)
196##                    certificate = certs[certcode]
197##                    cert_level = getattr(certificate,level,None)
198##                    if cert_level is None:
199##                        logger.info('Level %(level)s not in %(certcode)s' % vars())
200##                    l.getContent().edit(mapping={'Title': "Level %s" % level})
[361]201            else:
[393]202                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
[361]203                logger.info(em)
[393]204                no_import.write(em)
205                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]206                continue
[398]207            if tr_count > MAX_TRANS:
[422]208                transaction.commit()
209                em = 'Transaction commited\n' % student
[398]210                logger.info(em)
211                tr_count = 0
212            tr_count += 1
[708]213            pwl_dict.update(dc)
214            pwl_dict.update(da)
215            pwl_dict.update(dp)
[714]216            wftool = self.portal_workflow
[708]217            pwlist.append(pwl_template.substitute(pwl_dict))
[714]218            wftool.doActionFor(student_obj,'clear_and_validate')
[742]219            student_obj.manage_setLocalRoles(sid, ['Owner',])
[714]220            wftool.doActionFor(application,'close')
[742]221            application.manage_setLocalRoles(sid, ['Owner',])
[714]222            wftool.doActionFor(clearance,'close')
[742]223            clearance.manage_setLocalRoles(sid, ['Owner',])
[714]224            wftool.doActionFor(personal,'close')
[742]225            personal.manage_setLocalRoles(sid, ['Owner',])
[727]226            wftool.doActionFor(studycourse,'close_for_edit')
[742]227            studycourse.manage_setLocalRoles(sid, ['Owner',])
[714]228        open("%s/import/pwlist-%s.csv" % (i_home,name),"w+").write('\n'.join(pwlist))
[423]229        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[361]230    ###)
[382]231
[742]232    security.declareProtected(ModifyPortalContent,"loadPumeResultsFromCSV")###(
233    def loadPumeResultsFromCSV(self):
234        """load Fulltime Studentdata from CSV values"""
235        import transaction
236        import random
[763]237        wftool = self.portal_workflow
[757]238        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
239        csv_d = {'jamb_reg_no': "Matnumber",
240                 'jamb_lastname': "Surname",
241                 'pume_options': "Options",
242                 'session': "Session",
243                 'days': "Days",
244                 'response': "Responce",
245                 'wrong': "Wrong",
246                 'pume_eng_score': "EngScore",
[775]247                 'pume_gen_score': "GenScore",
[764]248                 'pume_tot_score': "Right",
[757]249                 'batch': "Batch",
250                 'serial': "SerialNo",
251                 'jamb_score': "JambScore",
252                 'omitted':"Omitted",
253                 'search_key': "SearchKey",
254                 'jamb_sex': "Sex",
255                 'fac1': "Fac1",
256                 'fac2': "Fac2",
257                 'jamb_first_cos': "CourseofStudy",
258                 'stud_status':"StudStatus",
259                 'registered': "Registered",
260                 'jamb_state': "State",
261                 'eng_fail': "EngFail",
262                 'gen_fail': "GenFail",
263                 'un_ans_eng': "UnAnsEng",
264                 'un_ans_eng': "UnAnsGen",
265                 'total_ans': "TotalUnAns",
266                 'dept': "Dept",
267                 'jamb_second_cos': "Course2",
268                 'jamb_third_cos': "course3",
269                 }
270        csv_fields = [f[1] for f in csv_d.items()]
[742]271        tr_count = 0
272        name = 'pume_results'
[757]273        no_import = []
274        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
275        no_import.append('%s\n' % s)
[742]276        logger = logging.getLogger('%s_import' % name)
277        logger.info('Start loading from %s.csv' % name)
278        try:
[757]279            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[742]280        except:
281            logger.error('Error reading %s.csv' % name)
282            return
[757]283        for jamb in result:
284            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
285            processing = "processing %s" % format
286            logger.info(processing % jamb)
287            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
[763]288            #import pdb;pdb.set_trace()
289            res = self.portal_catalog({'portal_type': "StudentApplication",
[757]290                                     'jamb_reg_no': jamb_reg_no })
291            if res:
292                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
[742]293                logger.info(em)
[757]294                no_import.append(em)
295                no_import.append(format % jamb)
[742]296                continue
[785]297            cert_id = jamb.get(csv_d['jamb_first_cos']).upper()
298            res = self.portal_catalog({'portal_type': "Certificate",
299                                     'id': cert_id })
300            if len(res) < 1:
301                em = 'No Certificate with ID %s \n' % cert_id
302                logger.info(em)
303                no_import.append(em)
304                no_import.append(format % jamb)
305                continue
306            cert = res[0].getObject()
307            cert_path = res[0].getPath()
308            cert_doc = cert.getContent()
[757]309            jamb_name = jamb.get(csv_d['jamb_lastname'])
310            jamb_name.replace('>','')
311            names = jamb_name.split()
312            letter = names[-1][0].upper()
313            sid = self.generateStudentId(letter)
314            not_created = True
315            while not_created:
316                try:
317                    students_folder.invokeFactory('Student', sid)
318                    not_created = False
319                except BadRequest:
320                    sid = self.generateStudentId(letter)
321            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
322            student = getattr(self,sid)
323            student.manage_setLocalRoles(sid, ['Owner',])
[766]324            student.invokeFactory('StudentClearance','clearance')
[775]325            #wftool.doActionFor(student.clearance,'open')
[840]326            dp = {'Title': 'Clearance/Eligibility Record'}
[766]327            student.clearance.manage_setLocalRoles(sid, ['Owner',])
[763]328            student.invokeFactory('StudentPume','pume')
329            dp = {'Title': 'Pume Data'}
[757]330            student.invokeFactory('StudentApplication','application')
331            da = {'Title': 'Application Data'}
332            da["jamb_lastname"] = jamb_name
333            da_fields = ('jamb_reg_no',
334                         'jamb_sex',
335                         'jamb_state',
336                         'jamb_score',
337                         'jamb_first_cos',
338                         'jamb_sex',
339                         'jamb_state',
340                         'jamb_first_cos',
341                         'jamb_second_cos',
342                         )
[763]343            for f in da_fields:
344                da[f] = jamb.get(csv_d[f])
[757]345            app = student.application
[763]346            app.getContent().edit(mapping=da)
[757]347            app.manage_setLocalRoles(sid, ['Owner',])
[780]348            #wftool.doActionFor(app,'close')
[763]349            dp_fields = (
350                         'pume_eng_score',
[764]351                         'pume_gen_score',
[763]352                         'pume_tot_score',
353                         )
354            for f in dp_fields:
[775]355                dp[f] = float(jamb.get(csv_d[f]))
[765]356            pume = student.pume
357            pume.getContent().edit(mapping=dp)
[780]358            #wftool.doActionFor(pume,'close')
[763]359            pume.manage_setLocalRoles(sid, ['Owner',])
[785]360            #
361            # Study Course
362            #
363            student.invokeFactory('StudentStudyCourse','study_course')
364            study_course = student.study_course
365            dsc = {}
366            from_certificate = ['title',
367                               'max_elect',
368                               'max_pass',
369                               'n_core',
370                               'nr_years',
371                               'probation_credits',
372                               'promotion_credits',
373                               'start_level',
374                              ]
375            for f in from_certificate:
376                dsc[f] = getattr(cert_doc,f)
377            cpl = cert_path.split('/')
378            dsc['faculty'] = cpl[-4]
379            dsc['department'] = cpl[-3]
380            dsc['study_course'] = cert_id
381            dsc['entry_session'] = jamb.get(csv_d['session'])
382            study_course.getContent().edit(mapping=dsc)
[757]383            student.getContent().createSubObjects()
[775]384            if dp['pume_tot_score']>49:
[780]385                wftool.doActionFor(student,'pume_pass')
[785]386                wftool.doActionFor(student,'admit')
[775]387            else:
[780]388                wftool.doActionFor(student,'pume_fail')
[790]389                wftool.doActionFor(student,'reject_admission')
[757]390            if len(no_import) > 1:
391                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
392                     '\n'.join(no_import))
[742]393        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
394    ###)
395
[398]396    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
[396]397    def loadFullTimeStudentsResultsFromCSV(self):
398        """load Fulltime Studentdata from CSV values"""
399        #return
[723]400        level_wf_actions = {}
401        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
402        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
[727]403        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
404        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
[398]405        import transaction
[723]406        wftool = self.portal_workflow
[398]407        tr_count = 0
408        name = 'short_full_time_results_2004_2005'
[396]409        no_import = False
410        if not no_import:
411            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
412            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
413        logger = logging.getLogger('%s_import' % name)
414        logger.info('Start loading from %s.csv' % name)
415        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
416        try:
417            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
418        except:
419            logger.error('Error reading %s.csv' % name)
420            return
[398]421        l = self.portal_catalog({'meta_type': "Course"})
422        courses = {}
423        for c in l:
424            courses[c.id] = c.getObject()
[723]425        level_changed = False
426        student_changed = False
427        sid = ''
428        #import pdb;pdb.set_trace()
[396]429        for result in results:
[723]430            temp_sid = result.get('Matnumber')
431            if temp_sid != sid:
432                student_changed = True
433                res = self.portal_catalog({'meta_type': "StudentClearance",
434                                         'SearchableText': temp_sid })
435                if not res:
436                    em = 'Student with ID %(Matnumber)s not found\n' % result
437                    logger.info(em)
438                    no_import.write(em)
439                    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)
440                    continue
441                elif len(res) > 1:
442                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
443                    logger.info(em)
444                    no_import.write(em)
445                    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)
446                    continue
447                sid = temp_sid
448                sf = res[0].getObject().aq_parent
449                sc = getattr(sf,'study_course')
450                level = ''
451            else:
452                student_changed = False
[398]453            course = result.get('CosCode')
454            if course not in courses.keys():
455                em = 'Course with ID %(CosCode)s not found\n' % result
[396]456                logger.info(em)
457                no_import.write(em)
[398]458                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]459                continue
[727]460            course_doc = courses[course].getContent()
[723]461            temp_level = result.get('Level')
[742]462            student_id = sf.getId()
463            result['StudentId'] = student_id
[723]464            if temp_level != level:
465                try:
466                    int(temp_level)
467                except:
468                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
469                    logger.info(em)
470                    no_import.write(em)
471                    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)
472                    continue
[727]473                level_changed = True
474                if 'dlev' in vars().keys():
[723]475                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
476                level = temp_level
477                l = getattr(sc,level,None)
478                if l is None:
479                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
480                    sc.invokeFactory('StudentStudyLevel', level)
481                    l = getattr(sc, level)
[742]482                    l.manage_setLocalRoles(student_id, ['Owner',])
[723]483            else:
484                level_changed = False
485            cr = getattr(l,course,None)
486            if cr is None:
487                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
488                l.invokeFactory('StudentCourseResult',course)
489            cr = getattr(l,course)
490            dcr = {}
[727]491            from_course = ['title',
492                           'credits',
493                           'passmark',
494                           ]
495            for f in from_course:
496                dcr[f] = getattr(course_doc,f)
[454]497            dlev = {}
[723]498            dcr['ansbook'] = result.get('Ansbook')
499            dcr['semester'] = getInt(result.get('Semster'))
500            dcr['status'] = result.get('CosStuatus')
501            dcr['score'] = getInt(result.get('Score'))
[454]502            dlev['session'] = result.get('Session')
[723]503            dcr['carry_level'] = result.get('CarryLevel')
504            dcr['grade'] = result.get('Grade')
[725]505            dcr['weight'] = result.get('Weight')
[454]506            dlev['verdict'] = result.get('Verdict')
[725]507            dcr['import_id'] = result.get('id')
508            gpa = result.get('GPA').replace(',','.')
509            dlev['imported_gpa'] = getFloat(gpa)
[723]510            cr.getContent().edit(mapping = dcr)
[742]511            cr.manage_setLocalRoles(student_id, ['Owner',])
[454]512            l.getContent().edit(mapping = dlev)
[398]513            if tr_count > MAX_TRANS:
514                transaction.commit()
515                tr_count = 0
516            tr_count += 1
[723]517            wftool.doActionFor(cr,'close')
518        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
[681]519        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[426]520
[398]521###)
[396]522
[457]523    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
524    def loadJAMBFromCSV(self):
525        """load JAMB data from CSV values"""
526        #return
527        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
528        import transaction
529        tr_count = 0
[572]530        name = 'SampleJAMBDataII'
[511]531        wftool = self.portal_workflow
[457]532        no_import = False
533        if not no_import:
534            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
535            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')
536        logger = logging.getLogger('%s_import' % name)
537        logger.info('Start loading from %s.csv' % name)
538        try:
539            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
540        except:
541            logger.error('Error reading %s.csv' % name)
542            return
543        for jamb in result:
544            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)
545            jamb_reg_no = jamb.get('REG-NO')
[472]546            res = self.portal_catalog({'meta_type': "StudentApplication",
[457]547                                     'jamb_reg_no': jamb_reg_no })
548            if res:
549                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
550                logger.info(em)
551                no_import.write(em)
552                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)
553                continue
[511]554            jamb_name = jamb.get("NAME")
[584]555            jamb_name.replace('>','')
[511]556            names = jamb_name.split()
557            letter = names[-1][0].upper()
[714]558            sid = self.generateStudentId(letter)
[457]559            not_created = True
560            while not_created:
561                try:
562                    students_folder.invokeFactory('Student', sid)
563                    not_created = False
564                except BadRequest:
[714]565                    sid = self.generateStudentId(letter)
[457]566            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[511]567            student = getattr(self,sid)
[519]568            student.manage_setLocalRoles(sid, ['Owner',])
[511]569            student.invokeFactory('StudentApplication','application')
[472]570            da = {'Title': 'Application Data'}
[457]571            da["jamb_reg_no"] = jamb.get("REG-NO")
[511]572            da["jamb_lastname"] = jamb_name
[457]573            da["jamb_sex"] = jamb.get("SEX")
574            da["jamb_state"] = jamb.get("STATE")
575            da["jamb_lga"] = jamb.get("LGA")
576            da["jamb_score"] = jamb.get("AGGREGATE")
577            da["jamb_first_cos"] = jamb.get("COURSE1")
578            da["jamb_second_cos"] = jamb.get("COURSE2")
579            da["jamb_first_uni"] = jamb.get("UNIV1")
580            da["jamb_second_uni"] = jamb.get("UNIV2")
[511]581            app = student.application
582            app_doc = app.getContent()
583            app_doc.edit(mapping=da)
[658]584            #wftool.doActionFor(app,'open',dest_container=app)
[511]585            app.manage_setLocalRoles(sid, ['Owner',])
586            student.getContent().createSubObjects()
[457]587        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
588    ###)
[426]589
[472]590
[511]591    security.declareProtected(View,"fixOwnership")
592    def fixOwnership(self):
593        """fix Ownership"""
594        for s in self.portal_catalog(meta_type = 'Student'):
595            student = s.getObject()
596            sid = s.getId
597            import pdb;pdb.set_trace()
598            student.application.manage_setLocalRoles(sid, ['Owner',])
599            student.personal.manage_setLocalRoles(sid, ['Owner',])
[603]600
[364]601    security.declareProtected(View,"Title")
602    def Title(self):
603        """compose title"""
[382]604        return "Student Section"
[361]605
[714]606    def generateStudentId(self,letter): ###(
607        import random
608        r = random
609        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
610            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
611        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
612        sid = "%c%d" % (letter,r.randint(99999,1000000))
613        while hasattr(students, sid):
614            sid = "%c%d" % (letter,r.randint(99999,1000000))
[758]615        return sid
[714]616        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
617    ###)
618
[361]619InitializeClass(StudentsFolder)
620
621def addStudentsFolder(container, id, REQUEST=None, **kw):
622    """Add a Student."""
623    ob = StudentsFolder(id, **kw)
624    return CPSBase_adder(container, ob, REQUEST=REQUEST)
625###)
626
[57]627class Student(CPSDocument): ###(
628    """
[154]629    WAeUP Student container for the various student data
[57]630    """
631    meta_type = 'Student'
632    portal_type = meta_type
633    security = ClassSecurityInfo()
[154]634
[152]635    security.declareProtected(View,"Title")
636    def Title(self):
637        """compose title"""
[153]638        reg_nr = self.getId()[1:]
[362]639        data = getattr(self,'personal',None)
[152]640        if data:
641            content = data.getContent()
642            return "%s %s" % (content.firstname,content.lastname)
[472]643        data = getattr(self,'application',None)
[464]644        if data:
645            content = data.getContent()
646            return "%s" % (content.jamb_lastname)
[152]647        return self.title
[154]648
[511]649    security.declarePrivate('makeStudentMember') ###(
650    def makeStudentMember(self,sid,password='uNsEt'):
651        """make the student a member"""
652        membership = self.portal_membership
[603]653        membership.addMember(sid,
[511]654                             password ,
655                             roles=('Member',
656                                     'Student',
[522]657                                     ),
[511]658                             domains='',
[904]659                             properties = {'memberareaCreationFlag': False,
660                                           'homeless': True},)
[511]661        member = membership.getMemberById(sid)
662        self.portal_registration.afterAdd(member, sid, password, None)
663        self.manage_setLocalRoles(sid, ['Owner',])
664
665###)
666
[764]667    security.declareProtected(View,'createSubObjects') ###(
668    def createSubObjects(self):
669        """make the student a member"""
670        dp = {'Title': 'Personal Data'}
671        app_doc = self.application.getContent()
672        names = app_doc.jamb_lastname.split()
673        if len(names) == 3:
674            dp['firstname'] = names[0].capitalize()
675            dp['middlename'] = names[1].capitalize()
676            dp['lastname'] = names[2].capitalize()
677        elif len(names) == 2:
678            dp['firstname'] = names[0].capitalize()
679            dp['lastname'] = names[1].capitalize()
680        else:
681            dp['lastname'] = app_doc.jamb_lastname
682        dp['sex'] = app_doc.jamb_sex == 'F'
683        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
684        proxy = self.aq_parent
685        proxy.invokeFactory('StudentPersonal','personal')
686        per = proxy.personal
687        per_doc = per.getContent()
688        per_doc.edit(mapping = dp)
[927]689        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
[764]690        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]691
[511]692###)
693
[57]694InitializeClass(Student)
695
696def addStudent(container, id, REQUEST=None, **kw):
697    """Add a Student."""
698    ob = Student(id, **kw)
699    return CPSBase_adder(container, ob, REQUEST=REQUEST)
700
701###)
[91]702
[639]703class StudentAccommodation(CPSDocument): ###(
704    """
705    WAeUP Student container for the various student data
706    """
707    meta_type = 'StudentAccommodation'
708    portal_type = meta_type
709    security = ClassSecurityInfo()
710
711    security.declareProtected(View,"Title")
712    def Title(self):
713        """compose title"""
714        content = self.getContent()
715        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
716        return "Accommodation Data for Session %s" % content.session
717
718
719InitializeClass(StudentAccommodation)
720
721def addStudentAccommodation(container, id, REQUEST=None, **kw):
722    """Add a Students personal data."""
723    ob = StudentAccommodation(id, **kw)
724    return CPSBase_adder(container, ob, REQUEST=REQUEST)
725
726###)
727
[89]728class StudentPersonal(CPSDocument): ###(
729    """
[154]730    WAeUP Student container for the various student data
[89]731    """
732    meta_type = 'StudentPersonal'
733    portal_type = meta_type
734    security = ClassSecurityInfo()
[152]735
736    security.declareProtected(View,"Title")
737    def Title(self):
738        """compose title"""
739        content = self.getContent()
[364]740        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
741        return "Personal Data"
[152]742
[154]743
[89]744InitializeClass(StudentPersonal)
745
746def addStudentPersonal(container, id, REQUEST=None, **kw):
747    """Add a Students personal data."""
748    ob = StudentPersonal(id, **kw)
749    return CPSBase_adder(container, ob, REQUEST=REQUEST)
750
751###)
752
[423]753class StudentClearance(CPSDocument): ###(
754    """
755    WAeUP Student container for the various student data
756    """
757    meta_type = 'StudentClearance'
758    portal_type = meta_type
759    security = ClassSecurityInfo()
760
761    security.declareProtected(View,"Title")
762    def Title(self):
763        """compose title"""
764        content = self.getContent()
[840]765        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
766        return "Clearance/Eligibility Record"
[423]767
768
769InitializeClass(StudentClearance)
770
771def addStudentClearance(container, id, REQUEST=None, **kw):
772    """Add a Students personal data."""
773    ob = StudentClearance(id, **kw)
774    return CPSBase_adder(container, ob, REQUEST=REQUEST)
775
776###)
777
[454]778class StudentStudyLevel(CPSDocument): ###(
779    """
780    WAeUP Student container for the various student data
781    """
782    meta_type = 'StudentStudyLevel'
783    portal_type = meta_type
784    security = ClassSecurityInfo()
785
786    security.declareProtected(View,"Title")
787    def Title(self):
788        """compose title"""
789        return "Level %s" % self.aq_parent.getId()
790
[723]791##    security.declarePublic("gpa")
792##    def gpa(self):
793##        """calculate the gpa"""
794##        sum = 0
795##        course_count = 0
796##        for sc in self.objectValues():
797##            result = sc.getContent()
798##            if not result.grade:
799##                continue
800##            res = self.portal_catalog({'meta_type': 'Course',
801##                                          'id': sc.aq_parent.id})
802##            if len(res) != 1:
803##                continue
804##            course = res[0].getObject().getContent()
805##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
806##            course_count += 1
807##        if course_count:
808##            return sum/course_count
809##        return 0.0
[472]810
[454]811InitializeClass(StudentStudyLevel)
812
813def addStudentStudyLevel(container, id, REQUEST=None, **kw):
814    """Add a Students personal data."""
815    ob = StudentStudyLevel(id, **kw)
816    return CPSBase_adder(container, ob, REQUEST=REQUEST)
817
818###)
819
[362]820class StudentStudyCourse(CPSDocument): ###(
821    """
822    WAeUP Student container for the various student data
823    """
824    meta_type = 'StudentStudyCourse'
825    portal_type = meta_type
826    security = ClassSecurityInfo()
827
[364]828    security.declareProtected(View,"Title")
829    def Title(self):
830        """compose title"""
831        content = self.getContent()
[453]832        return "Study Course"
[362]833
834
835InitializeClass(StudentStudyCourse)
836
837def addStudentStudyCourse(container, id, REQUEST=None, **kw):
838    """Add a Students personal data."""
839    ob = StudentStudyCourse(id, **kw)
840    return CPSBase_adder(container, ob, REQUEST=REQUEST)
841
842###)
843
[472]844class StudentApplication(CPSDocument): ###(
[179]845    """
846    WAeUP Student container for the various student data
847    """
[472]848    meta_type = 'StudentApplication'
[179]849    portal_type = meta_type
850    security = ClassSecurityInfo()
851
[181]852    security.declareProtected(View,"Title")
853    def Title(self):
854        """compose title"""
[472]855        return "Application Data"
[179]856
[181]857
[472]858InitializeClass(StudentApplication)
[179]859
[472]860def addStudentApplication(container, id, REQUEST=None, **kw):
[179]861    """Add a Students eligibility data."""
[472]862    ob = StudentApplication(id, **kw)
[179]863    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]864###)
[179]865
[758]866
867class StudentPume(CPSDocument): ###(
868    """
869    WAeUP Student container for the various student data
870    """
871    meta_type = 'StudentPume'
872    portal_type = meta_type
873    security = ClassSecurityInfo()
874
875    security.declareProtected(View,"Title")
876    def Title(self):
877        """compose title"""
878        return "PUME Results"
879
880
881InitializeClass(StudentPume)
882
883def addStudentPume(container, id, REQUEST=None, **kw):
884    """Add a Students PUME data."""
885    ob = StudentPume(id, **kw)
886    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[179]887###)
[181]888
[565]889##class StudentSemester(CPSDocument): ###(
890##    """
891##    WAeUP StudentSemester containing the courses and students
892##    """
893##    meta_type = 'StudentSemester'
894##    portal_type = meta_type
895##    security = ClassSecurityInfo()
896##
897##InitializeClass(StudentSemester)
898##
899##def addStudentSemester(container, id, REQUEST=None, **kw):
900##    """Add a StudentSemester."""
901##    ob = StudentSemester(id, **kw)
902##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
903##
904#####)
[464]905
[758]906##class Semester(CPSDocument): ###(
907##    """
908##    WAeUP Semester containing the courses and students
909##    """
910##    meta_type = 'Semester'
911##    portal_type = meta_type
912##    security = ClassSecurityInfo()
913##
914##InitializeClass(Semester)
915##
916##def addSemester(container, id, REQUEST=None, **kw):
917##    """Add a Semester."""
918##    ob = Semester(id, **kw)
919##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
920##
921#####)
[464]922
923class StudentCourseResult(CPSDocument): ###(
[89]924    """
[464]925    WAeUP StudentCourseResult
[89]926    """
[464]927    meta_type = 'StudentCourseResult'
[89]928    portal_type = meta_type
929    security = ClassSecurityInfo()
[472]930
[454]931    def getCourseEntry(self,cid):
[723]932        res = self.portal_catalog({'meta_type': "Course",
[454]933                                           'id': cid})
934        if res:
935            return res[-1]
936        else:
937            return None
[154]938
[454]939    security.declareProtected(View,"Title")
940    def Title(self):
941        """compose title"""
[723]942        cid = self.aq_parent.getId()
[454]943        ce = self.getCourseEntry(cid)
944        if ce:
945            return "%s" % ce.Title
946        return "No course with id %s" % cid
[152]947
[464]948InitializeClass(StudentCourseResult)
[454]949
[464]950def addStudentCourseResult(container, id, REQUEST=None, **kw):
951    """Add a StudentCourseResult."""
952    ob = StudentCourseResult(id, **kw)
[89]953    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]954###)
955
[579]956# Backward Compatibility StudyLevel
957
958from Products.WAeUP_SRP.Academics import StudyLevel
959
960from Products.WAeUP_SRP.Academics import addStudyLevel
961
Note: See TracBrowser for help on using the repository browser.