source: WAeUP_SRP/trunk/Students.py @ 1080

Last change on this file since 1080 was 1065, checked in by joachim, 18 years ago

improved search, modify studycourse, patchfor attribute error

  • Property svn:keywords set to Id
File size: 57.5 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 1065 2006-12-15 13:42:56Z 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
[971]19import csv,re,os
[362]20import Globals
21p_home = Globals.package_home(globals())
22i_home = Globals.INSTANCE_HOME
[981]23MAX_TRANS = 1000
[966]24import DateTime
[971]25import PIL.Image
26from StringIO import StringIO
[154]27
[958]28def makeCertificateCode(code): ###(
29    code = code.replace('.','')
30    code = code.replace('(','')
31    code = code.replace(')','')
32    code = code.replace('/','')
33    code = code.replace(' ','')
34    code = code.replace('_','')
35    return code
36
37###)
38
39def getInt(s): ###(
[723]40    try:
41        return int(s)
42    except:
43        return 0
[422]44
[725]45def getFloat(s):
46    try:
47        return float(s)
48    except:
49        return 0.0
50
[958]51###)
52
[714]53def getStudentByRegNo(self,reg_no): ###(
[502]54    """search student by JAMB Reg No and return StudentFolder"""
55    search = ZCatalog.searchResults(self.portal_catalog,{'meta_type': 'StudentApplication',
[606]56                                  'SearchableText': reg_no,
[502]57                                  })
58    if len(search) < 1:
59        return None
60    return search[0].getObject().aq_parent
61
[714]62###)
63
[361]64class StudentsFolder(CPSDocument): ###(
65    """
66    WAeUP container for the various WAeUP containers data
67    """
[362]68    meta_type = 'StudentsFolder'
[361]69    portal_type = meta_type
70    security = ClassSecurityInfo()
[154]71
[361]72    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsFromCSV")###(
73    def loadFullTimeStudentsFromCSV(self):
74        """load Fulltime Studentdata from CSV values"""
[398]75        import transaction
[708]76        import random
[398]77        tr_count = 0
[361]78        name = 'short_full_time'
79        no_import = False
[395]80        if not no_import:
81            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
82            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]83        logger = logging.getLogger('%s_import' % name)
84        logger.info('Start loading from %s.csv' % name)
[708]85        pwlist  = []
86        pwlist.append('"student_id","firstname","middlename","lastname","matric_no","jamb_reg_no","access_code"')
87        pwl_template = Template('"$student_id","$firstname","$middlename","$lastname","$matric_no","$jamb_reg_no","$access_code"')
[361]88        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
89        try:
90            students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
91        except:
92            logger.error('Error reading %s.csv' % name)
93            return
[422]94        l = self.portal_catalog({'meta_type': "StudentClearance",})
95        matrics = []
[361]96        for s in l:
[422]97            matrics.append(s.getObject().getContent().matric_no)
[423]98        print matrics
[361]99        l = self.portal_catalog({'meta_type': "Certificate"})
100        certs = {}
101        for c in l:
[727]102            ca,ac,fa,dep_id,co,certcode = c.relative_path.split('/')
103            cid = "%(dep_id)s_%(certcode)s" % vars()
104            certs[cid] = c.getObject()
[361]105        for student in students:
[393]106            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]107            sid = student.get('MatricNo')
[396]108            if sid == "":
109                em = 'Empty MatricNo\n'
110                logger.info(em)
111                no_import.write(em)
112                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)
113                continue
[361]114            certcode = makeCertificateCode(student.get('CourseMajor'))
[727]115            dep_id = student.get('Dept')
116            fac_id = student.get('Faculty')
117            cid = "%(dep_id)s_%(certcode)s" % vars()
118            if cid not in certs.keys():
[393]119                em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
[361]120                logger.info(em)
[393]121                no_import.write(em)
122                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]123                continue
[727]124            certificate_doc = certs[cid].getContent()
[395]125            level = student.get('StudentLevel')
[426]126            try:
[395]127                int(level)
128            except:
129                em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
130                logger.info(em)
131                no_import.write(em)
132                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)
133                continue
[422]134            matric_no = student.get('MatricNo')
135            if matric_no not in matrics:
136                matrics.append(matric_no)
[714]137                sid = self.generateStudentId(student.get('Lastname')[0])
[361]138                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
[714]139                students_folder.invokeFactory('Student', sid)
[426]140                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
[714]141                student_obj = getattr(self,sid)
[708]142                access_code = "%d" % random.randint(1000000000,9999999999)
[746]143                student_obj.getContent().makeStudentMember(sid,access_code,)
[708]144                pwl_dict = {'student_id': sid,'access_code':access_code}
[714]145                student_obj.invokeFactory('StudentApplication','application')
146                application = student_obj.application
[472]147                da = {'Title': 'Application Data'}
[714]148                student_obj.invokeFactory('StudentPersonal','personal')
[446]149                da['jamb_reg_no'] = student.get('EntryRegNo')
[714]150                personal = student_obj.personal
[708]151                dp = {'Title': 'Personal Data'}
[714]152                student_obj.invokeFactory('StudentClearance','clearance')
153                clearance = student_obj.clearance
[840]154                dc = {'Title': 'Clearance/Eligibility Record'}
[422]155                dc['matric_no'] = matric_no
[714]156                state = student.get('State')
157                lga = student.get('LGA')
158                if state and lga:
159                    lga =  state + ' / ' + lga
160                else:
161                    lga = "None"
[427]162                dc['lga'] = lga
[422]163                dc['nationality'] = student.get('Nationality')
164                dc['email'] = student.get('Emailaddress')
[708]165                dp['firstname'] = student.get('FirstName')
166                dp['middlename'] = student.get('MiddleName')
167                dp['lastname'] = student.get('Lastname')
168                dp['former_surname'] = student.get('FormerSurname')
169                dp['sex'] = student.get('Sex') == 'F'
170                dp['perm_address'] = student.get('PermanentAddress')
171                dp['perm_city'] = student.get('PermanentAddressCity')
172                dp['campus_address'] = student.get('CampusAddress')
173                dp['phone'] = student.get('PhoneNumber')
[714]174                application.getContent().edit(mapping=da)
175                personal.getContent().edit(mapping=dp)
176                clearance.getContent().edit(mapping=dc)
[362]177                #
178                # Study Course
179                #
[714]180                student_obj.invokeFactory('StudentStudyCourse','study_course')
181                studycourse = student_obj.study_course
[708]182                dsc = {}
[727]183                from_certificate = ['title',
184                                   'max_elect',
185                                   'max_pass',
186                                   'n_core',
187                                   'nr_years',
188                                   'probation_credits',
189                                   'promotion_credits',
190                                   'start_level',
191                                  ]
192                for f in from_certificate:
193                    dsc[f] = getattr(certificate_doc,f)
194                dsc['faculty'] = fac_id
195                dsc['department'] = dep_id
[708]196                dsc['study_course'] = certcode
[454]197                css = student.get('CurrentSession') or '2004-2005'
198                cs = int(css.split('-')[0]) - 2000
[714]199                cl = int(student.get('StudentLevel') or '100')/100
[708]200                dsc['entry_session'] = "200%s" % (cs - cl)
201                dsc['clr_ac_pin'] = access_code
[714]202                studycourse.getContent().edit(mapping=dsc)
[364]203                #
204                # Level
205                #
[723]206##                l = getattr(studycourse,level,None)
207##                if 0 and l is None:
208##                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
209##                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
210##                    studycourse.invokeFactory('StudentStudyLevel', level)
211##                    l = getattr(studycourse, level)
212##                    certificate = certs[certcode]
213##                    cert_level = getattr(certificate,level,None)
214##                    if cert_level is None:
215##                        logger.info('Level %(level)s not in %(certcode)s' % vars())
216##                    l.getContent().edit(mapping={'Title': "Level %s" % level})
[361]217            else:
[393]218                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
[361]219                logger.info(em)
[393]220                no_import.write(em)
221                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]222                continue
[398]223            if tr_count > MAX_TRANS:
[422]224                transaction.commit()
225                em = 'Transaction commited\n' % student
[398]226                logger.info(em)
227                tr_count = 0
228            tr_count += 1
[708]229            pwl_dict.update(dc)
230            pwl_dict.update(da)
231            pwl_dict.update(dp)
[714]232            wftool = self.portal_workflow
[708]233            pwlist.append(pwl_template.substitute(pwl_dict))
[714]234            wftool.doActionFor(student_obj,'clear_and_validate')
[742]235            student_obj.manage_setLocalRoles(sid, ['Owner',])
[714]236            wftool.doActionFor(application,'close')
[742]237            application.manage_setLocalRoles(sid, ['Owner',])
[714]238            wftool.doActionFor(clearance,'close')
[742]239            clearance.manage_setLocalRoles(sid, ['Owner',])
[714]240            wftool.doActionFor(personal,'close')
[742]241            personal.manage_setLocalRoles(sid, ['Owner',])
[727]242            wftool.doActionFor(studycourse,'close_for_edit')
[742]243            studycourse.manage_setLocalRoles(sid, ['Owner',])
[714]244        open("%s/import/pwlist-%s.csv" % (i_home,name),"w+").write('\n'.join(pwlist))
[423]245        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[361]246    ###)
[382]247
[742]248    security.declareProtected(ModifyPortalContent,"loadPumeResultsFromCSV")###(
249    def loadPumeResultsFromCSV(self):
[966]250        """load Fulltime Studentdata from CSV values into pumeresults catalog"""
251        import transaction
252        import random
253        from pdb import set_trace
254        csv_d = {'jamb_reg_no': "RegNumber",
255                 'status': "Admission Status",
256                 'name': "Name",
257                 'score': "Score",
258                 'sex': "Sex",
259                 'faculty': "Faculty",
260                 'department': "Dept",
261                 'course': "Course",
262                 'course_code_org': "Course Code",
263                 }
264        csv_fields = [f[1] for f in csv_d.items()]
265        tr_count = 0
266        total = 0
[971]267        #name = 'pup_new'
268        name = 'pup_update'
269        update = name.endswith('update')
[966]270        no_import = []
[1005]271        s = ','.join(['"%s"' % fn for fn in csv_fields])
[966]272        no_import.append('%s' % s)
[1005]273        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
274        no_import_name = "%s/import/%s_not_imported_%s.csv" % (i_home,name,current)
275        open(no_import_name,"w").write('\n'.join(no_import))
[966]276        no_import = []
277        logger = logging.getLogger('%s_import' % name)
278        starttime = DateTime.now()
279        logger.info('Start loading from %s.csv' % name)
280        try:
281            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
282        except:
283            logger.error('Error reading %s.csv' % name)
284            return
285        pume = self.portal_pumeresults
286        format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
[975]287        eduplicate = '"dupplicate",%s' % format
[1005]288        added = 'added ,%s' % format
[966]289        for jamb in result:
290            dict = {}
291            #set_trace()
292            for f,fn in csv_d.items():
293                dict[f] = jamb.get(csv_d[f])
[971]294            res = pume(jamb_reg_no=jamb.get(csv_d['jamb_reg_no']))
295            if len(res) > 0:
296                if update:
[1005]297                    try:
298                        pume.modifyRecord(**dict)
299                    except ValueError:
300                        logger.info(eduplicate % jamb)
301                        continue
302                    except KeyError:
303                        pume.addRecord(**dict)
304                        logger.info(added % jamb)
305                        continue
[971]306                else:
307                    data = res[0]
308                    if data.name != jamb.get(csv_d['name']):
309                        #set_trace()
310                        logger.info(eduplicate % jamb)
311                        #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
312                        #logger.info(em)
313                        dd = {}
314                        for f,fn in csv_d.items():
315                            dd[fn] = getattr(data,f)
316                        no_import.append(eduplicate % dd)
317                        no_import.append(eduplicate % jamb)
318                    continue
[966]319            try:
320                pume.addRecord(**dict)
321            except ValueError:
322                logger.info(eduplicate % jamb)
323                #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
324                #logger.info(em)
325                no_import.append(eduplicate % jamb)
326        logger.info('End loading from %s.csv' % name)
327        if len(no_import) > 1:
[1005]328            open(no_import_name,"w+").write('\n'.join(no_import))
[966]329        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[971]330    ###)
[966]331
332    security.declareProtected(ModifyPortalContent,"createNewStudents")###(
333    def createNewStudents(self):
[742]334        """load Fulltime Studentdata from CSV values"""
335        import transaction
336        import random
[971]337        #from pdb import set_trace
[763]338        wftool = self.portal_workflow
[757]339        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
[971]340        csv_d = {'jamb_reg_no': "RegNumber",
[958]341                 'jamb_lastname': "Name",
[971]342                 'session': "Session",
343                 'pume_tot_score': "PUME SCORE",
344                 'jamb_score': "JambScore",
[958]345                 'jamb_sex': "Sex",
[971]346                 'jamb_state': "State",
[980]347##                 'jamb_first_cos': "AdminCourse",
[971]348                 'faculty': "AdminFaculty",
349                 'course_code': "AdmitCoscode",
350                 'stud_status':"AdmitStatus",
351                 'department': "AdmitDept",
352                 'jamb_lga': "LGA",
353                 'app_email': "email",
[980]354                 'app_mobile': "PhoneNumbers",
[958]355                 }
356        csv_fields = [f[1] for f in csv_d.items()]
357        tr_count = 0
[961]358        total = 0
[958]359        #name = 'pume_results'
[971]360        name = 'Admitted'
[958]361        no_import = []
362        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
[971]363        no_import.append('"Error",%s' % s)
364        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
365        no_certificate = "no certificate %s" % format
[966]366        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
367                    '\n'.join(no_import))
[958]368        logger = logging.getLogger('%s_import' % name)
369        logger.info('Start loading from %s.csv' % name)
[971]370        l = self.portal_catalog({'meta_type': "Certificate"})
371        certs = {}
372        cert_docs = {}
373        for f in l:
374            certs[f.getId] = f.getObject().getContent()
[958]375        try:
376            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
377        except:
378            logger.error('Error reading %s.csv' % name)
379            return
380        for jamb in result:
[971]381            jamb['Error'] = "Processing "
382            logger.info(format % jamb)
[958]383            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
384            res = self.portal_catalog({'portal_type': "StudentApplication",
[959]385                                     'SearchableText': jamb_reg_no })
[958]386            if res:
[980]387                em = 'Student with RegNo %s already exists\n' % jamb_reg_no
[958]388                logger.info(em)
[971]389                jamb['Error'] = "Student exists"
[958]390                no_import.append(format % jamb)
391                continue
[971]392            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
393            if cert_id not in certs.keys():
[958]394                em = 'No Certificate with ID %s \n' % cert_id
395                logger.info(em)
[971]396                jamb['Error'] = "No Certificate %s" % cert_id
397                no_import.append( format % jamb)
[958]398                continue
[971]399            cert_doc = certs[cert_id]
400            catalog_entry = {}
401            catalog_entry['jamb_reg_no'] = jamb_reg_no
[958]402            jamb_name = jamb.get(csv_d['jamb_lastname'])
403            jamb_name.replace('>','')
[966]404            jamb_name.replace('<','')
[958]405            names = jamb_name.split()
406            letter = names[-1][0].upper()
407            sid = self.generateStudentId(letter)
408            not_created = True
409            while not_created:
410                try:
411                    students_folder.invokeFactory('Student', sid)
412                    not_created = False
413                except BadRequest:
414                    sid = self.generateStudentId(letter)
[971]415            catalog_entry['id'] = sid
[958]416            tr_count += 1
[961]417            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[958]418            student = getattr(self,sid)
419            student.manage_setLocalRoles(sid, ['Owner',])
420            student.invokeFactory('StudentPume','pume')
421            dp = {'Title': 'Pume Data'}
422            student.invokeFactory('StudentApplication','application')
423            da = {'Title': 'Application Data'}
424            da["jamb_lastname"] = jamb_name
425            da_fields = ('jamb_reg_no',
426                         'jamb_sex',
427                         #'jamb_state',
[966]428                         'jamb_score',
[980]429##                         'jamb_first_cos',
[958]430                         'jamb_sex',
[971]431                         'jamb_state',
432                         'jamb_lga',
433                         'app_email',
[980]434                         'app_mobile',
[958]435                         )
436            for f in da_fields:
437                da[f] = jamb.get(csv_d[f])
[971]438            catalog_entry['email'] = jamb.get(csv_d['app_email'])
[958]439            app = student.application
[971]440            app_doc = app.getContent()
[975]441            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
[971]442            #import pdb;pdb.set_trace()
443            if os.path.exists(picture):
444                file = open(picture)
[974]445                if False:
446                    img = PIL.Image.open(file)
447                    img.thumbnail((150,200),
448                                  resample=PIL.Image.ANTIALIAS)
449                    # We now need a buffer to write to. It can't be the same
450                    # as the inbuffer as the PNG writer will write over itself.
451                    outfile = StringIO()
452                    img.save(outfile, format=img.format)
453                else:
454                    outfile = file.read()
[971]455                app_doc.manage_addFile('passport',
456                                       file=outfile,
457                                       title="%s.jpg" % jamb_reg_no)
[958]458            app.getContent().edit(mapping=da)
459            app.manage_setLocalRoles(sid, ['Owner',])
460            #wftool.doActionFor(app,'close')
461            dp_fields = (
462                         #'pume_eng_score',
463                         #'pume_gen_score',
464                         'pume_tot_score',
465                         )
[964]466            dp['pume_tot_score'] = jamb.get(csv_d['pume_tot_score']) or "No Option Shaded"
[958]467            pume = student.pume
468            pume.getContent().edit(mapping=dp)
469            #wftool.doActionFor(pume,'close')
470            pume.manage_setLocalRoles(sid, ['Owner',])
[966]471            #student.getContent().createSubObjects()
[975]472            dp = {}
[966]473            if len(names) == 3:
474                dp['firstname'] = names[0].capitalize()
475                dp['middlename'] = names[1].capitalize()
476                dp['lastname'] = names[2].capitalize()
477            elif len(names) == 2:
478                dp['firstname'] = names[0].capitalize()
[971]479                dp['middlename'] = ''
[966]480                dp['lastname'] = names[1].capitalize()
481            else:
[971]482                dp['firstname'] = ''
483                dp['middlename'] = ''
[966]484                dp['lastname'] = jamb_name
485            dp['sex'] = jamb.get(csv_d['jamb_sex']) == 'F'
[971]486            catalog_entry['sex'] = dp['sex']
487            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
[966]488            student.invokeFactory('StudentPersonal','personal')
489            per = student.personal
490            per_doc = per.getContent()
491            per_doc.edit(mapping = dp)
492            per.manage_setLocalRoles(sid, ['Owner',])
[958]493            if jamb.get(csv_d['stud_status']) == "Admitted":
494                wftool.doActionFor(student,'pume_pass')
495                wftool.doActionFor(student,'admit')
496            else:
497                wftool.doActionFor(student,'pume_fail')
498                wftool.doActionFor(student,'reject_admission')
499                continue
[964]500            #
[966]501            # Clearance
502            #
503            student.invokeFactory('StudentClearance','clearance')
504            #wftool.doActionFor(student.clearance,'open')
505            dp = {'Title': 'Clearance/Eligibility Record'}
506            student.clearance.manage_setLocalRoles(sid, ['Owner',])
507            #
[964]508            # Study Course
509            #
[958]510            student.invokeFactory('StudentStudyCourse','study_course')
511            study_course = student.study_course
512            dsc = {}
513            from_certificate = ['title',
514                               'max_elect',
515                               'max_pass',
516                               'n_core',
517                               'nr_years',
518                               'probation_credits',
519                               'promotion_credits',
520                               'start_level',
521                              ]
522            for f in from_certificate:
523                dsc[f] = getattr(cert_doc,f)
[971]524            dsc['faculty'] = jamb.get(csv_d['faculty'])
525            dsc['department'] = jamb.get(csv_d['department'])
526            catalog_entry['faculty'] = jamb.get(csv_d['faculty'])
527            catalog_entry['department'] = jamb.get(csv_d['department'])
528            catalog_entry['course'] = cert_id
529            catalog_entry['level'] = getattr(cert_doc,'start_level')
[958]530            dsc['study_course'] = cert_id
[971]531            dsc['entry_session'] = jamb.get(csv_d['session'])
[958]532            study_course.getContent().edit(mapping=dsc)
[971]533            self.students_catalog.addRecord(**catalog_entry)
[981]534            if tr_count > MAX_TRANS:
[966]535                if len(no_import) > 1:
536                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
537                             '\n'.join(no_import))
538                    no_import = []
[961]539                em = '%d transactions commited\n' % tr_count
[958]540                transaction.commit()
541                logger.info(em)
[961]542                total += tr_count
[958]543                tr_count = 0
544        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
545    ###)
546
[1065]547    security.declareProtected(ModifyPortalContent,"updateStudyCourse")###(
548    def updateStudyCourse(self):
549        """update StudyCourse from CSV values"""
550        import transaction
551        import random
552        from pdb import set_trace
553        wftool = self.portal_workflow
554        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
555        csv_d = {'jamb_reg_no': "RegNumber",
556                 'jamb_lastname': "Name",
557                 'session': "Session",
558                 'pume_tot_score': "PUME SCORE",
559                 'jamb_score': "JambScore",
560                 'jamb_sex': "Sex",
561                 'jamb_state': "State",
562##                 'jamb_first_cos': "AdminCourse",
563                 'faculty': "AdminFaculty",
564                 'course_code': "AdmitCoscode",
565                 'stud_status':"AdmitStatus",
566                 'department': "AdmitDept",
567                 'jamb_lga': "LGA",
568                 'app_email': "email",
569                 'app_mobile': "PhoneNumbers",
570                 }
571        csv_fields = [f[1] for f in csv_d.items()]
572        tr_count = 0
573        total = 0
574        #name = 'pume_results'
575        name = 'StudyCourseChange'
576        no_import = []
577        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
578        no_import.append('"Error",%s' % s)
579        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
580        no_certificate = "no certificate %s" % format
581        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
582                    '\n'.join(no_import))
583        logger = logging.getLogger('%s_import' % name)
584        logger.info('Start loading from %s.csv' % name)
585        l = self.portal_catalog({'meta_type': "Certificate"})
586        try:
587            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
588        except:
589            logger.error('Error reading %s.csv' % name)
590            return
591        for jamb in result:
592            jamb['Error'] = "Processing "
593            logger.info(format % jamb)
594            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
595            res = self.portal_catalog({'portal_type': "StudentApplication",
596                                     'SearchableText': jamb_reg_no })
597            if not res:
598                em = 'Student with RegNo %s does not exists\n' % jamb_reg_no
599                logger.info(em)
600                jamb['Error'] = "Student not exists"
601                no_import.append(format % jamb)
602                continue
603            sid = res[0].getPath().split('/')[-2]
604            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
605            res = self.portal_catalog(portal_type = "Certificate", id = cert_id)
606            if not res:
607                em = 'No Certificate with ID %s \n' % cert_id
608                logger.info(em)
609                jamb['Error'] = "No Certificate %s" % cert_id
610                no_import.append( format % jamb)
611                continue
612            cert_brain = res[0]
613            catalog_entry = {}
614            student = getattr(self,sid)
615            #
616            # Study Course
617            #
618            study_course = student.study_course
619            dsc = {}
620            cert_pl = cert_brain.getPath().split('/')
621            catalog_entry['id'] = sid
622            catalog_entry['faculty'] = cert_pl[-4]
623            catalog_entry['department'] = cert_pl[-3]
624            catalog_entry['course'] = cert_id
625            dsc['study_course'] = cert_id
626            study_course.getContent().edit(mapping=dsc)
627            self.students_catalog.modifyRecord(**catalog_entry)
628            if tr_count > 10:
629                if len(no_import) > 1:
630                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
631                             '\n'.join(no_import))
632                    no_import = []
633                em = '%d transactions commited\n' % tr_count
634                transaction.commit()
635                logger.info(em)
636                total += tr_count
637                tr_count = 0
638            tr_count += 1
639        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
640    ###)
641
[958]642    security.declareProtected(ModifyPortalContent,"OLDloadPumeResultsFromCSV")###(
643    def OLDloadPumeResultsFromCSV(self):
644        """load Fulltime Studentdata from CSV values"""
645        import transaction
646        import random
647        wftool = self.portal_workflow
648        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
649        csv_d = {'jamb_reg_no': "JAMBRegno",
650                 'jamb_lastname': "Name",
[757]651                 'pume_options': "Options",
652                 'session': "Session",
653                 'days': "Days",
654                 'response': "Responce",
655                 'wrong': "Wrong",
656                 'pume_eng_score': "EngScore",
[775]657                 'pume_gen_score': "GenScore",
[958]658                 'pume_tot_score': "Score",
[757]659                 'batch': "Batch",
660                 'serial': "SerialNo",
661                 'jamb_score': "JambScore",
662                 'omitted':"Omitted",
663                 'search_key': "SearchKey",
664                 'jamb_sex': "Sex",
665                 'fac1': "Fac1",
666                 'fac2': "Fac2",
667                 'jamb_first_cos': "CourseofStudy",
668                 'stud_status':"StudStatus",
669                 'registered': "Registered",
670                 'jamb_state': "State",
671                 'eng_fail': "EngFail",
672                 'gen_fail': "GenFail",
673                 'un_ans_eng': "UnAnsEng",
674                 'un_ans_eng': "UnAnsGen",
675                 'total_ans': "TotalUnAns",
676                 'dept': "Dept",
677                 'jamb_second_cos': "Course2",
678                 'jamb_third_cos': "course3",
679                 }
680        csv_fields = [f[1] for f in csv_d.items()]
[742]681        tr_count = 0
682        name = 'pume_results'
[757]683        no_import = []
684        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
685        no_import.append('%s\n' % s)
[742]686        logger = logging.getLogger('%s_import' % name)
687        logger.info('Start loading from %s.csv' % name)
688        try:
[757]689            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[742]690        except:
691            logger.error('Error reading %s.csv' % name)
692            return
[757]693        for jamb in result:
694            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
695            processing = "processing %s" % format
696            logger.info(processing % jamb)
697            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
[763]698            #import pdb;pdb.set_trace()
699            res = self.portal_catalog({'portal_type': "StudentApplication",
[757]700                                     'jamb_reg_no': jamb_reg_no })
701            if res:
702                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
[742]703                logger.info(em)
[757]704                no_import.append(em)
705                no_import.append(format % jamb)
[742]706                continue
[785]707            cert_id = jamb.get(csv_d['jamb_first_cos']).upper()
708            res = self.portal_catalog({'portal_type': "Certificate",
709                                     'id': cert_id })
710            if len(res) < 1:
711                em = 'No Certificate with ID %s \n' % cert_id
712                logger.info(em)
713                no_import.append(em)
714                no_import.append(format % jamb)
715                continue
716            cert = res[0].getObject()
717            cert_path = res[0].getPath()
718            cert_doc = cert.getContent()
[757]719            jamb_name = jamb.get(csv_d['jamb_lastname'])
720            jamb_name.replace('>','')
721            names = jamb_name.split()
722            letter = names[-1][0].upper()
723            sid = self.generateStudentId(letter)
724            not_created = True
725            while not_created:
726                try:
727                    students_folder.invokeFactory('Student', sid)
728                    not_created = False
729                except BadRequest:
730                    sid = self.generateStudentId(letter)
731            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
732            student = getattr(self,sid)
733            student.manage_setLocalRoles(sid, ['Owner',])
[766]734            student.invokeFactory('StudentClearance','clearance')
[775]735            #wftool.doActionFor(student.clearance,'open')
[840]736            dp = {'Title': 'Clearance/Eligibility Record'}
[766]737            student.clearance.manage_setLocalRoles(sid, ['Owner',])
[763]738            student.invokeFactory('StudentPume','pume')
739            dp = {'Title': 'Pume Data'}
[757]740            student.invokeFactory('StudentApplication','application')
741            da = {'Title': 'Application Data'}
742            da["jamb_lastname"] = jamb_name
743            da_fields = ('jamb_reg_no',
744                         'jamb_sex',
745                         'jamb_state',
746                         'jamb_score',
747                         'jamb_first_cos',
748                         'jamb_sex',
749                         'jamb_state',
750                         'jamb_first_cos',
751                         'jamb_second_cos',
752                         )
[763]753            for f in da_fields:
754                da[f] = jamb.get(csv_d[f])
[757]755            app = student.application
[763]756            app.getContent().edit(mapping=da)
[757]757            app.manage_setLocalRoles(sid, ['Owner',])
[780]758            #wftool.doActionFor(app,'close')
[763]759            dp_fields = (
760                         'pume_eng_score',
[764]761                         'pume_gen_score',
[763]762                         'pume_tot_score',
763                         )
764            for f in dp_fields:
[775]765                dp[f] = float(jamb.get(csv_d[f]))
[765]766            pume = student.pume
767            pume.getContent().edit(mapping=dp)
[780]768            #wftool.doActionFor(pume,'close')
[763]769            pume.manage_setLocalRoles(sid, ['Owner',])
[785]770            #
771            # Study Course
772            #
773            student.invokeFactory('StudentStudyCourse','study_course')
774            study_course = student.study_course
775            dsc = {}
776            from_certificate = ['title',
777                               'max_elect',
778                               'max_pass',
779                               'n_core',
780                               'nr_years',
781                               'probation_credits',
782                               'promotion_credits',
783                               'start_level',
784                              ]
785            for f in from_certificate:
786                dsc[f] = getattr(cert_doc,f)
787            cpl = cert_path.split('/')
788            dsc['faculty'] = cpl[-4]
789            dsc['department'] = cpl[-3]
790            dsc['study_course'] = cert_id
791            dsc['entry_session'] = jamb.get(csv_d['session'])
792            study_course.getContent().edit(mapping=dsc)
[757]793            student.getContent().createSubObjects()
[775]794            if dp['pume_tot_score']>49:
[780]795                wftool.doActionFor(student,'pume_pass')
[785]796                wftool.doActionFor(student,'admit')
[775]797            else:
[780]798                wftool.doActionFor(student,'pume_fail')
[790]799                wftool.doActionFor(student,'reject_admission')
[757]800            if len(no_import) > 1:
801                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
802                     '\n'.join(no_import))
[742]803        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
804    ###)
805
[398]806    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
[396]807    def loadFullTimeStudentsResultsFromCSV(self):
808        """load Fulltime Studentdata from CSV values"""
809        #return
[723]810        level_wf_actions = {}
811        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
812        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
[727]813        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
814        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
[398]815        import transaction
[723]816        wftool = self.portal_workflow
[398]817        tr_count = 0
818        name = 'short_full_time_results_2004_2005'
[396]819        no_import = False
820        if not no_import:
821            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
822            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
823        logger = logging.getLogger('%s_import' % name)
824        logger.info('Start loading from %s.csv' % name)
825        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
826        try:
827            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
828        except:
829            logger.error('Error reading %s.csv' % name)
830            return
[398]831        l = self.portal_catalog({'meta_type': "Course"})
832        courses = {}
833        for c in l:
834            courses[c.id] = c.getObject()
[723]835        level_changed = False
836        student_changed = False
837        sid = ''
838        #import pdb;pdb.set_trace()
[396]839        for result in results:
[723]840            temp_sid = result.get('Matnumber')
841            if temp_sid != sid:
842                student_changed = True
843                res = self.portal_catalog({'meta_type': "StudentClearance",
844                                         'SearchableText': temp_sid })
845                if not res:
846                    em = 'Student with ID %(Matnumber)s not found\n' % result
847                    logger.info(em)
848                    no_import.write(em)
849                    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)
850                    continue
851                elif len(res) > 1:
852                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
853                    logger.info(em)
854                    no_import.write(em)
855                    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)
856                    continue
857                sid = temp_sid
858                sf = res[0].getObject().aq_parent
859                sc = getattr(sf,'study_course')
860                level = ''
861            else:
862                student_changed = False
[398]863            course = result.get('CosCode')
864            if course not in courses.keys():
865                em = 'Course with ID %(CosCode)s not found\n' % result
[396]866                logger.info(em)
867                no_import.write(em)
[398]868                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]869                continue
[727]870            course_doc = courses[course].getContent()
[723]871            temp_level = result.get('Level')
[742]872            student_id = sf.getId()
873            result['StudentId'] = student_id
[723]874            if temp_level != level:
875                try:
876                    int(temp_level)
877                except:
878                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
879                    logger.info(em)
880                    no_import.write(em)
881                    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)
882                    continue
[727]883                level_changed = True
884                if 'dlev' in vars().keys():
[723]885                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
886                level = temp_level
887                l = getattr(sc,level,None)
888                if l is None:
889                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
890                    sc.invokeFactory('StudentStudyLevel', level)
891                    l = getattr(sc, level)
[742]892                    l.manage_setLocalRoles(student_id, ['Owner',])
[723]893            else:
894                level_changed = False
895            cr = getattr(l,course,None)
896            if cr is None:
897                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
898                l.invokeFactory('StudentCourseResult',course)
899            cr = getattr(l,course)
900            dcr = {}
[727]901            from_course = ['title',
902                           'credits',
903                           'passmark',
904                           ]
905            for f in from_course:
906                dcr[f] = getattr(course_doc,f)
[454]907            dlev = {}
[723]908            dcr['ansbook'] = result.get('Ansbook')
909            dcr['semester'] = getInt(result.get('Semster'))
910            dcr['status'] = result.get('CosStuatus')
911            dcr['score'] = getInt(result.get('Score'))
[454]912            dlev['session'] = result.get('Session')
[723]913            dcr['carry_level'] = result.get('CarryLevel')
914            dcr['grade'] = result.get('Grade')
[725]915            dcr['weight'] = result.get('Weight')
[454]916            dlev['verdict'] = result.get('Verdict')
[725]917            dcr['import_id'] = result.get('id')
918            gpa = result.get('GPA').replace(',','.')
919            dlev['imported_gpa'] = getFloat(gpa)
[723]920            cr.getContent().edit(mapping = dcr)
[742]921            cr.manage_setLocalRoles(student_id, ['Owner',])
[454]922            l.getContent().edit(mapping = dlev)
[398]923            if tr_count > MAX_TRANS:
924                transaction.commit()
925                tr_count = 0
926            tr_count += 1
[723]927            wftool.doActionFor(cr,'close')
928        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
[681]929        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[426]930
[398]931###)
[396]932
[457]933    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
934    def loadJAMBFromCSV(self):
935        """load JAMB data from CSV values"""
936        #return
937        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
938        import transaction
939        tr_count = 0
[572]940        name = 'SampleJAMBDataII'
[511]941        wftool = self.portal_workflow
[457]942        no_import = False
943        if not no_import:
944            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
945            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')
946        logger = logging.getLogger('%s_import' % name)
947        logger.info('Start loading from %s.csv' % name)
948        try:
949            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
950        except:
951            logger.error('Error reading %s.csv' % name)
952            return
953        for jamb in result:
954            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)
955            jamb_reg_no = jamb.get('REG-NO')
[472]956            res = self.portal_catalog({'meta_type': "StudentApplication",
[457]957                                     'jamb_reg_no': jamb_reg_no })
958            if res:
959                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
960                logger.info(em)
961                no_import.write(em)
962                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)
963                continue
[511]964            jamb_name = jamb.get("NAME")
[584]965            jamb_name.replace('>','')
[511]966            names = jamb_name.split()
967            letter = names[-1][0].upper()
[714]968            sid = self.generateStudentId(letter)
[457]969            not_created = True
970            while not_created:
971                try:
972                    students_folder.invokeFactory('Student', sid)
973                    not_created = False
974                except BadRequest:
[714]975                    sid = self.generateStudentId(letter)
[457]976            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[511]977            student = getattr(self,sid)
[519]978            student.manage_setLocalRoles(sid, ['Owner',])
[511]979            student.invokeFactory('StudentApplication','application')
[472]980            da = {'Title': 'Application Data'}
[457]981            da["jamb_reg_no"] = jamb.get("REG-NO")
[511]982            da["jamb_lastname"] = jamb_name
[457]983            da["jamb_sex"] = jamb.get("SEX")
984            da["jamb_state"] = jamb.get("STATE")
985            da["jamb_lga"] = jamb.get("LGA")
986            da["jamb_score"] = jamb.get("AGGREGATE")
987            da["jamb_first_cos"] = jamb.get("COURSE1")
988            da["jamb_second_cos"] = jamb.get("COURSE2")
989            da["jamb_first_uni"] = jamb.get("UNIV1")
990            da["jamb_second_uni"] = jamb.get("UNIV2")
[511]991            app = student.application
992            app_doc = app.getContent()
993            app_doc.edit(mapping=da)
[658]994            #wftool.doActionFor(app,'open',dest_container=app)
[511]995            app.manage_setLocalRoles(sid, ['Owner',])
996            student.getContent().createSubObjects()
[457]997        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
998    ###)
[426]999
[472]1000
[511]1001    security.declareProtected(View,"fixOwnership")
1002    def fixOwnership(self):
1003        """fix Ownership"""
1004        for s in self.portal_catalog(meta_type = 'Student'):
1005            student = s.getObject()
1006            sid = s.getId
1007            import pdb;pdb.set_trace()
1008            student.application.manage_setLocalRoles(sid, ['Owner',])
1009            student.personal.manage_setLocalRoles(sid, ['Owner',])
[603]1010
[364]1011    security.declareProtected(View,"Title")
1012    def Title(self):
1013        """compose title"""
[382]1014        return "Student Section"
[361]1015
[714]1016    def generateStudentId(self,letter): ###(
1017        import random
1018        r = random
1019        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
1020            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
1021        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
1022        sid = "%c%d" % (letter,r.randint(99999,1000000))
1023        while hasattr(students, sid):
1024            sid = "%c%d" % (letter,r.randint(99999,1000000))
[758]1025        return sid
[714]1026        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
1027    ###)
1028
[361]1029InitializeClass(StudentsFolder)
1030
1031def addStudentsFolder(container, id, REQUEST=None, **kw):
1032    """Add a Student."""
1033    ob = StudentsFolder(id, **kw)
1034    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1035###)
1036
[57]1037class Student(CPSDocument): ###(
1038    """
[154]1039    WAeUP Student container for the various student data
[57]1040    """
1041    meta_type = 'Student'
1042    portal_type = meta_type
1043    security = ClassSecurityInfo()
[154]1044
[152]1045    security.declareProtected(View,"Title")
1046    def Title(self):
1047        """compose title"""
[153]1048        reg_nr = self.getId()[1:]
[362]1049        data = getattr(self,'personal',None)
[152]1050        if data:
1051            content = data.getContent()
1052            return "%s %s" % (content.firstname,content.lastname)
[472]1053        data = getattr(self,'application',None)
[464]1054        if data:
1055            content = data.getContent()
1056            return "%s" % (content.jamb_lastname)
[152]1057        return self.title
[154]1058
[511]1059    security.declarePrivate('makeStudentMember') ###(
1060    def makeStudentMember(self,sid,password='uNsEt'):
1061        """make the student a member"""
1062        membership = self.portal_membership
[603]1063        membership.addMember(sid,
[511]1064                             password ,
1065                             roles=('Member',
1066                                     'Student',
[522]1067                                     ),
[511]1068                             domains='',
[904]1069                             properties = {'memberareaCreationFlag': False,
1070                                           'homeless': True},)
[511]1071        member = membership.getMemberById(sid)
1072        self.portal_registration.afterAdd(member, sid, password, None)
1073        self.manage_setLocalRoles(sid, ['Owner',])
1074
1075###)
1076
[764]1077    security.declareProtected(View,'createSubObjects') ###(
1078    def createSubObjects(self):
1079        """make the student a member"""
1080        dp = {'Title': 'Personal Data'}
1081        app_doc = self.application.getContent()
1082        names = app_doc.jamb_lastname.split()
1083        if len(names) == 3:
1084            dp['firstname'] = names[0].capitalize()
1085            dp['middlename'] = names[1].capitalize()
1086            dp['lastname'] = names[2].capitalize()
1087        elif len(names) == 2:
1088            dp['firstname'] = names[0].capitalize()
1089            dp['lastname'] = names[1].capitalize()
1090        else:
1091            dp['lastname'] = app_doc.jamb_lastname
1092        dp['sex'] = app_doc.jamb_sex == 'F'
1093        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
1094        proxy = self.aq_parent
1095        proxy.invokeFactory('StudentPersonal','personal')
1096        per = proxy.personal
1097        per_doc = per.getContent()
1098        per_doc.edit(mapping = dp)
[927]1099        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
[764]1100        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]1101
[511]1102###)
1103
[57]1104InitializeClass(Student)
1105
1106def addStudent(container, id, REQUEST=None, **kw):
1107    """Add a Student."""
1108    ob = Student(id, **kw)
1109    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1110
1111###)
[91]1112
[639]1113class StudentAccommodation(CPSDocument): ###(
1114    """
1115    WAeUP Student container for the various student data
1116    """
1117    meta_type = 'StudentAccommodation'
1118    portal_type = meta_type
1119    security = ClassSecurityInfo()
1120
1121    security.declareProtected(View,"Title")
1122    def Title(self):
1123        """compose title"""
1124        content = self.getContent()
1125        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
1126        return "Accommodation Data for Session %s" % content.session
1127
1128
1129InitializeClass(StudentAccommodation)
1130
1131def addStudentAccommodation(container, id, REQUEST=None, **kw):
1132    """Add a Students personal data."""
1133    ob = StudentAccommodation(id, **kw)
1134    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1135
1136###)
1137
[89]1138class StudentPersonal(CPSDocument): ###(
1139    """
[154]1140    WAeUP Student container for the various student data
[89]1141    """
1142    meta_type = 'StudentPersonal'
1143    portal_type = meta_type
1144    security = ClassSecurityInfo()
[152]1145
1146    security.declareProtected(View,"Title")
1147    def Title(self):
1148        """compose title"""
1149        content = self.getContent()
[364]1150        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
1151        return "Personal Data"
[152]1152
[154]1153
[89]1154InitializeClass(StudentPersonal)
1155
1156def addStudentPersonal(container, id, REQUEST=None, **kw):
1157    """Add a Students personal data."""
1158    ob = StudentPersonal(id, **kw)
1159    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1160
1161###)
1162
[423]1163class StudentClearance(CPSDocument): ###(
1164    """
1165    WAeUP Student container for the various student data
1166    """
1167    meta_type = 'StudentClearance'
1168    portal_type = meta_type
1169    security = ClassSecurityInfo()
1170
1171    security.declareProtected(View,"Title")
1172    def Title(self):
1173        """compose title"""
1174        content = self.getContent()
[840]1175        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
1176        return "Clearance/Eligibility Record"
[423]1177
1178
1179InitializeClass(StudentClearance)
1180
1181def addStudentClearance(container, id, REQUEST=None, **kw):
1182    """Add a Students personal data."""
1183    ob = StudentClearance(id, **kw)
1184    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1185
1186###)
1187
[454]1188class StudentStudyLevel(CPSDocument): ###(
1189    """
1190    WAeUP Student container for the various student data
1191    """
1192    meta_type = 'StudentStudyLevel'
1193    portal_type = meta_type
1194    security = ClassSecurityInfo()
1195
1196    security.declareProtected(View,"Title")
1197    def Title(self):
1198        """compose title"""
1199        return "Level %s" % self.aq_parent.getId()
1200
[723]1201##    security.declarePublic("gpa")
1202##    def gpa(self):
1203##        """calculate the gpa"""
1204##        sum = 0
1205##        course_count = 0
1206##        for sc in self.objectValues():
1207##            result = sc.getContent()
1208##            if not result.grade:
1209##                continue
1210##            res = self.portal_catalog({'meta_type': 'Course',
1211##                                          'id': sc.aq_parent.id})
1212##            if len(res) != 1:
1213##                continue
1214##            course = res[0].getObject().getContent()
1215##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
1216##            course_count += 1
1217##        if course_count:
1218##            return sum/course_count
1219##        return 0.0
[472]1220
[454]1221InitializeClass(StudentStudyLevel)
1222
1223def addStudentStudyLevel(container, id, REQUEST=None, **kw):
1224    """Add a Students personal data."""
1225    ob = StudentStudyLevel(id, **kw)
1226    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1227
1228###)
1229
[362]1230class StudentStudyCourse(CPSDocument): ###(
1231    """
1232    WAeUP Student container for the various student data
1233    """
1234    meta_type = 'StudentStudyCourse'
1235    portal_type = meta_type
1236    security = ClassSecurityInfo()
1237
[364]1238    security.declareProtected(View,"Title")
1239    def Title(self):
1240        """compose title"""
1241        content = self.getContent()
[453]1242        return "Study Course"
[362]1243
1244
1245InitializeClass(StudentStudyCourse)
1246
1247def addStudentStudyCourse(container, id, REQUEST=None, **kw):
1248    """Add a Students personal data."""
1249    ob = StudentStudyCourse(id, **kw)
1250    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1251
1252###)
1253
[472]1254class StudentApplication(CPSDocument): ###(
[179]1255    """
1256    WAeUP Student container for the various student data
1257    """
[472]1258    meta_type = 'StudentApplication'
[179]1259    portal_type = meta_type
1260    security = ClassSecurityInfo()
1261
[181]1262    security.declareProtected(View,"Title")
1263    def Title(self):
1264        """compose title"""
[472]1265        return "Application Data"
[179]1266
[181]1267
[472]1268InitializeClass(StudentApplication)
[179]1269
[472]1270def addStudentApplication(container, id, REQUEST=None, **kw):
[179]1271    """Add a Students eligibility data."""
[472]1272    ob = StudentApplication(id, **kw)
[179]1273    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]1274###)
[179]1275
[758]1276
1277class StudentPume(CPSDocument): ###(
1278    """
1279    WAeUP Student container for the various student data
1280    """
1281    meta_type = 'StudentPume'
1282    portal_type = meta_type
1283    security = ClassSecurityInfo()
1284
1285    security.declareProtected(View,"Title")
1286    def Title(self):
1287        """compose title"""
1288        return "PUME Results"
1289
1290
1291InitializeClass(StudentPume)
1292
1293def addStudentPume(container, id, REQUEST=None, **kw):
1294    """Add a Students PUME data."""
1295    ob = StudentPume(id, **kw)
1296    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[179]1297###)
[181]1298
[565]1299##class StudentSemester(CPSDocument): ###(
1300##    """
1301##    WAeUP StudentSemester containing the courses and students
1302##    """
1303##    meta_type = 'StudentSemester'
1304##    portal_type = meta_type
1305##    security = ClassSecurityInfo()
1306##
1307##InitializeClass(StudentSemester)
1308##
1309##def addStudentSemester(container, id, REQUEST=None, **kw):
1310##    """Add a StudentSemester."""
1311##    ob = StudentSemester(id, **kw)
1312##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1313##
1314#####)
[464]1315
[758]1316##class Semester(CPSDocument): ###(
1317##    """
1318##    WAeUP Semester containing the courses and students
1319##    """
1320##    meta_type = 'Semester'
1321##    portal_type = meta_type
1322##    security = ClassSecurityInfo()
1323##
1324##InitializeClass(Semester)
1325##
1326##def addSemester(container, id, REQUEST=None, **kw):
1327##    """Add a Semester."""
1328##    ob = Semester(id, **kw)
1329##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1330##
1331#####)
[464]1332
1333class StudentCourseResult(CPSDocument): ###(
[89]1334    """
[464]1335    WAeUP StudentCourseResult
[89]1336    """
[464]1337    meta_type = 'StudentCourseResult'
[89]1338    portal_type = meta_type
1339    security = ClassSecurityInfo()
[472]1340
[454]1341    def getCourseEntry(self,cid):
[723]1342        res = self.portal_catalog({'meta_type': "Course",
[454]1343                                           'id': cid})
1344        if res:
1345            return res[-1]
1346        else:
1347            return None
[154]1348
[454]1349    security.declareProtected(View,"Title")
1350    def Title(self):
1351        """compose title"""
[723]1352        cid = self.aq_parent.getId()
[454]1353        ce = self.getCourseEntry(cid)
1354        if ce:
1355            return "%s" % ce.Title
1356        return "No course with id %s" % cid
[152]1357
[464]1358InitializeClass(StudentCourseResult)
[454]1359
[464]1360def addStudentCourseResult(container, id, REQUEST=None, **kw):
1361    """Add a StudentCourseResult."""
1362    ob = StudentCourseResult(id, **kw)
[89]1363    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]1364###)
1365
[579]1366# Backward Compatibility StudyLevel
1367
1368from Products.WAeUP_SRP.Academics import StudyLevel
1369
1370from Products.WAeUP_SRP.Academics import addStudyLevel
1371
Note: See TracBrowser for help on using the repository browser.