source: WAeUP_SRP/trunk/Students.py @ 783

Last change on this file since 783 was 780, checked in by joachim, 19 years ago

view PUME result finalized,
export of PINs started

  • Property svn:keywords set to Id
File size: 38.5 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 780 2006-11-02 10:56:46Z 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
[422]138                dc = {'Title': 'Clearance Data'}
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
[757]297            jamb_name = jamb.get(csv_d['jamb_lastname'])
298            jamb_name.replace('>','')
299            names = jamb_name.split()
300            letter = names[-1][0].upper()
301            sid = self.generateStudentId(letter)
302            not_created = True
303            while not_created:
304                try:
305                    students_folder.invokeFactory('Student', sid)
306                    not_created = False
307                except BadRequest:
308                    sid = self.generateStudentId(letter)
309            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
310            student = getattr(self,sid)
311            student.manage_setLocalRoles(sid, ['Owner',])
[766]312            student.invokeFactory('StudentClearance','clearance')
[775]313            #wftool.doActionFor(student.clearance,'open')
[766]314            dp = {'Title': 'Clearance Data'}
315            student.clearance.manage_setLocalRoles(sid, ['Owner',])
[763]316            student.invokeFactory('StudentPume','pume')
317            dp = {'Title': 'Pume Data'}
[757]318            student.invokeFactory('StudentApplication','application')
319            da = {'Title': 'Application Data'}
320            da["jamb_lastname"] = jamb_name
321            da_fields = ('jamb_reg_no',
322                         'jamb_sex',
323                         'jamb_state',
324                         'jamb_score',
325                         'jamb_first_cos',
326                         'jamb_sex',
327                         'jamb_state',
328                         'jamb_first_cos',
329                         'jamb_second_cos',
330                         )
[763]331            for f in da_fields:
332                da[f] = jamb.get(csv_d[f])
[757]333            app = student.application
[763]334            app.getContent().edit(mapping=da)
[757]335            app.manage_setLocalRoles(sid, ['Owner',])
[780]336            #wftool.doActionFor(app,'close')
[763]337            dp_fields = (
338                         'pume_eng_score',
[764]339                         'pume_gen_score',
[763]340                         'pume_tot_score',
341                         )
342            for f in dp_fields:
[775]343                dp[f] = float(jamb.get(csv_d[f]))
[765]344            pume = student.pume
345            pume.getContent().edit(mapping=dp)
[780]346            #wftool.doActionFor(pume,'close')
[763]347            pume.manage_setLocalRoles(sid, ['Owner',])
[757]348            student.getContent().createSubObjects()
[775]349            if dp['pume_tot_score']>49:
[780]350                wftool.doActionFor(student,'pume_pass')
[775]351            else:
[780]352                wftool.doActionFor(student,'pume_fail')
[757]353            if len(no_import) > 1:
354                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
355                     '\n'.join(no_import))
[742]356        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
357    ###)
358
[398]359    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
[396]360    def loadFullTimeStudentsResultsFromCSV(self):
361        """load Fulltime Studentdata from CSV values"""
362        #return
[723]363        level_wf_actions = {}
364        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
365        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
[727]366        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
367        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
[398]368        import transaction
[723]369        wftool = self.portal_workflow
[398]370        tr_count = 0
371        name = 'short_full_time_results_2004_2005'
[396]372        no_import = False
373        if not no_import:
374            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
375            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
376        logger = logging.getLogger('%s_import' % name)
377        logger.info('Start loading from %s.csv' % name)
378        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
379        try:
380            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
381        except:
382            logger.error('Error reading %s.csv' % name)
383            return
[398]384        l = self.portal_catalog({'meta_type': "Course"})
385        courses = {}
386        for c in l:
387            courses[c.id] = c.getObject()
[723]388        level_changed = False
389        student_changed = False
390        sid = ''
391        #import pdb;pdb.set_trace()
[396]392        for result in results:
[723]393            temp_sid = result.get('Matnumber')
394            if temp_sid != sid:
395                student_changed = True
396                res = self.portal_catalog({'meta_type': "StudentClearance",
397                                         'SearchableText': temp_sid })
398                if not res:
399                    em = 'Student with ID %(Matnumber)s not found\n' % result
400                    logger.info(em)
401                    no_import.write(em)
402                    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)
403                    continue
404                elif len(res) > 1:
405                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
406                    logger.info(em)
407                    no_import.write(em)
408                    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)
409                    continue
410                sid = temp_sid
411                sf = res[0].getObject().aq_parent
412                sc = getattr(sf,'study_course')
413                level = ''
414            else:
415                student_changed = False
[398]416            course = result.get('CosCode')
417            if course not in courses.keys():
418                em = 'Course with ID %(CosCode)s not found\n' % result
[396]419                logger.info(em)
420                no_import.write(em)
[398]421                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]422                continue
[727]423            course_doc = courses[course].getContent()
[723]424            temp_level = result.get('Level')
[742]425            student_id = sf.getId()
426            result['StudentId'] = student_id
[723]427            if temp_level != level:
428                try:
429                    int(temp_level)
430                except:
431                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
432                    logger.info(em)
433                    no_import.write(em)
434                    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)
435                    continue
[727]436                level_changed = True
437                if 'dlev' in vars().keys():
[723]438                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
439                level = temp_level
440                l = getattr(sc,level,None)
441                if l is None:
442                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
443                    sc.invokeFactory('StudentStudyLevel', level)
444                    l = getattr(sc, level)
[742]445                    l.manage_setLocalRoles(student_id, ['Owner',])
[723]446            else:
447                level_changed = False
448            cr = getattr(l,course,None)
449            if cr is None:
450                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
451                l.invokeFactory('StudentCourseResult',course)
452            cr = getattr(l,course)
453            dcr = {}
[727]454            from_course = ['title',
455                           'credits',
456                           'passmark',
457                           ]
458            for f in from_course:
459                dcr[f] = getattr(course_doc,f)
[454]460            dlev = {}
[723]461            dcr['ansbook'] = result.get('Ansbook')
462            dcr['semester'] = getInt(result.get('Semster'))
463            dcr['status'] = result.get('CosStuatus')
464            dcr['score'] = getInt(result.get('Score'))
[454]465            dlev['session'] = result.get('Session')
[723]466            dcr['carry_level'] = result.get('CarryLevel')
467            dcr['grade'] = result.get('Grade')
[725]468            dcr['weight'] = result.get('Weight')
[454]469            dlev['verdict'] = result.get('Verdict')
[725]470            dcr['import_id'] = result.get('id')
471            gpa = result.get('GPA').replace(',','.')
472            dlev['imported_gpa'] = getFloat(gpa)
[723]473            cr.getContent().edit(mapping = dcr)
[742]474            cr.manage_setLocalRoles(student_id, ['Owner',])
[454]475            l.getContent().edit(mapping = dlev)
[398]476            if tr_count > MAX_TRANS:
477                transaction.commit()
478                tr_count = 0
479            tr_count += 1
[723]480            wftool.doActionFor(cr,'close')
481        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
[681]482        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[426]483
[398]484###)
[396]485
[457]486    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
487    def loadJAMBFromCSV(self):
488        """load JAMB data from CSV values"""
489        #return
490        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
491        import transaction
492        tr_count = 0
[572]493        name = 'SampleJAMBDataII'
[511]494        wftool = self.portal_workflow
[457]495        no_import = False
496        if not no_import:
497            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
498            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')
499        logger = logging.getLogger('%s_import' % name)
500        logger.info('Start loading from %s.csv' % name)
501        try:
502            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
503        except:
504            logger.error('Error reading %s.csv' % name)
505            return
506        for jamb in result:
507            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)
508            jamb_reg_no = jamb.get('REG-NO')
[472]509            res = self.portal_catalog({'meta_type': "StudentApplication",
[457]510                                     'jamb_reg_no': jamb_reg_no })
511            if res:
512                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
513                logger.info(em)
514                no_import.write(em)
515                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)
516                continue
[511]517            jamb_name = jamb.get("NAME")
[584]518            jamb_name.replace('>','')
[511]519            names = jamb_name.split()
520            letter = names[-1][0].upper()
[714]521            sid = self.generateStudentId(letter)
[457]522            not_created = True
523            while not_created:
524                try:
525                    students_folder.invokeFactory('Student', sid)
526                    not_created = False
527                except BadRequest:
[714]528                    sid = self.generateStudentId(letter)
[457]529            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[511]530            student = getattr(self,sid)
[519]531            student.manage_setLocalRoles(sid, ['Owner',])
[511]532            student.invokeFactory('StudentApplication','application')
[472]533            da = {'Title': 'Application Data'}
[457]534            da["jamb_reg_no"] = jamb.get("REG-NO")
[511]535            da["jamb_lastname"] = jamb_name
[457]536            da["jamb_sex"] = jamb.get("SEX")
537            da["jamb_state"] = jamb.get("STATE")
538            da["jamb_lga"] = jamb.get("LGA")
539            da["jamb_score"] = jamb.get("AGGREGATE")
540            da["jamb_first_cos"] = jamb.get("COURSE1")
541            da["jamb_second_cos"] = jamb.get("COURSE2")
542            da["jamb_first_uni"] = jamb.get("UNIV1")
543            da["jamb_second_uni"] = jamb.get("UNIV2")
[511]544            app = student.application
545            app_doc = app.getContent()
546            app_doc.edit(mapping=da)
[658]547            #wftool.doActionFor(app,'open',dest_container=app)
[511]548            app.manage_setLocalRoles(sid, ['Owner',])
549            student.getContent().createSubObjects()
[457]550        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
551    ###)
[426]552
[472]553
[511]554    security.declareProtected(View,"fixOwnership")
555    def fixOwnership(self):
556        """fix Ownership"""
557        for s in self.portal_catalog(meta_type = 'Student'):
558            student = s.getObject()
559            sid = s.getId
560            import pdb;pdb.set_trace()
561            student.application.manage_setLocalRoles(sid, ['Owner',])
562            student.personal.manage_setLocalRoles(sid, ['Owner',])
[603]563
[364]564    security.declareProtected(View,"Title")
565    def Title(self):
566        """compose title"""
[382]567        return "Student Section"
[361]568
[714]569    def generateStudentId(self,letter): ###(
570        import random
571        r = random
572        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
573            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
574        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
575        sid = "%c%d" % (letter,r.randint(99999,1000000))
576        while hasattr(students, sid):
577            sid = "%c%d" % (letter,r.randint(99999,1000000))
[758]578        return sid
[714]579        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
580    ###)
581
[361]582InitializeClass(StudentsFolder)
583
584def addStudentsFolder(container, id, REQUEST=None, **kw):
585    """Add a Student."""
586    ob = StudentsFolder(id, **kw)
587    return CPSBase_adder(container, ob, REQUEST=REQUEST)
588###)
589
[57]590class Student(CPSDocument): ###(
591    """
[154]592    WAeUP Student container for the various student data
[57]593    """
594    meta_type = 'Student'
595    portal_type = meta_type
596    security = ClassSecurityInfo()
[154]597
[152]598    security.declareProtected(View,"Title")
599    def Title(self):
600        """compose title"""
[153]601        reg_nr = self.getId()[1:]
[362]602        data = getattr(self,'personal',None)
[152]603        if data:
604            content = data.getContent()
605            return "%s %s" % (content.firstname,content.lastname)
[472]606        data = getattr(self,'application',None)
[464]607        if data:
608            content = data.getContent()
609            return "%s" % (content.jamb_lastname)
[152]610        return self.title
[154]611
[511]612    security.declarePrivate('makeStudentMember') ###(
613    def makeStudentMember(self,sid,password='uNsEt'):
614        """make the student a member"""
615        membership = self.portal_membership
[603]616        membership.addMember(sid,
[511]617                             password ,
618                             roles=('Member',
619                                     'Student',
[522]620                                     ),
[511]621                             domains='',
[522]622                             properties = {'memberareaCreationFlag': False,},)
[511]623        member = membership.getMemberById(sid)
624        self.portal_registration.afterAdd(member, sid, password, None)
625        self.manage_setLocalRoles(sid, ['Owner',])
626
627###)
628
[764]629    security.declareProtected(View,'createSubObjects') ###(
630    def createSubObjects(self):
631        """make the student a member"""
632        dp = {'Title': 'Personal Data'}
633        app_doc = self.application.getContent()
634        names = app_doc.jamb_lastname.split()
635        if len(names) == 3:
636            dp['firstname'] = names[0].capitalize()
637            dp['middlename'] = names[1].capitalize()
638            dp['lastname'] = names[2].capitalize()
639        elif len(names) == 2:
640            dp['firstname'] = names[0].capitalize()
641            dp['lastname'] = names[1].capitalize()
642        else:
643            dp['lastname'] = app_doc.jamb_lastname
644        dp['sex'] = app_doc.jamb_sex == 'F'
645        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
646        proxy = self.aq_parent
647        proxy.invokeFactory('StudentPersonal','personal')
648        per = proxy.personal
649        per_doc = per.getContent()
650        per_doc.edit(mapping = dp)
651        per.manage_setLocalRoles(self.getId(), ['Owner',])
652        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]653
[511]654###)
655
[57]656InitializeClass(Student)
657
658def addStudent(container, id, REQUEST=None, **kw):
659    """Add a Student."""
660    ob = Student(id, **kw)
661    return CPSBase_adder(container, ob, REQUEST=REQUEST)
662
663###)
[91]664
[639]665class StudentAccommodation(CPSDocument): ###(
666    """
667    WAeUP Student container for the various student data
668    """
669    meta_type = 'StudentAccommodation'
670    portal_type = meta_type
671    security = ClassSecurityInfo()
672
673    security.declareProtected(View,"Title")
674    def Title(self):
675        """compose title"""
676        content = self.getContent()
677        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
678        return "Accommodation Data for Session %s" % content.session
679
680
681InitializeClass(StudentAccommodation)
682
683def addStudentAccommodation(container, id, REQUEST=None, **kw):
684    """Add a Students personal data."""
685    ob = StudentAccommodation(id, **kw)
686    return CPSBase_adder(container, ob, REQUEST=REQUEST)
687
688###)
689
[89]690class StudentPersonal(CPSDocument): ###(
691    """
[154]692    WAeUP Student container for the various student data
[89]693    """
694    meta_type = 'StudentPersonal'
695    portal_type = meta_type
696    security = ClassSecurityInfo()
[152]697
698    security.declareProtected(View,"Title")
699    def Title(self):
700        """compose title"""
701        content = self.getContent()
[364]702        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
703        return "Personal Data"
[152]704
[154]705
[89]706InitializeClass(StudentPersonal)
707
708def addStudentPersonal(container, id, REQUEST=None, **kw):
709    """Add a Students personal data."""
710    ob = StudentPersonal(id, **kw)
711    return CPSBase_adder(container, ob, REQUEST=REQUEST)
712
713###)
714
[423]715class StudentClearance(CPSDocument): ###(
716    """
717    WAeUP Student container for the various student data
718    """
719    meta_type = 'StudentClearance'
720    portal_type = meta_type
721    security = ClassSecurityInfo()
722
723    security.declareProtected(View,"Title")
724    def Title(self):
725        """compose title"""
726        content = self.getContent()
727        #return "Clearance Data for %s %s" % (content.firstname,content.lastname)
728        return "Clearance Data"
729
730
731InitializeClass(StudentClearance)
732
733def addStudentClearance(container, id, REQUEST=None, **kw):
734    """Add a Students personal data."""
735    ob = StudentClearance(id, **kw)
736    return CPSBase_adder(container, ob, REQUEST=REQUEST)
737
738###)
739
[454]740class StudentStudyLevel(CPSDocument): ###(
741    """
742    WAeUP Student container for the various student data
743    """
744    meta_type = 'StudentStudyLevel'
745    portal_type = meta_type
746    security = ClassSecurityInfo()
747
748    security.declareProtected(View,"Title")
749    def Title(self):
750        """compose title"""
751        return "Level %s" % self.aq_parent.getId()
752
[723]753##    security.declarePublic("gpa")
754##    def gpa(self):
755##        """calculate the gpa"""
756##        sum = 0
757##        course_count = 0
758##        for sc in self.objectValues():
759##            result = sc.getContent()
760##            if not result.grade:
761##                continue
762##            res = self.portal_catalog({'meta_type': 'Course',
763##                                          'id': sc.aq_parent.id})
764##            if len(res) != 1:
765##                continue
766##            course = res[0].getObject().getContent()
767##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
768##            course_count += 1
769##        if course_count:
770##            return sum/course_count
771##        return 0.0
[472]772
[454]773InitializeClass(StudentStudyLevel)
774
775def addStudentStudyLevel(container, id, REQUEST=None, **kw):
776    """Add a Students personal data."""
777    ob = StudentStudyLevel(id, **kw)
778    return CPSBase_adder(container, ob, REQUEST=REQUEST)
779
780###)
781
[362]782class StudentStudyCourse(CPSDocument): ###(
783    """
784    WAeUP Student container for the various student data
785    """
786    meta_type = 'StudentStudyCourse'
787    portal_type = meta_type
788    security = ClassSecurityInfo()
789
[364]790    security.declareProtected(View,"Title")
791    def Title(self):
792        """compose title"""
793        content = self.getContent()
[453]794        return "Study Course"
[362]795
796
797InitializeClass(StudentStudyCourse)
798
799def addStudentStudyCourse(container, id, REQUEST=None, **kw):
800    """Add a Students personal data."""
801    ob = StudentStudyCourse(id, **kw)
802    return CPSBase_adder(container, ob, REQUEST=REQUEST)
803
804###)
805
[472]806class StudentApplication(CPSDocument): ###(
[179]807    """
808    WAeUP Student container for the various student data
809    """
[472]810    meta_type = 'StudentApplication'
[179]811    portal_type = meta_type
812    security = ClassSecurityInfo()
813
[181]814    security.declareProtected(View,"Title")
815    def Title(self):
816        """compose title"""
[472]817        return "Application Data"
[179]818
[181]819
[472]820InitializeClass(StudentApplication)
[179]821
[472]822def addStudentApplication(container, id, REQUEST=None, **kw):
[179]823    """Add a Students eligibility data."""
[472]824    ob = StudentApplication(id, **kw)
[179]825    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]826###)
[179]827
[758]828
829class StudentPume(CPSDocument): ###(
830    """
831    WAeUP Student container for the various student data
832    """
833    meta_type = 'StudentPume'
834    portal_type = meta_type
835    security = ClassSecurityInfo()
836
837    security.declareProtected(View,"Title")
838    def Title(self):
839        """compose title"""
840        return "PUME Results"
841
842
843InitializeClass(StudentPume)
844
845def addStudentPume(container, id, REQUEST=None, **kw):
846    """Add a Students PUME data."""
847    ob = StudentPume(id, **kw)
848    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[179]849###)
[181]850
[565]851##class StudentSemester(CPSDocument): ###(
852##    """
853##    WAeUP StudentSemester containing the courses and students
854##    """
855##    meta_type = 'StudentSemester'
856##    portal_type = meta_type
857##    security = ClassSecurityInfo()
858##
859##InitializeClass(StudentSemester)
860##
861##def addStudentSemester(container, id, REQUEST=None, **kw):
862##    """Add a StudentSemester."""
863##    ob = StudentSemester(id, **kw)
864##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
865##
866#####)
[464]867
[758]868##class Semester(CPSDocument): ###(
869##    """
870##    WAeUP Semester containing the courses and students
871##    """
872##    meta_type = 'Semester'
873##    portal_type = meta_type
874##    security = ClassSecurityInfo()
875##
876##InitializeClass(Semester)
877##
878##def addSemester(container, id, REQUEST=None, **kw):
879##    """Add a Semester."""
880##    ob = Semester(id, **kw)
881##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
882##
883#####)
[464]884
885class StudentCourseResult(CPSDocument): ###(
[89]886    """
[464]887    WAeUP StudentCourseResult
[89]888    """
[464]889    meta_type = 'StudentCourseResult'
[89]890    portal_type = meta_type
891    security = ClassSecurityInfo()
[472]892
[454]893    def getCourseEntry(self,cid):
[723]894        res = self.portal_catalog({'meta_type': "Course",
[454]895                                           'id': cid})
896        if res:
897            return res[-1]
898        else:
899            return None
[154]900
[454]901    security.declareProtected(View,"Title")
902    def Title(self):
903        """compose title"""
[723]904        cid = self.aq_parent.getId()
[454]905        ce = self.getCourseEntry(cid)
906        if ce:
907            return "%s" % ce.Title
908        return "No course with id %s" % cid
[152]909
[464]910InitializeClass(StudentCourseResult)
[454]911
[464]912def addStudentCourseResult(container, id, REQUEST=None, **kw):
913    """Add a StudentCourseResult."""
914    ob = StudentCourseResult(id, **kw)
[89]915    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]916###)
917
[579]918# Backward Compatibility StudyLevel
919
920from Products.WAeUP_SRP.Academics import StudyLevel
921
922from Products.WAeUP_SRP.Academics import addStudyLevel
923
Note: See TracBrowser for help on using the repository browser.