source: WAeUP_SRP/trunk/Students.py @ 1251

Last change on this file since 1251 was 1168, checked in by joachim, 18 years ago

convert all matric_no to uppercase, check for existing records in catalog

  • Property svn:keywords set to Id
File size: 77.3 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 1168 2007-01-01 16:05:02Z 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
[1111]64def checkJambNo(jnr):
65    try:
66        if len(jnr) != 10:
67            return False
68    except:
69        return False
70    try:
71        int(jnr[:8])
72        return True
73    except:
74        return False
[1119]75
[361]76class StudentsFolder(CPSDocument): ###(
77    """
78    WAeUP container for the various WAeUP containers data
79    """
[362]80    meta_type = 'StudentsFolder'
[361]81    portal_type = meta_type
82    security = ClassSecurityInfo()
[154]83
[361]84    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsFromCSV")###(
85    def loadFullTimeStudentsFromCSV(self):
86        """load Fulltime Studentdata from CSV values"""
[398]87        import transaction
[708]88        import random
[398]89        tr_count = 0
[361]90        name = 'short_full_time'
91        no_import = False
[395]92        if not no_import:
93            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
94            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')
[1082]95        logger = logging.getLogger('Import.%s' % name)
[361]96        logger.info('Start loading from %s.csv' % name)
[708]97        pwlist  = []
98        pwlist.append('"student_id","firstname","middlename","lastname","matric_no","jamb_reg_no","access_code"')
99        pwl_template = Template('"$student_id","$firstname","$middlename","$lastname","$matric_no","$jamb_reg_no","$access_code"')
[361]100        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
101        try:
102            students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
103        except:
104            logger.error('Error reading %s.csv' % name)
105            return
[422]106        l = self.portal_catalog({'meta_type': "StudentClearance",})
107        matrics = []
[361]108        for s in l:
[422]109            matrics.append(s.getObject().getContent().matric_no)
[423]110        print matrics
[361]111        l = self.portal_catalog({'meta_type': "Certificate"})
112        certs = {}
113        for c in l:
[727]114            ca,ac,fa,dep_id,co,certcode = c.relative_path.split('/')
115            cid = "%(dep_id)s_%(certcode)s" % vars()
116            certs[cid] = c.getObject()
[361]117        for student in students:
[393]118            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]119            sid = student.get('MatricNo')
[396]120            if sid == "":
121                em = 'Empty MatricNo\n'
122                logger.info(em)
123                no_import.write(em)
124                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)
125                continue
[361]126            certcode = makeCertificateCode(student.get('CourseMajor'))
[727]127            dep_id = student.get('Dept')
128            fac_id = student.get('Faculty')
129            cid = "%(dep_id)s_%(certcode)s" % vars()
130            if cid not in certs.keys():
[393]131                em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
[361]132                logger.info(em)
[393]133                no_import.write(em)
134                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]135                continue
[727]136            certificate_doc = certs[cid].getContent()
[395]137            level = student.get('StudentLevel')
[426]138            try:
[395]139                int(level)
140            except:
141                em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
142                logger.info(em)
143                no_import.write(em)
144                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)
145                continue
[422]146            matric_no = student.get('MatricNo')
147            if matric_no not in matrics:
148                matrics.append(matric_no)
[714]149                sid = self.generateStudentId(student.get('Lastname')[0])
[361]150                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
[714]151                students_folder.invokeFactory('Student', sid)
[426]152                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
[714]153                student_obj = getattr(self,sid)
[708]154                access_code = "%d" % random.randint(1000000000,9999999999)
[746]155                student_obj.getContent().makeStudentMember(sid,access_code,)
[708]156                pwl_dict = {'student_id': sid,'access_code':access_code}
[714]157                student_obj.invokeFactory('StudentApplication','application')
158                application = student_obj.application
[472]159                da = {'Title': 'Application Data'}
[714]160                student_obj.invokeFactory('StudentPersonal','personal')
[446]161                da['jamb_reg_no'] = student.get('EntryRegNo')
[714]162                personal = student_obj.personal
[708]163                dp = {'Title': 'Personal Data'}
[714]164                student_obj.invokeFactory('StudentClearance','clearance')
165                clearance = student_obj.clearance
[840]166                dc = {'Title': 'Clearance/Eligibility Record'}
[422]167                dc['matric_no'] = matric_no
[714]168                state = student.get('State')
169                lga = student.get('LGA')
170                if state and lga:
171                    lga =  state + ' / ' + lga
172                else:
173                    lga = "None"
[427]174                dc['lga'] = lga
[422]175                dc['nationality'] = student.get('Nationality')
176                dc['email'] = student.get('Emailaddress')
[708]177                dp['firstname'] = student.get('FirstName')
178                dp['middlename'] = student.get('MiddleName')
179                dp['lastname'] = student.get('Lastname')
180                dp['former_surname'] = student.get('FormerSurname')
181                dp['sex'] = student.get('Sex') == 'F'
182                dp['perm_address'] = student.get('PermanentAddress')
183                dp['perm_city'] = student.get('PermanentAddressCity')
184                dp['campus_address'] = student.get('CampusAddress')
185                dp['phone'] = student.get('PhoneNumber')
[714]186                application.getContent().edit(mapping=da)
187                personal.getContent().edit(mapping=dp)
188                clearance.getContent().edit(mapping=dc)
[362]189                #
190                # Study Course
191                #
[714]192                student_obj.invokeFactory('StudentStudyCourse','study_course')
193                studycourse = student_obj.study_course
[708]194                dsc = {}
[727]195                from_certificate = ['title',
196                                   'max_elect',
197                                   'max_pass',
198                                   'n_core',
199                                   'nr_years',
200                                   'probation_credits',
201                                   'promotion_credits',
202                                   'start_level',
203                                  ]
204                for f in from_certificate:
205                    dsc[f] = getattr(certificate_doc,f)
206                dsc['faculty'] = fac_id
207                dsc['department'] = dep_id
[708]208                dsc['study_course'] = certcode
[454]209                css = student.get('CurrentSession') or '2004-2005'
210                cs = int(css.split('-')[0]) - 2000
[714]211                cl = int(student.get('StudentLevel') or '100')/100
[708]212                dsc['entry_session'] = "200%s" % (cs - cl)
213                dsc['clr_ac_pin'] = access_code
[714]214                studycourse.getContent().edit(mapping=dsc)
[364]215                #
216                # Level
217                #
[723]218##                l = getattr(studycourse,level,None)
219##                if 0 and l is None:
220##                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
221##                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
222##                    studycourse.invokeFactory('StudentStudyLevel', level)
223##                    l = getattr(studycourse, level)
224##                    certificate = certs[certcode]
225##                    cert_level = getattr(certificate,level,None)
226##                    if cert_level is None:
227##                        logger.info('Level %(level)s not in %(certcode)s' % vars())
228##                    l.getContent().edit(mapping={'Title': "Level %s" % level})
[361]229            else:
[393]230                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
[361]231                logger.info(em)
[393]232                no_import.write(em)
233                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]234                continue
[398]235            if tr_count > MAX_TRANS:
[422]236                transaction.commit()
237                em = 'Transaction commited\n' % student
[398]238                logger.info(em)
239                tr_count = 0
240            tr_count += 1
[708]241            pwl_dict.update(dc)
242            pwl_dict.update(da)
243            pwl_dict.update(dp)
[714]244            wftool = self.portal_workflow
[708]245            pwlist.append(pwl_template.substitute(pwl_dict))
[714]246            wftool.doActionFor(student_obj,'clear_and_validate')
[742]247            student_obj.manage_setLocalRoles(sid, ['Owner',])
[714]248            wftool.doActionFor(application,'close')
[742]249            application.manage_setLocalRoles(sid, ['Owner',])
[714]250            wftool.doActionFor(clearance,'close')
[742]251            clearance.manage_setLocalRoles(sid, ['Owner',])
[714]252            wftool.doActionFor(personal,'close')
[742]253            personal.manage_setLocalRoles(sid, ['Owner',])
[727]254            wftool.doActionFor(studycourse,'close_for_edit')
[742]255            studycourse.manage_setLocalRoles(sid, ['Owner',])
[714]256        open("%s/import/pwlist-%s.csv" % (i_home,name),"w+").write('\n'.join(pwlist))
[423]257        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[361]258    ###)
[382]259
[742]260    security.declareProtected(ModifyPortalContent,"loadPumeResultsFromCSV")###(
261    def loadPumeResultsFromCSV(self):
[966]262        """load Fulltime Studentdata from CSV values into pumeresults catalog"""
263        import transaction
264        import random
[1111]265##        csv_d = {'jamb_reg_no': "RegNumber", ###(
266##                 'status': "Admission Status",
267##                 'name': "Name",
268##                 'score': "Score",
269##                 'sex': "Sex",
270##                 'faculty': "Faculty",
271##                 'department': "Dept",
272##                 'course': "Course",
273##                 'course_code_org': "Course Code",
274##                 }
275###)
276        csv_d = {'jamb_reg_no': "JAMBRegno",
[966]277                 'name': "Name",
278                 'score': "Score",
279                 'sex': "Sex",
[1119]280                 'course': "Course",
[966]281                 'faculty': "Faculty",
282                 'department': "Dept",
283                 'course_code_org': "Course Code",
[1111]284                 'status': "Admission Status",
285                 'result_type': None,
[966]286                 }
[1111]287        csv_fields = [f[1] for f in csv_d.items() if f[1]]
[966]288        tr_count = 0
289        total = 0
[1111]290        name = 'pup_new'
291        #name = 'pup_update'
[971]292        update = name.endswith('update')
[966]293        no_import = []
[1111]294        ok_import = []
295        ok_import.append('%s' % ','.join(['"%s"' % fn for fn in csv_d.keys()]))
296        no_import.append('%s' % ','.join(['"%s"' % fn for fn in csv_fields]))
[1005]297        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
[1111]298        ok_import_name = "%s/import/%s_imported_%s.csv" % (i_home,name,current)
299        #open(ok_import_name,"w").write('\n'.join(no_import))
[1005]300        no_import_name = "%s/import/%s_not_imported_%s.csv" % (i_home,name,current)
[1111]301        #open(no_import_name,"w").write('\n'.join(no_import))
[1082]302        logger = logging.getLogger('Import.%s' % name)
[966]303        starttime = DateTime.now()
304        logger.info('Start loading from %s.csv' % name)
305        try:
306            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
307        except:
308            logger.error('Error reading %s.csv' % name)
309            return
310        pume = self.portal_pumeresults
311        format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
[1111]312        import_format = ','.join(['"%%(%s)s"' % fn for fn in csv_d.keys()])
[1119]313        eduplicate = '%s,"duplicate"' % format
314        einvalidjamb = '%s,"invalid JambRegNo"' % format
[1005]315        added = 'added ,%s' % format
[1111]316        #from pdb import set_trace;set_trace()
[966]317        for jamb in result:
318            dict = {}
319            for f,fn in csv_d.items():
320                dict[f] = jamb.get(csv_d[f])
[1111]321            dict['result_type'] = 'DE'
322            jnr = jamb.get(csv_d['jamb_reg_no'])
323            if not checkJambNo(jnr):
324                logger.info(einvalidjamb % jamb)
325                dd = {}
326                for f,fn in csv_d.items():
327                    dd[fn] = getattr(data,f)
328                    no_import.append(eduplicate % dd)
329                    no_import.append(eduplicate % jamb)
330                continue
331            res = pume(jamb_reg_no=jnr)
[971]332            if len(res) > 0:
333                if update:
[1005]334                    try:
335                        pume.modifyRecord(**dict)
336                    except ValueError:
337                        logger.info(eduplicate % jamb)
338                        continue
339                    except KeyError:
340                        pume.addRecord(**dict)
341                        logger.info(added % jamb)
342                        continue
[971]343                else:
344                    data = res[0]
345                    if data.name != jamb.get(csv_d['name']):
346                        #set_trace()
347                        logger.info(eduplicate % jamb)
348                        #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
349                        #logger.info(em)
350                        dd = {}
351                        for f,fn in csv_d.items():
352                            dd[fn] = getattr(data,f)
353                        no_import.append(eduplicate % dd)
354                        no_import.append(eduplicate % jamb)
355                    continue
[966]356            try:
357                pume.addRecord(**dict)
[1111]358                ok_import.append(import_format % dict)
[966]359            except ValueError:
360                logger.info(eduplicate % jamb)
361                #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
362                #logger.info(em)
363                no_import.append(eduplicate % jamb)
364        logger.info('End loading from %s.csv' % name)
365        if len(no_import) > 1:
[1005]366            open(no_import_name,"w+").write('\n'.join(no_import))
[1111]367        open(ok_import_name,"w+").write('\n'.join(ok_import))
[966]368        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[971]369    ###)
[966]370
[1121]371    security.declareProtected(ModifyPortalContent,"createDEStudents")###(
372    def createDEStudents(self):
373        """load Fulltime Studentdata from CSV values"""
374        import transaction
375        import random
376        #from pdb import set_trace
377        wftool = self.portal_workflow
378        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
379        csv_d = {'jamb_reg_no': "RegNumber",
380                 'jamb_lastname': "Name",
381                 'session': "Session",
382                 'pume_tot_score': "PUDE SCORE",
383                 ##'jamb_score': "JambScore",
384                 'entry_mode': "EntryMode",
385                 'jamb_sex': "Sex",
386                 'jamb_state': "State",
387                 'jamb_first_cos': "AdminCourse",
388                 'faculty': "AdminFaculty",
389                 'course_code': "AdmitCoscode",
390                 'stud_status':"AdmitStatus",
391                 'department': "AdmitDept",
392                 'jamb_lga': "LGA",
393                 'app_email': "email",
394                 'app_mobile': "PhoneNumbers",
395                 }
396        csv_fields = [f[1] for f in csv_d.items()]
397        tr_count = 0
398        total = 0
399        #name = 'pume_results'
400        name = 'DE_Admitted'
401        no_import = []
402        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
403        no_import.append('"Error",%s' % s)
404        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
405        no_certificate = "no certificate %s" % format
406        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write('\n'.join(no_import))
407        logger = logging.getLogger('Import.%s' % name)
408        logger.info('start loading from %s.csv' % name)
409        l = self.portal_catalog({'meta_type': "Certificate"})
410        certs = {}
411        cert_docs = {}
412        for f in l:
413            certs[f.getId] = f.getObject().getContent()
414        try:
415            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
416        except:
417            logger.error('Error reading %s.csv' % name)
418            return
419        for jamb in result:
420            jamb['Error'] = "Processing "
421            logger.info(format % jamb)
422            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
423            res = self.portal_catalog({'portal_type': "StudentApplication",
424                                     'SearchableText': jamb_reg_no })
425            if res:
426                em = 'Student with RegNo %s already exists\n' % jamb_reg_no
427                logger.info(em)
428                jamb['Error'] = "Student exists"
429                no_import.append(format % jamb)
430                continue
431            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
432            if cert_id not in certs.keys():
433                em = 'No Certificate with ID %s \n' % cert_id
434                logger.info(em)
435                jamb['Error'] = "No Certificate %s" % cert_id
436                no_import.append( format % jamb)
437                continue
438            jamb_reg_no =jamb.get(csv_d['jamb_reg_no'])
439            cert_doc = certs[cert_id]
440            catalog_entry = {}
441            catalog_entry['jamb_reg_no'] = jamb_reg_no
442            jamb_name = jamb.get(csv_d['jamb_lastname'])
443            jamb_name.replace('>','')
444            jamb_name.replace('<','')
445            names = jamb_name.split()
446            letter = names[-1][0].upper()
447            sid = self.generateStudentId(letter)
448            not_created = True
449            while not_created:
450                try:
451                    students_folder.invokeFactory('Student', sid)
452                    not_created = False
453                except BadRequest:
454                    sid = self.generateStudentId(letter)
455            catalog_entry['id'] = sid
456            tr_count += 1
457            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
458            student = getattr(self,sid)
459            student.manage_setLocalRoles(sid, ['Owner',])
460            student.invokeFactory('StudentPume','pume')
461            dp = {'Title': 'Pume Data'}
462            student.invokeFactory('StudentApplication','application')
463            da = {'Title': 'Application Data'}
464            da["jamb_lastname"] = jamb_name
465            da_fields = ('jamb_reg_no',
466                         'jamb_sex',
467                         'entry_mode',
468                         #'jamb_score',
469                         'jamb_first_cos',
470                         'jamb_sex',
471                         'jamb_state',
472                         'jamb_lga',
473                         'app_email',
474                         'app_mobile',
475                         )
476            for f in da_fields:
477                da[f] = jamb.get(csv_d[f])
478            catalog_entry['email'] = jamb.get(csv_d['app_email'])
479            app = student.application
480            app_doc = app.getContent()
481            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
482            #import pdb;pdb.set_trace()
483            if os.path.exists(picture):
484                file = open(picture)
485                if False:
486                    img = PIL.Image.open(file)
487                    img.thumbnail((150,200),
488                                  resample=PIL.Image.ANTIALIAS)
489                    # We now need a buffer to write to. It can't be the same
490                    # as the inbuffer as the PNG writer will write over itself.
491                    outfile = StringIO()
492                    img.save(outfile, format=img.format)
493                else:
494                    outfile = file.read()
495                app_doc.manage_addFile('passport',
496                                       file=outfile,
497                                       title="%s.jpg" % jamb_reg_no)
498            app.getContent().edit(mapping=da)
499            app.manage_setLocalRoles(sid, ['Owner',])
500            #wftool.doActionFor(app,'close')
501            dp_fields = (
502                         #'pume_eng_score',
503                         #'pume_gen_score',
504                         'pume_tot_score',
505                         )
506            dp['pume_tot_score'] = jamb.get(csv_d['pume_tot_score']) or "No Option Shaded"
507            pume = student.pume
508            pume.getContent().edit(mapping=dp)
509            #wftool.doActionFor(pume,'close')
510            pume.manage_setLocalRoles(sid, ['Owner',])
511            #student.getContent().createSubObjects()
512            dp = {}
513            if len(names) == 3:
514                dp['firstname'] = names[0].capitalize()
515                dp['middlename'] = names[1].capitalize()
516                dp['lastname'] = names[2].capitalize()
517            elif len(names) == 2:
518                dp['firstname'] = names[0].capitalize()
519                dp['middlename'] = ''
520                dp['lastname'] = names[1].capitalize()
521            else:
522                dp['firstname'] = ''
523                dp['middlename'] = ''
524                dp['lastname'] = jamb_name
525            dp['sex'] = jamb.get(csv_d['jamb_sex']) == 'F'
526            catalog_entry['sex'] = dp['sex']
527            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
528            student.invokeFactory('StudentPersonal','personal')
529            per = student.personal
530            per_doc = per.getContent()
531            per_doc.edit(mapping = dp)
532            per.manage_setLocalRoles(sid, ['Owner',])
533            if jamb.get(csv_d['stud_status']) == "Admitted":
534                wftool.doActionFor(student,'pume_pass')
535                wftool.doActionFor(student,'admit')
536            else:
537                wftool.doActionFor(student,'pume_fail')
538                wftool.doActionFor(student,'reject_admission')
539                continue
540            #
541            # Clearance
542            #
543            student.invokeFactory('StudentClearance','clearance')
544            #wftool.doActionFor(student.clearance,'open')
545            dp = {'Title': 'Clearance/Eligibility Record'}
546            student.clearance.manage_setLocalRoles(sid, ['Owner',])
547            #
548            # Study Course
549            #
550            student.invokeFactory('StudentStudyCourse','study_course')
551            study_course = student.study_course
552            dsc = {}
553            from_certificate = ['title',
554                               'max_elect',
555                               'max_pass',
556                               'n_core',
557                               'nr_years',
558                               'probation_credits',
559                               'promotion_credits',
560                               'start_level',
561                              ]
562            for f in from_certificate:
563                dsc[f] = getattr(cert_doc,f)
564            dsc['faculty'] = jamb.get(csv_d['faculty'])
565            dsc['department'] = jamb.get(csv_d['department'])
566            catalog_entry['faculty'] = jamb.get(csv_d['faculty'])
567            catalog_entry['department'] = jamb.get(csv_d['department'])
568            catalog_entry['course'] = cert_id
569            catalog_entry['level'] = getattr(cert_doc,'start_level')
570            dsc['study_course'] = cert_id
571            dsc['entry_session'] = jamb.get(csv_d['session'])
572            study_course.getContent().edit(mapping=dsc)
573            self.students_catalog.addRecord(**catalog_entry)
[1124]574            if tr_count > 10:
[1121]575                if len(no_import) > 1:
[1127]576                    open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
[1121]577                             '\n'.join(no_import))
578                    no_import = []
579                em = '%d transactions commited\n' % tr_count
580                transaction.commit()
581                logger.info(em)
582                total += tr_count
583                tr_count = 0
[1127]584        open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
[1125]585                                               '\n'.join(no_import))
[1121]586        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
587    ###)
588
[966]589    security.declareProtected(ModifyPortalContent,"createNewStudents")###(
590    def createNewStudents(self):
[742]591        """load Fulltime Studentdata from CSV values"""
592        import transaction
593        import random
[971]594        #from pdb import set_trace
[763]595        wftool = self.portal_workflow
[757]596        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
[971]597        csv_d = {'jamb_reg_no': "RegNumber",
[958]598                 'jamb_lastname': "Name",
[971]599                 'session': "Session",
600                 'pume_tot_score': "PUME SCORE",
601                 'jamb_score': "JambScore",
[958]602                 'jamb_sex': "Sex",
[971]603                 'jamb_state': "State",
[980]604##                 'jamb_first_cos': "AdminCourse",
[971]605                 'faculty': "AdminFaculty",
606                 'course_code': "AdmitCoscode",
607                 'stud_status':"AdmitStatus",
608                 'department': "AdmitDept",
609                 'jamb_lga': "LGA",
610                 'app_email': "email",
[980]611                 'app_mobile': "PhoneNumbers",
[958]612                 }
613        csv_fields = [f[1] for f in csv_d.items()]
614        tr_count = 0
[961]615        total = 0
[958]616        #name = 'pume_results'
[971]617        name = 'Admitted'
[958]618        no_import = []
619        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
[971]620        no_import.append('"Error",%s' % s)
621        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
622        no_certificate = "no certificate %s" % format
[1121]623        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write('\n'.join(no_import))
[1082]624        logger = logging.getLogger('Import.%s' % name)
[1121]625        logger.info('start loading from %s.csv' % name)
[971]626        l = self.portal_catalog({'meta_type': "Certificate"})
627        certs = {}
628        cert_docs = {}
629        for f in l:
630            certs[f.getId] = f.getObject().getContent()
[958]631        try:
632            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
633        except:
634            logger.error('Error reading %s.csv' % name)
635            return
636        for jamb in result:
[971]637            jamb['Error'] = "Processing "
638            logger.info(format % jamb)
[958]639            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
640            res = self.portal_catalog({'portal_type': "StudentApplication",
[959]641                                     'SearchableText': jamb_reg_no })
[958]642            if res:
[980]643                em = 'Student with RegNo %s already exists\n' % jamb_reg_no
[958]644                logger.info(em)
[971]645                jamb['Error'] = "Student exists"
[958]646                no_import.append(format % jamb)
647                continue
[971]648            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
649            if cert_id not in certs.keys():
[958]650                em = 'No Certificate with ID %s \n' % cert_id
651                logger.info(em)
[971]652                jamb['Error'] = "No Certificate %s" % cert_id
653                no_import.append( format % jamb)
[958]654                continue
[1121]655            res = self.portal_pumeresults(jamb_reg_no = jamb_reg_no)
656            if len(res) == 1:
657                self.portal_pumeresults.modifyRecord(jamb_reg_no = jamb_reg_no,
658                                                     status = jamb.get(csv_d['stud_status']),
659                                                     )
660            jamb_reg_no =jamb.get(csv_d['jamb_reg_no'])
[971]661            cert_doc = certs[cert_id]
662            catalog_entry = {}
663            catalog_entry['jamb_reg_no'] = jamb_reg_no
[958]664            jamb_name = jamb.get(csv_d['jamb_lastname'])
665            jamb_name.replace('>','')
[966]666            jamb_name.replace('<','')
[958]667            names = jamb_name.split()
668            letter = names[-1][0].upper()
669            sid = self.generateStudentId(letter)
670            not_created = True
671            while not_created:
672                try:
673                    students_folder.invokeFactory('Student', sid)
674                    not_created = False
675                except BadRequest:
676                    sid = self.generateStudentId(letter)
[971]677            catalog_entry['id'] = sid
[958]678            tr_count += 1
[961]679            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[958]680            student = getattr(self,sid)
681            student.manage_setLocalRoles(sid, ['Owner',])
682            student.invokeFactory('StudentPume','pume')
683            dp = {'Title': 'Pume Data'}
684            student.invokeFactory('StudentApplication','application')
685            da = {'Title': 'Application Data'}
686            da["jamb_lastname"] = jamb_name
687            da_fields = ('jamb_reg_no',
688                         'jamb_sex',
689                         #'jamb_state',
[966]690                         'jamb_score',
[980]691##                         'jamb_first_cos',
[958]692                         'jamb_sex',
[971]693                         'jamb_state',
694                         'jamb_lga',
695                         'app_email',
[980]696                         'app_mobile',
[958]697                         )
698            for f in da_fields:
699                da[f] = jamb.get(csv_d[f])
[971]700            catalog_entry['email'] = jamb.get(csv_d['app_email'])
[958]701            app = student.application
[971]702            app_doc = app.getContent()
[975]703            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
[971]704            #import pdb;pdb.set_trace()
705            if os.path.exists(picture):
706                file = open(picture)
[974]707                if False:
708                    img = PIL.Image.open(file)
709                    img.thumbnail((150,200),
710                                  resample=PIL.Image.ANTIALIAS)
711                    # We now need a buffer to write to. It can't be the same
712                    # as the inbuffer as the PNG writer will write over itself.
713                    outfile = StringIO()
714                    img.save(outfile, format=img.format)
715                else:
716                    outfile = file.read()
[971]717                app_doc.manage_addFile('passport',
718                                       file=outfile,
719                                       title="%s.jpg" % jamb_reg_no)
[958]720            app.getContent().edit(mapping=da)
721            app.manage_setLocalRoles(sid, ['Owner',])
722            #wftool.doActionFor(app,'close')
723            dp_fields = (
724                         #'pume_eng_score',
725                         #'pume_gen_score',
726                         'pume_tot_score',
727                         )
[964]728            dp['pume_tot_score'] = jamb.get(csv_d['pume_tot_score']) or "No Option Shaded"
[958]729            pume = student.pume
730            pume.getContent().edit(mapping=dp)
731            #wftool.doActionFor(pume,'close')
732            pume.manage_setLocalRoles(sid, ['Owner',])
[966]733            #student.getContent().createSubObjects()
[975]734            dp = {}
[966]735            if len(names) == 3:
736                dp['firstname'] = names[0].capitalize()
737                dp['middlename'] = names[1].capitalize()
738                dp['lastname'] = names[2].capitalize()
739            elif len(names) == 2:
740                dp['firstname'] = names[0].capitalize()
[971]741                dp['middlename'] = ''
[966]742                dp['lastname'] = names[1].capitalize()
743            else:
[971]744                dp['firstname'] = ''
745                dp['middlename'] = ''
[966]746                dp['lastname'] = jamb_name
747            dp['sex'] = jamb.get(csv_d['jamb_sex']) == 'F'
[971]748            catalog_entry['sex'] = dp['sex']
749            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
[966]750            student.invokeFactory('StudentPersonal','personal')
751            per = student.personal
752            per_doc = per.getContent()
753            per_doc.edit(mapping = dp)
754            per.manage_setLocalRoles(sid, ['Owner',])
[958]755            if jamb.get(csv_d['stud_status']) == "Admitted":
756                wftool.doActionFor(student,'pume_pass')
757                wftool.doActionFor(student,'admit')
758            else:
759                wftool.doActionFor(student,'pume_fail')
760                wftool.doActionFor(student,'reject_admission')
761                continue
[964]762            #
[966]763            # Clearance
764            #
765            student.invokeFactory('StudentClearance','clearance')
766            #wftool.doActionFor(student.clearance,'open')
767            dp = {'Title': 'Clearance/Eligibility Record'}
768            student.clearance.manage_setLocalRoles(sid, ['Owner',])
769            #
[964]770            # Study Course
771            #
[958]772            student.invokeFactory('StudentStudyCourse','study_course')
773            study_course = student.study_course
774            dsc = {}
775            from_certificate = ['title',
776                               'max_elect',
777                               'max_pass',
778                               'n_core',
779                               'nr_years',
780                               'probation_credits',
781                               'promotion_credits',
782                               'start_level',
783                              ]
784            for f in from_certificate:
785                dsc[f] = getattr(cert_doc,f)
[971]786            dsc['faculty'] = jamb.get(csv_d['faculty'])
787            dsc['department'] = jamb.get(csv_d['department'])
788            catalog_entry['faculty'] = jamb.get(csv_d['faculty'])
789            catalog_entry['department'] = jamb.get(csv_d['department'])
790            catalog_entry['course'] = cert_id
791            catalog_entry['level'] = getattr(cert_doc,'start_level')
[958]792            dsc['study_course'] = cert_id
[971]793            dsc['entry_session'] = jamb.get(csv_d['session'])
[958]794            study_course.getContent().edit(mapping=dsc)
[971]795            self.students_catalog.addRecord(**catalog_entry)
[1126]796            if tr_count > 10:
797                if len(no_import) > 0:
[1127]798                    open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
[966]799                             '\n'.join(no_import))
800                    no_import = []
[961]801                em = '%d transactions commited\n' % tr_count
[958]802                transaction.commit()
803                logger.info(em)
[961]804                total += tr_count
[958]805                tr_count = 0
[1127]806        open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
[1126]807                                                '\n'.join(no_import))
[958]808        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
809    ###)
810
[1151]811    security.declareProtected(ModifyPortalContent,"importReturningStudents")###(
812    def importReturningStudents(self):
813        """load Returning Studentdata from CSV values"""
[1146]814        import transaction
815        import random
816        #from pdb import set_trace
817        wftool = self.portal_workflow
818        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
819        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
820        tr_count = 1
821        total = 0
822        #name = 'pume_results'
[1151]823        name = 'Returning'
824        table = self.returning_import
[1146]825        no_import = []
826        imported = []
827        logger = logging.getLogger('Import.%s' % name)
828        try:
[1151]829            returning = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[1146]830        except:
831            logger.error('Error reading %s.csv' % name)
832            return
833        l = self.portal_catalog({'meta_type': "Certificate"})
834        certs = {}
835        cert_docs = {}
836        for f in l:
837            certs[f.getId] = f.getObject().getContent()
838        start = True
839        res = table()
840        regs = []
841        if len(res) > 0:
842            regs = [s.matric_no for s in res]
[1151]843        for student in returning:
[1146]844            if start:
845                start = False
846                logger.info('start loading from %s.csv' % name)
847                s = ','.join(['"(%s)"' % fn for fn in student.keys()])
848                imported.append(s)
849                no_import.append('%s,"Error"' % s)
850                format = ','.join(['"%%(%s)s"' % fn for fn in student.keys()])
851                format_error = format + ',"%(Error)s"'
852                no_certificate = "no certificate %s" % format
[1168]853            matric_no = student.get('matric_no').upper()
854            student['matric_no'] = matric_no
855            if matric_no == '':
[1146]856                student['Error'] = "Empty matric_no" 
857                no_import.append( format_error % student)
858                continue
[1168]859            if matric_no in regs or self.returning_import(matric_no = matric_no):
[1146]860                student['Error'] = "Duplicate" 
861                no_import.append( format_error % student)
862                continue
863            cert_id = makeCertificateCode(student.get('Coursemajorcode'))
864            if cert_id not in certs.keys():
865                student['Error'] = "No Certificate %s" % cert_id
866                no_import.append( format_error % student)
867                continue
868            try:
869                table.addRecord(**student)
870            except ValueError:
871                import pdb;pdb.set_trace()
872                student['Error'] = "Duplicate" 
873                no_import.append( format_error % student)
874                continue
875            regs.append(student.get('matric_no'))
876            imported.append(format % student)
877            tr_count += 1
878            if tr_count > 1000:
879                if len(no_import) > 0:
880                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
[1151]881                             '\n'.join(no_import) + '\n')
[1146]882                    no_import = []
883                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
[1151]884                                            '\n'.join(no_import) + "\n")
885                imported = []
[1146]886                em = '%d transactions commited total %s\n' % (tr_count,total)
887                transaction.commit()
[1168]888                regs = []
[1146]889                logger.info(em)
890                total += tr_count
891                tr_count = 0
892        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
893                                            '\n'.join(no_import))
894        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
895                                                '\n'.join(no_import))
896        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
897    ###)
898
899    security.declareProtected(ModifyPortalContent,"importResults")###(
900    def importResults(self):
[1151]901        """load Returning Students Results from CSV"""
[1146]902        import transaction
903        import random
904        #from pdb import set_trace
905        wftool = self.portal_workflow
906        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
907        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
908        tr_count = 1
909        total = 0
910        #name = 'pume_results'
911        name = 'Results'
912        table = self.results_import
913        no_import = []
914        imported = []
915        logger = logging.getLogger('Import.%s' % name)
916        try:
917            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
918        except:
919            logger.error('Error reading %s.csv' % name)
920            return
921        l = self.portal_catalog({'meta_type': "Course"})
922        courses = [f.getId for f in l]
923        start = True
924        res = table()
925        regs = []
926        if len(res) > 0:
927            regs = [s.key for s in res]
928        no_course = []
929        no_course_list = []
930        course_count = 0
931        for result in results:
932            if start:
933                start = False
934                logger.info('start loading from %s.csv' % name)
935                s = ','.join(['"(%s)"' % fn for fn in result.keys()])
936                imported.append(s)
937                no_import.append('%s,"Error"' % s)
938                format = ','.join(['"%%(%s)s"' % fn for fn in result.keys()])
939                format_error = format + ',"%(Error)s"'
940                no_certificate = "no certificate %s" % format
941            course_id = result.get('CosCode')
[1168]942            matric_no = result.get('matric_no').upper()
943            result['matric_no'] = matric_no
944            key = matric_no+course_id
945            if matric_no == '':
[1146]946                result['Error'] = "Empty matric_no" 
947                no_import.append( format_error % result)
948                continue
[1168]949            if key in regs or self.results_import(key = key):
[1146]950                result['Error'] = "Duplicate" 
951                no_import.append( format_error % result)
952                continue
953            if course_id not in courses:
954                if course_id not in no_course:
955                    course_count +=1
956                    no_course.append(course_id)
957                    no_course_list.append('"%s"' % course_id)
958                    #result['Error'] = "No Course"
959                    #logger.info(format_error % result)
960            result['key'] = key
961            try:
962                table.addRecord(**result)
963            except ValueError:
964                import pdb;pdb.set_trace()
965                result['Error'] = "Duplicate" 
966                no_import.append( format_error % result)
967                continue
968            regs.append(key)
969            imported.append(format % result)
970            tr_count += 1
971            if tr_count > 1000:
972                if len(no_import) > 0:
973                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
[1151]974                             '\n'.join(no_import)+'\n')
[1146]975                    no_import = []
976                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
[1151]977                                            '\n'.join(imported) + '\n')
[1146]978                imported = []
979                if no_course_list:
980                    open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
[1151]981                                            '\n'.join(no_course_list) + '\n')
[1146]982                    no_course_list = []
983                em = '%d transactions commited total %s\n courses not found %s' % (tr_count,total,course_count)
984                transaction.commit()
985                logger.info(em)
[1168]986                regs = []
[1146]987                total += tr_count
988                tr_count = 0
989        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
990                                            '\n'.join(imported))
991        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
992                                                '\n'.join(no_import))
993        if no_course_list:
994            open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
995                                    '\n'.join(no_course_list))
996        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
997    ###)
998
[1065]999    security.declareProtected(ModifyPortalContent,"updateStudyCourse")###(
1000    def updateStudyCourse(self):
1001        """update StudyCourse from CSV values"""
1002        import transaction
1003        import random
1004        from pdb import set_trace
1005        wftool = self.portal_workflow
1006        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
1007        csv_d = {'jamb_reg_no': "RegNumber",
1008                 'jamb_lastname': "Name",
1009                 'session': "Session",
1010                 'pume_tot_score': "PUME SCORE",
1011                 'jamb_score': "JambScore",
1012                 'jamb_sex': "Sex",
1013                 'jamb_state': "State",
1014##                 'jamb_first_cos': "AdminCourse",
1015                 'faculty': "AdminFaculty",
1016                 'course_code': "AdmitCoscode",
1017                 'stud_status':"AdmitStatus",
1018                 'department': "AdmitDept",
1019                 'jamb_lga': "LGA",
1020                 'app_email': "email",
1021                 'app_mobile': "PhoneNumbers",
1022                 }
1023        csv_fields = [f[1] for f in csv_d.items()]
1024        tr_count = 0
1025        total = 0
1026        #name = 'pume_results'
1027        name = 'StudyCourseChange'
1028        no_import = []
1029        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
1030        no_import.append('"Error",%s' % s)
1031        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
1032        no_certificate = "no certificate %s" % format
1033        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
1034                    '\n'.join(no_import))
[1082]1035        logger = logging.getLogger('Import.%s' % name)
[1065]1036        logger.info('Start loading from %s.csv' % name)
1037        l = self.portal_catalog({'meta_type': "Certificate"})
1038        try:
1039            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1040        except:
1041            logger.error('Error reading %s.csv' % name)
1042            return
1043        for jamb in result:
1044            jamb['Error'] = "Processing "
1045            logger.info(format % jamb)
1046            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
1047            res = self.portal_catalog({'portal_type': "StudentApplication",
1048                                     'SearchableText': jamb_reg_no })
1049            if not res:
1050                em = 'Student with RegNo %s does not exists\n' % jamb_reg_no
1051                logger.info(em)
1052                jamb['Error'] = "Student not exists"
1053                no_import.append(format % jamb)
1054                continue
1055            sid = res[0].getPath().split('/')[-2]
1056            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
1057            res = self.portal_catalog(portal_type = "Certificate", id = cert_id)
1058            if not res:
1059                em = 'No Certificate with ID %s \n' % cert_id
1060                logger.info(em)
1061                jamb['Error'] = "No Certificate %s" % cert_id
1062                no_import.append( format % jamb)
1063                continue
1064            cert_brain = res[0]
1065            catalog_entry = {}
1066            student = getattr(self,sid)
1067            #
1068            # Study Course
1069            #
1070            study_course = student.study_course
1071            dsc = {}
1072            cert_pl = cert_brain.getPath().split('/')
1073            catalog_entry['id'] = sid
1074            catalog_entry['faculty'] = cert_pl[-4]
1075            catalog_entry['department'] = cert_pl[-3]
1076            catalog_entry['course'] = cert_id
1077            dsc['study_course'] = cert_id
1078            study_course.getContent().edit(mapping=dsc)
1079            self.students_catalog.modifyRecord(**catalog_entry)
1080            if tr_count > 10:
1081                if len(no_import) > 1:
1082                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
1083                             '\n'.join(no_import))
1084                    no_import = []
1085                em = '%d transactions commited\n' % tr_count
1086                transaction.commit()
1087                logger.info(em)
1088                total += tr_count
1089                tr_count = 0
1090            tr_count += 1
1091        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1092    ###)
1093
[958]1094    security.declareProtected(ModifyPortalContent,"OLDloadPumeResultsFromCSV")###(
1095    def OLDloadPumeResultsFromCSV(self):
1096        """load Fulltime Studentdata from CSV values"""
1097        import transaction
1098        import random
1099        wftool = self.portal_workflow
1100        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
1101        csv_d = {'jamb_reg_no': "JAMBRegno",
1102                 'jamb_lastname': "Name",
[757]1103                 'pume_options': "Options",
1104                 'session': "Session",
1105                 'days': "Days",
1106                 'response': "Responce",
1107                 'wrong': "Wrong",
1108                 'pume_eng_score': "EngScore",
[775]1109                 'pume_gen_score': "GenScore",
[958]1110                 'pume_tot_score': "Score",
[757]1111                 'batch': "Batch",
1112                 'serial': "SerialNo",
1113                 'jamb_score': "JambScore",
1114                 'omitted':"Omitted",
1115                 'search_key': "SearchKey",
1116                 'jamb_sex': "Sex",
1117                 'fac1': "Fac1",
1118                 'fac2': "Fac2",
1119                 'jamb_first_cos': "CourseofStudy",
1120                 'stud_status':"StudStatus",
1121                 'registered': "Registered",
1122                 'jamb_state': "State",
1123                 'eng_fail': "EngFail",
1124                 'gen_fail': "GenFail",
1125                 'un_ans_eng': "UnAnsEng",
1126                 'un_ans_eng': "UnAnsGen",
1127                 'total_ans': "TotalUnAns",
1128                 'dept': "Dept",
1129                 'jamb_second_cos': "Course2",
1130                 'jamb_third_cos': "course3",
1131                 }
1132        csv_fields = [f[1] for f in csv_d.items()]
[742]1133        tr_count = 0
1134        name = 'pume_results'
[757]1135        no_import = []
1136        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
1137        no_import.append('%s\n' % s)
[1082]1138        logger = logging.getLogger('Import.%s' % name)
[742]1139        logger.info('Start loading from %s.csv' % name)
1140        try:
[757]1141            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[742]1142        except:
1143            logger.error('Error reading %s.csv' % name)
1144            return
[757]1145        for jamb in result:
1146            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
1147            processing = "processing %s" % format
1148            logger.info(processing % jamb)
1149            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
[763]1150            #import pdb;pdb.set_trace()
1151            res = self.portal_catalog({'portal_type': "StudentApplication",
[757]1152                                     'jamb_reg_no': jamb_reg_no })
1153            if res:
1154                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
[742]1155                logger.info(em)
[757]1156                no_import.append(em)
1157                no_import.append(format % jamb)
[742]1158                continue
[785]1159            cert_id = jamb.get(csv_d['jamb_first_cos']).upper()
1160            res = self.portal_catalog({'portal_type': "Certificate",
1161                                     'id': cert_id })
1162            if len(res) < 1:
1163                em = 'No Certificate with ID %s \n' % cert_id
1164                logger.info(em)
1165                no_import.append(em)
1166                no_import.append(format % jamb)
1167                continue
1168            cert = res[0].getObject()
1169            cert_path = res[0].getPath()
1170            cert_doc = cert.getContent()
[757]1171            jamb_name = jamb.get(csv_d['jamb_lastname'])
1172            jamb_name.replace('>','')
1173            names = jamb_name.split()
1174            letter = names[-1][0].upper()
1175            sid = self.generateStudentId(letter)
1176            not_created = True
1177            while not_created:
1178                try:
1179                    students_folder.invokeFactory('Student', sid)
1180                    not_created = False
1181                except BadRequest:
1182                    sid = self.generateStudentId(letter)
1183            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
1184            student = getattr(self,sid)
1185            student.manage_setLocalRoles(sid, ['Owner',])
[766]1186            student.invokeFactory('StudentClearance','clearance')
[775]1187            #wftool.doActionFor(student.clearance,'open')
[840]1188            dp = {'Title': 'Clearance/Eligibility Record'}
[766]1189            student.clearance.manage_setLocalRoles(sid, ['Owner',])
[763]1190            student.invokeFactory('StudentPume','pume')
1191            dp = {'Title': 'Pume Data'}
[757]1192            student.invokeFactory('StudentApplication','application')
1193            da = {'Title': 'Application Data'}
1194            da["jamb_lastname"] = jamb_name
1195            da_fields = ('jamb_reg_no',
1196                         'jamb_sex',
1197                         'jamb_state',
1198                         'jamb_score',
1199                         'jamb_first_cos',
1200                         'jamb_sex',
1201                         'jamb_state',
1202                         'jamb_first_cos',
1203                         'jamb_second_cos',
1204                         )
[763]1205            for f in da_fields:
1206                da[f] = jamb.get(csv_d[f])
[757]1207            app = student.application
[763]1208            app.getContent().edit(mapping=da)
[757]1209            app.manage_setLocalRoles(sid, ['Owner',])
[780]1210            #wftool.doActionFor(app,'close')
[763]1211            dp_fields = (
1212                         'pume_eng_score',
[764]1213                         'pume_gen_score',
[763]1214                         'pume_tot_score',
1215                         )
1216            for f in dp_fields:
[775]1217                dp[f] = float(jamb.get(csv_d[f]))
[765]1218            pume = student.pume
1219            pume.getContent().edit(mapping=dp)
[780]1220            #wftool.doActionFor(pume,'close')
[763]1221            pume.manage_setLocalRoles(sid, ['Owner',])
[785]1222            #
1223            # Study Course
1224            #
1225            student.invokeFactory('StudentStudyCourse','study_course')
1226            study_course = student.study_course
1227            dsc = {}
1228            from_certificate = ['title',
1229                               'max_elect',
1230                               'max_pass',
1231                               'n_core',
1232                               'nr_years',
1233                               'probation_credits',
1234                               'promotion_credits',
1235                               'start_level',
1236                              ]
1237            for f in from_certificate:
1238                dsc[f] = getattr(cert_doc,f)
1239            cpl = cert_path.split('/')
1240            dsc['faculty'] = cpl[-4]
1241            dsc['department'] = cpl[-3]
1242            dsc['study_course'] = cert_id
1243            dsc['entry_session'] = jamb.get(csv_d['session'])
1244            study_course.getContent().edit(mapping=dsc)
[757]1245            student.getContent().createSubObjects()
[775]1246            if dp['pume_tot_score']>49:
[780]1247                wftool.doActionFor(student,'pume_pass')
[785]1248                wftool.doActionFor(student,'admit')
[775]1249            else:
[780]1250                wftool.doActionFor(student,'pume_fail')
[790]1251                wftool.doActionFor(student,'reject_admission')
[757]1252            if len(no_import) > 1:
1253                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
1254                     '\n'.join(no_import))
[742]1255        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1256    ###)
1257
[398]1258    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
[396]1259    def loadFullTimeStudentsResultsFromCSV(self):
1260        """load Fulltime Studentdata from CSV values"""
1261        #return
[723]1262        level_wf_actions = {}
1263        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
1264        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
[727]1265        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
1266        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
[398]1267        import transaction
[723]1268        wftool = self.portal_workflow
[398]1269        tr_count = 0
1270        name = 'short_full_time_results_2004_2005'
[396]1271        no_import = False
1272        if not no_import:
1273            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
1274            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
[1146]1275        logger = logging.getLogger('import.%s' % name)
[396]1276        logger.info('Start loading from %s.csv' % name)
1277        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
1278        try:
1279            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1280        except:
1281            logger.error('Error reading %s.csv' % name)
1282            return
[398]1283        l = self.portal_catalog({'meta_type': "Course"})
1284        courses = {}
1285        for c in l:
1286            courses[c.id] = c.getObject()
[723]1287        level_changed = False
1288        student_changed = False
1289        sid = ''
1290        #import pdb;pdb.set_trace()
[396]1291        for result in results:
[723]1292            temp_sid = result.get('Matnumber')
1293            if temp_sid != sid:
1294                student_changed = True
1295                res = self.portal_catalog({'meta_type': "StudentClearance",
1296                                         'SearchableText': temp_sid })
1297                if not res:
1298                    em = 'Student with ID %(Matnumber)s not found\n' % result
1299                    logger.info(em)
1300                    no_import.write(em)
1301                    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)
1302                    continue
1303                elif len(res) > 1:
1304                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
1305                    logger.info(em)
1306                    no_import.write(em)
1307                    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)
1308                    continue
1309                sid = temp_sid
1310                sf = res[0].getObject().aq_parent
1311                sc = getattr(sf,'study_course')
1312                level = ''
1313            else:
1314                student_changed = False
[398]1315            course = result.get('CosCode')
1316            if course not in courses.keys():
1317                em = 'Course with ID %(CosCode)s not found\n' % result
[396]1318                logger.info(em)
1319                no_import.write(em)
[398]1320                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]1321                continue
[727]1322            course_doc = courses[course].getContent()
[723]1323            temp_level = result.get('Level')
[742]1324            student_id = sf.getId()
1325            result['StudentId'] = student_id
[723]1326            if temp_level != level:
1327                try:
1328                    int(temp_level)
1329                except:
1330                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
1331                    logger.info(em)
1332                    no_import.write(em)
1333                    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)
1334                    continue
[727]1335                level_changed = True
1336                if 'dlev' in vars().keys():
[723]1337                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
1338                level = temp_level
1339                l = getattr(sc,level,None)
1340                if l is None:
1341                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
1342                    sc.invokeFactory('StudentStudyLevel', level)
1343                    l = getattr(sc, level)
[742]1344                    l.manage_setLocalRoles(student_id, ['Owner',])
[723]1345            else:
1346                level_changed = False
1347            cr = getattr(l,course,None)
1348            if cr is None:
1349                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
1350                l.invokeFactory('StudentCourseResult',course)
1351            cr = getattr(l,course)
1352            dcr = {}
[727]1353            from_course = ['title',
1354                           'credits',
1355                           'passmark',
1356                           ]
1357            for f in from_course:
1358                dcr[f] = getattr(course_doc,f)
[454]1359            dlev = {}
[723]1360            dcr['ansbook'] = result.get('Ansbook')
1361            dcr['semester'] = getInt(result.get('Semster'))
1362            dcr['status'] = result.get('CosStuatus')
1363            dcr['score'] = getInt(result.get('Score'))
[454]1364            dlev['session'] = result.get('Session')
[723]1365            dcr['carry_level'] = result.get('CarryLevel')
1366            dcr['grade'] = result.get('Grade')
[725]1367            dcr['weight'] = result.get('Weight')
[454]1368            dlev['verdict'] = result.get('Verdict')
[725]1369            dcr['import_id'] = result.get('id')
1370            gpa = result.get('GPA').replace(',','.')
1371            dlev['imported_gpa'] = getFloat(gpa)
[723]1372            cr.getContent().edit(mapping = dcr)
[742]1373            cr.manage_setLocalRoles(student_id, ['Owner',])
[454]1374            l.getContent().edit(mapping = dlev)
[398]1375            if tr_count > MAX_TRANS:
1376                transaction.commit()
1377                tr_count = 0
1378            tr_count += 1
[723]1379            wftool.doActionFor(cr,'close')
1380        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
[681]1381        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[426]1382
[398]1383###)
[396]1384
[457]1385    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
1386    def loadJAMBFromCSV(self):
1387        """load JAMB data from CSV values"""
1388        #return
1389        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
1390        import transaction
1391        tr_count = 0
[572]1392        name = 'SampleJAMBDataII'
[511]1393        wftool = self.portal_workflow
[457]1394        no_import = False
1395        if not no_import:
1396            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
1397            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')
[1082]1398        logger = logging.getLogger('Import.%s' % name)
[457]1399        logger.info('Start loading from %s.csv' % name)
1400        try:
1401            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1402        except:
1403            logger.error('Error reading %s.csv' % name)
1404            return
1405        for jamb in result:
1406            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)
1407            jamb_reg_no = jamb.get('REG-NO')
[472]1408            res = self.portal_catalog({'meta_type': "StudentApplication",
[457]1409                                     'jamb_reg_no': jamb_reg_no })
1410            if res:
1411                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
1412                logger.info(em)
1413                no_import.write(em)
1414                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)
1415                continue
[511]1416            jamb_name = jamb.get("NAME")
[584]1417            jamb_name.replace('>','')
[511]1418            names = jamb_name.split()
1419            letter = names[-1][0].upper()
[714]1420            sid = self.generateStudentId(letter)
[457]1421            not_created = True
1422            while not_created:
1423                try:
1424                    students_folder.invokeFactory('Student', sid)
1425                    not_created = False
1426                except BadRequest:
[714]1427                    sid = self.generateStudentId(letter)
[457]1428            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[511]1429            student = getattr(self,sid)
[519]1430            student.manage_setLocalRoles(sid, ['Owner',])
[511]1431            student.invokeFactory('StudentApplication','application')
[472]1432            da = {'Title': 'Application Data'}
[457]1433            da["jamb_reg_no"] = jamb.get("REG-NO")
[511]1434            da["jamb_lastname"] = jamb_name
[457]1435            da["jamb_sex"] = jamb.get("SEX")
1436            da["jamb_state"] = jamb.get("STATE")
1437            da["jamb_lga"] = jamb.get("LGA")
1438            da["jamb_score"] = jamb.get("AGGREGATE")
1439            da["jamb_first_cos"] = jamb.get("COURSE1")
1440            da["jamb_second_cos"] = jamb.get("COURSE2")
1441            da["jamb_first_uni"] = jamb.get("UNIV1")
1442            da["jamb_second_uni"] = jamb.get("UNIV2")
[511]1443            app = student.application
1444            app_doc = app.getContent()
1445            app_doc.edit(mapping=da)
[658]1446            #wftool.doActionFor(app,'open',dest_container=app)
[511]1447            app.manage_setLocalRoles(sid, ['Owner',])
1448            student.getContent().createSubObjects()
[457]1449        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1450    ###)
[426]1451
[472]1452
[511]1453    security.declareProtected(View,"fixOwnership")
1454    def fixOwnership(self):
1455        """fix Ownership"""
1456        for s in self.portal_catalog(meta_type = 'Student'):
1457            student = s.getObject()
1458            sid = s.getId
1459            import pdb;pdb.set_trace()
1460            student.application.manage_setLocalRoles(sid, ['Owner',])
1461            student.personal.manage_setLocalRoles(sid, ['Owner',])
[603]1462
[364]1463    security.declareProtected(View,"Title")
1464    def Title(self):
1465        """compose title"""
[382]1466        return "Student Section"
[361]1467
[714]1468    def generateStudentId(self,letter): ###(
1469        import random
1470        r = random
1471        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
1472            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
1473        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
1474        sid = "%c%d" % (letter,r.randint(99999,1000000))
1475        while hasattr(students, sid):
1476            sid = "%c%d" % (letter,r.randint(99999,1000000))
[758]1477        return sid
[714]1478        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
1479    ###)
1480
[361]1481InitializeClass(StudentsFolder)
1482
1483def addStudentsFolder(container, id, REQUEST=None, **kw):
1484    """Add a Student."""
1485    ob = StudentsFolder(id, **kw)
1486    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1487###)
1488
[57]1489class Student(CPSDocument): ###(
1490    """
[154]1491    WAeUP Student container for the various student data
[57]1492    """
1493    meta_type = 'Student'
1494    portal_type = meta_type
1495    security = ClassSecurityInfo()
[154]1496
[152]1497    security.declareProtected(View,"Title")
1498    def Title(self):
1499        """compose title"""
[153]1500        reg_nr = self.getId()[1:]
[362]1501        data = getattr(self,'personal',None)
[152]1502        if data:
1503            content = data.getContent()
[1143]1504            return "%s %s %s" % (content.firstname,content.middlename,content.lastname)
[472]1505        data = getattr(self,'application',None)
[464]1506        if data:
1507            content = data.getContent()
1508            return "%s" % (content.jamb_lastname)
[152]1509        return self.title
[154]1510
[511]1511    security.declarePrivate('makeStudentMember') ###(
1512    def makeStudentMember(self,sid,password='uNsEt'):
1513        """make the student a member"""
1514        membership = self.portal_membership
[603]1515        membership.addMember(sid,
[511]1516                             password ,
1517                             roles=('Member',
1518                                     'Student',
[522]1519                                     ),
[511]1520                             domains='',
[904]1521                             properties = {'memberareaCreationFlag': False,
1522                                           'homeless': True},)
[511]1523        member = membership.getMemberById(sid)
1524        self.portal_registration.afterAdd(member, sid, password, None)
1525        self.manage_setLocalRoles(sid, ['Owner',])
1526
1527###)
1528
[764]1529    security.declareProtected(View,'createSubObjects') ###(
1530    def createSubObjects(self):
1531        """make the student a member"""
1532        dp = {'Title': 'Personal Data'}
1533        app_doc = self.application.getContent()
1534        names = app_doc.jamb_lastname.split()
1535        if len(names) == 3:
1536            dp['firstname'] = names[0].capitalize()
1537            dp['middlename'] = names[1].capitalize()
1538            dp['lastname'] = names[2].capitalize()
1539        elif len(names) == 2:
1540            dp['firstname'] = names[0].capitalize()
1541            dp['lastname'] = names[1].capitalize()
1542        else:
1543            dp['lastname'] = app_doc.jamb_lastname
1544        dp['sex'] = app_doc.jamb_sex == 'F'
1545        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
1546        proxy = self.aq_parent
1547        proxy.invokeFactory('StudentPersonal','personal')
1548        per = proxy.personal
1549        per_doc = per.getContent()
1550        per_doc.edit(mapping = dp)
[927]1551        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
[764]1552        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]1553
[511]1554###)
1555
[57]1556InitializeClass(Student)
1557
1558def addStudent(container, id, REQUEST=None, **kw):
1559    """Add a Student."""
1560    ob = Student(id, **kw)
1561    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1562
1563###)
[91]1564
[639]1565class StudentAccommodation(CPSDocument): ###(
1566    """
1567    WAeUP Student container for the various student data
1568    """
1569    meta_type = 'StudentAccommodation'
1570    portal_type = meta_type
1571    security = ClassSecurityInfo()
1572
1573    security.declareProtected(View,"Title")
1574    def Title(self):
1575        """compose title"""
1576        content = self.getContent()
1577        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
1578        return "Accommodation Data for Session %s" % content.session
1579
1580
1581InitializeClass(StudentAccommodation)
1582
1583def addStudentAccommodation(container, id, REQUEST=None, **kw):
1584    """Add a Students personal data."""
1585    ob = StudentAccommodation(id, **kw)
1586    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1587
1588###)
1589
[89]1590class StudentPersonal(CPSDocument): ###(
1591    """
[154]1592    WAeUP Student container for the various student data
[89]1593    """
1594    meta_type = 'StudentPersonal'
1595    portal_type = meta_type
1596    security = ClassSecurityInfo()
[152]1597
1598    security.declareProtected(View,"Title")
1599    def Title(self):
1600        """compose title"""
1601        content = self.getContent()
[364]1602        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
1603        return "Personal Data"
[152]1604
[154]1605
[89]1606InitializeClass(StudentPersonal)
1607
1608def addStudentPersonal(container, id, REQUEST=None, **kw):
1609    """Add a Students personal data."""
1610    ob = StudentPersonal(id, **kw)
1611    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1612
1613###)
1614
[423]1615class StudentClearance(CPSDocument): ###(
1616    """
1617    WAeUP Student container for the various student data
1618    """
1619    meta_type = 'StudentClearance'
1620    portal_type = meta_type
1621    security = ClassSecurityInfo()
1622
1623    security.declareProtected(View,"Title")
1624    def Title(self):
1625        """compose title"""
1626        content = self.getContent()
[840]1627        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
1628        return "Clearance/Eligibility Record"
[423]1629
1630
1631InitializeClass(StudentClearance)
1632
1633def addStudentClearance(container, id, REQUEST=None, **kw):
1634    """Add a Students personal data."""
1635    ob = StudentClearance(id, **kw)
1636    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1637
1638###)
1639
[454]1640class StudentStudyLevel(CPSDocument): ###(
1641    """
1642    WAeUP Student container for the various student data
1643    """
1644    meta_type = 'StudentStudyLevel'
1645    portal_type = meta_type
1646    security = ClassSecurityInfo()
1647
1648    security.declareProtected(View,"Title")
1649    def Title(self):
1650        """compose title"""
1651        return "Level %s" % self.aq_parent.getId()
1652
[723]1653##    security.declarePublic("gpa")
1654##    def gpa(self):
1655##        """calculate the gpa"""
1656##        sum = 0
1657##        course_count = 0
1658##        for sc in self.objectValues():
1659##            result = sc.getContent()
1660##            if not result.grade:
1661##                continue
1662##            res = self.portal_catalog({'meta_type': 'Course',
1663##                                          'id': sc.aq_parent.id})
1664##            if len(res) != 1:
1665##                continue
1666##            course = res[0].getObject().getContent()
1667##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
1668##            course_count += 1
1669##        if course_count:
1670##            return sum/course_count
1671##        return 0.0
[472]1672
[454]1673InitializeClass(StudentStudyLevel)
1674
1675def addStudentStudyLevel(container, id, REQUEST=None, **kw):
1676    """Add a Students personal data."""
1677    ob = StudentStudyLevel(id, **kw)
1678    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1679
1680###)
1681
[362]1682class StudentStudyCourse(CPSDocument): ###(
1683    """
1684    WAeUP Student container for the various student data
1685    """
1686    meta_type = 'StudentStudyCourse'
1687    portal_type = meta_type
1688    security = ClassSecurityInfo()
1689
[364]1690    security.declareProtected(View,"Title")
1691    def Title(self):
1692        """compose title"""
1693        content = self.getContent()
[453]1694        return "Study Course"
[362]1695
1696
1697InitializeClass(StudentStudyCourse)
1698
1699def addStudentStudyCourse(container, id, REQUEST=None, **kw):
1700    """Add a Students personal data."""
1701    ob = StudentStudyCourse(id, **kw)
1702    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1703
1704###)
1705
[472]1706class StudentApplication(CPSDocument): ###(
[179]1707    """
1708    WAeUP Student container for the various student data
1709    """
[472]1710    meta_type = 'StudentApplication'
[179]1711    portal_type = meta_type
1712    security = ClassSecurityInfo()
1713
[181]1714    security.declareProtected(View,"Title")
1715    def Title(self):
1716        """compose title"""
[472]1717        return "Application Data"
[179]1718
[181]1719
[472]1720InitializeClass(StudentApplication)
[179]1721
[472]1722def addStudentApplication(container, id, REQUEST=None, **kw):
[179]1723    """Add a Students eligibility data."""
[472]1724    ob = StudentApplication(id, **kw)
[179]1725    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]1726###)
[179]1727
[758]1728class StudentPume(CPSDocument): ###(
1729    """
1730    WAeUP Student container for the various student data
1731    """
1732    meta_type = 'StudentPume'
1733    portal_type = meta_type
1734    security = ClassSecurityInfo()
1735
1736    security.declareProtected(View,"Title")
1737    def Title(self):
1738        """compose title"""
1739        return "PUME Results"
1740
1741
1742InitializeClass(StudentPume)
1743
1744def addStudentPume(container, id, REQUEST=None, **kw):
1745    """Add a Students PUME data."""
1746    ob = StudentPume(id, **kw)
1747    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[179]1748###)
[181]1749
[565]1750##class StudentSemester(CPSDocument): ###(
1751##    """
1752##    WAeUP StudentSemester containing the courses and students
1753##    """
1754##    meta_type = 'StudentSemester'
1755##    portal_type = meta_type
1756##    security = ClassSecurityInfo()
1757##
1758##InitializeClass(StudentSemester)
1759##
1760##def addStudentSemester(container, id, REQUEST=None, **kw):
1761##    """Add a StudentSemester."""
1762##    ob = StudentSemester(id, **kw)
1763##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1764##
1765#####)
[464]1766
[758]1767##class Semester(CPSDocument): ###(
1768##    """
1769##    WAeUP Semester containing the courses and students
1770##    """
1771##    meta_type = 'Semester'
1772##    portal_type = meta_type
1773##    security = ClassSecurityInfo()
1774##
1775##InitializeClass(Semester)
1776##
1777##def addSemester(container, id, REQUEST=None, **kw):
1778##    """Add a Semester."""
1779##    ob = Semester(id, **kw)
1780##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1781##
1782#####)
[464]1783
1784class StudentCourseResult(CPSDocument): ###(
[89]1785    """
[464]1786    WAeUP StudentCourseResult
[89]1787    """
[464]1788    meta_type = 'StudentCourseResult'
[89]1789    portal_type = meta_type
1790    security = ClassSecurityInfo()
[472]1791
[454]1792    def getCourseEntry(self,cid):
[723]1793        res = self.portal_catalog({'meta_type': "Course",
[454]1794                                           'id': cid})
1795        if res:
1796            return res[-1]
1797        else:
1798            return None
[154]1799
[454]1800    security.declareProtected(View,"Title")
1801    def Title(self):
1802        """compose title"""
[723]1803        cid = self.aq_parent.getId()
[454]1804        ce = self.getCourseEntry(cid)
1805        if ce:
1806            return "%s" % ce.Title
1807        return "No course with id %s" % cid
[152]1808
[464]1809InitializeClass(StudentCourseResult)
[454]1810
[464]1811def addStudentCourseResult(container, id, REQUEST=None, **kw):
1812    """Add a StudentCourseResult."""
1813    ob = StudentCourseResult(id, **kw)
[89]1814    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]1815###)
1816
[579]1817# Backward Compatibility StudyLevel
1818
1819from Products.WAeUP_SRP.Academics import StudyLevel
1820
1821from Products.WAeUP_SRP.Academics import addStudyLevel
1822
Note: See TracBrowser for help on using the repository browser.