source: WAeUP_SRP/trunk/Students.py @ 971

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

modified pumeresults upload to update results
filename must be pup_update
IMPORTANT the heading must be the same as in the first upload.
Resolved PUME Results contains a different heading.
Import of admitted Students with pictures
students_catalog created
searchStudents speedup

  • Property svn:keywords set to Id
File size: 52.9 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 971 2006-11-30 19:31:01Z 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
[959]23MAX_TRANS = 100
[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 = []
271        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
272        no_import.append('%s' % s)
273        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
274                    '\n'.join(no_import))
275        no_import = []
276        logger = logging.getLogger('%s_import' % name)
277        starttime = DateTime.now()
278        logger.info('Start loading from %s.csv' % name)
279        try:
280            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
281        except:
282            logger.error('Error reading %s.csv' % name)
283            return
284        pume = self.portal_pumeresults
285        format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
286        eduplicate = '"dupplicate",%s' % format
287        for jamb in result:
288            dict = {}
289            #set_trace()
290            for f,fn in csv_d.items():
291                dict[f] = jamb.get(csv_d[f])
[971]292            res = pume(jamb_reg_no=jamb.get(csv_d['jamb_reg_no']))
293            if len(res) > 0:
294                if update:
295                    pume.modifyRecord(**dict)
296                else:
297                    data = res[0]
298                    if data.name != jamb.get(csv_d['name']):
299                        #set_trace()
300                        logger.info(eduplicate % jamb)
301                        #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
302                        #logger.info(em)
303                        dd = {}
304                        for f,fn in csv_d.items():
305                            dd[fn] = getattr(data,f)
306                        no_import.append(eduplicate % dd)
307                        no_import.append(eduplicate % jamb)
308                    continue
[966]309            try:
310                pume.addRecord(**dict)
311            except ValueError:
312                logger.info(eduplicate % jamb)
313                #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
314                #logger.info(em)
315                no_import.append(eduplicate % jamb)
316        logger.info('End loading from %s.csv' % name)
317        if len(no_import) > 1:
318            open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
319            '\n'.join(no_import))
320        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[971]321    ###)
[966]322
323    security.declareProtected(ModifyPortalContent,"createNewStudents")###(
324    def createNewStudents(self):
[742]325        """load Fulltime Studentdata from CSV values"""
326        import transaction
327        import random
[971]328        #from pdb import set_trace
[763]329        wftool = self.portal_workflow
[757]330        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
[971]331        csv_d = {'jamb_reg_no': "RegNumber",
[958]332                 'jamb_lastname': "Name",
[971]333                 'session': "Session",
334                 'pume_tot_score': "PUME SCORE",
335                 'jamb_score': "JambScore",
[958]336                 'jamb_sex': "Sex",
[971]337                 'jamb_state': "State",
338                 'jamb_first_cos': "AdminCourse",
339                 'faculty': "AdminFaculty",
340                 'course_code': "AdmitCoscode",
341                 'stud_status':"AdmitStatus",
342                 'department': "AdmitDept",
343                 'jamb_lga': "LGA",
344                 'app_email': "email",
[958]345                 }
346        csv_fields = [f[1] for f in csv_d.items()]
347        tr_count = 0
[961]348        total = 0
[958]349        #name = 'pume_results'
[971]350        name = 'Admitted'
[958]351        no_import = []
352        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
[971]353        no_import.append('"Error",%s' % s)
354        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
355        no_certificate = "no certificate %s" % format
[966]356        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
357                    '\n'.join(no_import))
[958]358        logger = logging.getLogger('%s_import' % name)
359        logger.info('Start loading from %s.csv' % name)
[971]360        l = self.portal_catalog({'meta_type': "Certificate"})
361        certs = {}
362        cert_docs = {}
363        for f in l:
364            certs[f.getId] = f.getObject().getContent()
[958]365        try:
366            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
367        except:
368            logger.error('Error reading %s.csv' % name)
369            return
370        for jamb in result:
[971]371            jamb['Error'] = "Processing "
372            logger.info(format % jamb)
[958]373            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
374            res = self.portal_catalog({'portal_type': "StudentApplication",
[959]375                                     'SearchableText': jamb_reg_no })
[958]376            if res:
377                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
378                logger.info(em)
[971]379                jamb['Error'] = "Student exists"
[958]380                no_import.append(format % jamb)
381                continue
[971]382            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
383            if cert_id not in certs.keys():
[958]384                em = 'No Certificate with ID %s \n' % cert_id
385                logger.info(em)
[971]386                jamb['Error'] = "No Certificate %s" % cert_id
387                no_import.append( format % jamb)
[958]388                continue
[971]389            cert_doc = certs[cert_id]
390            catalog_entry = {}
391            catalog_entry['jamb_reg_no'] = jamb_reg_no
[958]392            jamb_name = jamb.get(csv_d['jamb_lastname'])
393            jamb_name.replace('>','')
[966]394            jamb_name.replace('<','')
[958]395            names = jamb_name.split()
396            letter = names[-1][0].upper()
397            sid = self.generateStudentId(letter)
398            not_created = True
399            while not_created:
400                try:
401                    students_folder.invokeFactory('Student', sid)
402                    not_created = False
403                except BadRequest:
404                    sid = self.generateStudentId(letter)
[971]405            catalog_entry['id'] = sid
[958]406            tr_count += 1
[961]407            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[958]408            student = getattr(self,sid)
409            student.manage_setLocalRoles(sid, ['Owner',])
410            student.invokeFactory('StudentPume','pume')
411            dp = {'Title': 'Pume Data'}
412            student.invokeFactory('StudentApplication','application')
413            da = {'Title': 'Application Data'}
414            da["jamb_lastname"] = jamb_name
415            da_fields = ('jamb_reg_no',
416                         'jamb_sex',
417                         #'jamb_state',
[966]418                         'jamb_score',
[958]419                         'jamb_first_cos',
420                         'jamb_sex',
[971]421                         'jamb_state',
422                         'jamb_lga',
423                         'app_email',
[958]424                         )
425            for f in da_fields:
426                da[f] = jamb.get(csv_d[f])
[971]427            catalog_entry['email'] = jamb.get(csv_d['app_email'])
[958]428            app = student.application
[971]429            app_doc = app.getContent()
430            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
431            #import pdb;pdb.set_trace()
432            if os.path.exists(picture):
433                file = open(picture)
434                img = PIL.Image.open(file)
435                img.thumbnail((150,200),
436                              resample=PIL.Image.ANTIALIAS)
437                # We now need a buffer to write to. It can't be the same
438                # as the inbuffer as the PNG writer will write over itself.
439                outfile = StringIO()
440                img.save(outfile, format=img.format)
441                app_doc.manage_addFile('passport',
442                                       file=outfile,
443                                       title="%s.jpg" % jamb_reg_no)
[958]444            app.getContent().edit(mapping=da)
445            app.manage_setLocalRoles(sid, ['Owner',])
446            #wftool.doActionFor(app,'close')
447            dp_fields = (
448                         #'pume_eng_score',
449                         #'pume_gen_score',
450                         'pume_tot_score',
451                         )
[964]452            dp['pume_tot_score'] = jamb.get(csv_d['pume_tot_score']) or "No Option Shaded"
[958]453            pume = student.pume
454            pume.getContent().edit(mapping=dp)
455            #wftool.doActionFor(pume,'close')
456            pume.manage_setLocalRoles(sid, ['Owner',])
[966]457            #student.getContent().createSubObjects()
458            dp = {}
459            if len(names) == 3:
460                dp['firstname'] = names[0].capitalize()
461                dp['middlename'] = names[1].capitalize()
462                dp['lastname'] = names[2].capitalize()
463            elif len(names) == 2:
464                dp['firstname'] = names[0].capitalize()
[971]465                dp['middlename'] = ''
[966]466                dp['lastname'] = names[1].capitalize()
467            else:
[971]468                dp['firstname'] = ''
469                dp['middlename'] = ''
[966]470                dp['lastname'] = jamb_name
471            dp['sex'] = jamb.get(csv_d['jamb_sex']) == 'F'
[971]472            catalog_entry['sex'] = dp['sex']
473            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
[966]474            student.invokeFactory('StudentPersonal','personal')
475            per = student.personal
476            per_doc = per.getContent()
477            per_doc.edit(mapping = dp)
478            per.manage_setLocalRoles(sid, ['Owner',])
[958]479            if jamb.get(csv_d['stud_status']) == "Admitted":
480                wftool.doActionFor(student,'pume_pass')
481                wftool.doActionFor(student,'admit')
482            else:
483                wftool.doActionFor(student,'pume_fail')
484                wftool.doActionFor(student,'reject_admission')
485                continue
[964]486            #
[966]487            # Clearance
488            #
489            student.invokeFactory('StudentClearance','clearance')
490            #wftool.doActionFor(student.clearance,'open')
491            dp = {'Title': 'Clearance/Eligibility Record'}
492            student.clearance.manage_setLocalRoles(sid, ['Owner',])
493            #
[964]494            # Study Course
495            #
[958]496            student.invokeFactory('StudentStudyCourse','study_course')
497            study_course = student.study_course
498            dsc = {}
499            from_certificate = ['title',
500                               'max_elect',
501                               'max_pass',
502                               'n_core',
503                               'nr_years',
504                               'probation_credits',
505                               'promotion_credits',
506                               'start_level',
507                              ]
508            for f in from_certificate:
509                dsc[f] = getattr(cert_doc,f)
[971]510            dsc['faculty'] = jamb.get(csv_d['faculty'])
511            dsc['department'] = jamb.get(csv_d['department'])
512            catalog_entry['faculty'] = jamb.get(csv_d['faculty'])
513            catalog_entry['department'] = jamb.get(csv_d['department'])
514            catalog_entry['course'] = cert_id
515            catalog_entry['level'] = getattr(cert_doc,'start_level')
[958]516            dsc['study_course'] = cert_id
[971]517            dsc['entry_session'] = jamb.get(csv_d['session'])
[958]518            study_course.getContent().edit(mapping=dsc)
[971]519            self.students_catalog.addRecord(**catalog_entry)
520            if tr_count > 1000:
[966]521                if len(no_import) > 1:
522                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
523                             '\n'.join(no_import))
524                    no_import = []
[961]525                em = '%d transactions commited\n' % tr_count
[958]526                transaction.commit()
527                logger.info(em)
[961]528                total += tr_count
[958]529                tr_count = 0
530        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
531    ###)
532
533    security.declareProtected(ModifyPortalContent,"OLDloadPumeResultsFromCSV")###(
534    def OLDloadPumeResultsFromCSV(self):
535        """load Fulltime Studentdata from CSV values"""
536        import transaction
537        import random
538        wftool = self.portal_workflow
539        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
540        csv_d = {'jamb_reg_no': "JAMBRegno",
541                 'jamb_lastname': "Name",
[757]542                 'pume_options': "Options",
543                 'session': "Session",
544                 'days': "Days",
545                 'response': "Responce",
546                 'wrong': "Wrong",
547                 'pume_eng_score': "EngScore",
[775]548                 'pume_gen_score': "GenScore",
[958]549                 'pume_tot_score': "Score",
[757]550                 'batch': "Batch",
551                 'serial': "SerialNo",
552                 'jamb_score': "JambScore",
553                 'omitted':"Omitted",
554                 'search_key': "SearchKey",
555                 'jamb_sex': "Sex",
556                 'fac1': "Fac1",
557                 'fac2': "Fac2",
558                 'jamb_first_cos': "CourseofStudy",
559                 'stud_status':"StudStatus",
560                 'registered': "Registered",
561                 'jamb_state': "State",
562                 'eng_fail': "EngFail",
563                 'gen_fail': "GenFail",
564                 'un_ans_eng': "UnAnsEng",
565                 'un_ans_eng': "UnAnsGen",
566                 'total_ans': "TotalUnAns",
567                 'dept': "Dept",
568                 'jamb_second_cos': "Course2",
569                 'jamb_third_cos': "course3",
570                 }
571        csv_fields = [f[1] for f in csv_d.items()]
[742]572        tr_count = 0
573        name = 'pume_results'
[757]574        no_import = []
575        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
576        no_import.append('%s\n' % s)
[742]577        logger = logging.getLogger('%s_import' % name)
578        logger.info('Start loading from %s.csv' % name)
579        try:
[757]580            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[742]581        except:
582            logger.error('Error reading %s.csv' % name)
583            return
[757]584        for jamb in result:
585            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
586            processing = "processing %s" % format
587            logger.info(processing % jamb)
588            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
[763]589            #import pdb;pdb.set_trace()
590            res = self.portal_catalog({'portal_type': "StudentApplication",
[757]591                                     'jamb_reg_no': jamb_reg_no })
592            if res:
593                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
[742]594                logger.info(em)
[757]595                no_import.append(em)
596                no_import.append(format % jamb)
[742]597                continue
[785]598            cert_id = jamb.get(csv_d['jamb_first_cos']).upper()
599            res = self.portal_catalog({'portal_type': "Certificate",
600                                     'id': cert_id })
601            if len(res) < 1:
602                em = 'No Certificate with ID %s \n' % cert_id
603                logger.info(em)
604                no_import.append(em)
605                no_import.append(format % jamb)
606                continue
607            cert = res[0].getObject()
608            cert_path = res[0].getPath()
609            cert_doc = cert.getContent()
[757]610            jamb_name = jamb.get(csv_d['jamb_lastname'])
611            jamb_name.replace('>','')
612            names = jamb_name.split()
613            letter = names[-1][0].upper()
614            sid = self.generateStudentId(letter)
615            not_created = True
616            while not_created:
617                try:
618                    students_folder.invokeFactory('Student', sid)
619                    not_created = False
620                except BadRequest:
621                    sid = self.generateStudentId(letter)
622            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
623            student = getattr(self,sid)
624            student.manage_setLocalRoles(sid, ['Owner',])
[766]625            student.invokeFactory('StudentClearance','clearance')
[775]626            #wftool.doActionFor(student.clearance,'open')
[840]627            dp = {'Title': 'Clearance/Eligibility Record'}
[766]628            student.clearance.manage_setLocalRoles(sid, ['Owner',])
[763]629            student.invokeFactory('StudentPume','pume')
630            dp = {'Title': 'Pume Data'}
[757]631            student.invokeFactory('StudentApplication','application')
632            da = {'Title': 'Application Data'}
633            da["jamb_lastname"] = jamb_name
634            da_fields = ('jamb_reg_no',
635                         'jamb_sex',
636                         'jamb_state',
637                         'jamb_score',
638                         'jamb_first_cos',
639                         'jamb_sex',
640                         'jamb_state',
641                         'jamb_first_cos',
642                         'jamb_second_cos',
643                         )
[763]644            for f in da_fields:
645                da[f] = jamb.get(csv_d[f])
[757]646            app = student.application
[763]647            app.getContent().edit(mapping=da)
[757]648            app.manage_setLocalRoles(sid, ['Owner',])
[780]649            #wftool.doActionFor(app,'close')
[763]650            dp_fields = (
651                         'pume_eng_score',
[764]652                         'pume_gen_score',
[763]653                         'pume_tot_score',
654                         )
655            for f in dp_fields:
[775]656                dp[f] = float(jamb.get(csv_d[f]))
[765]657            pume = student.pume
658            pume.getContent().edit(mapping=dp)
[780]659            #wftool.doActionFor(pume,'close')
[763]660            pume.manage_setLocalRoles(sid, ['Owner',])
[785]661            #
662            # Study Course
663            #
664            student.invokeFactory('StudentStudyCourse','study_course')
665            study_course = student.study_course
666            dsc = {}
667            from_certificate = ['title',
668                               'max_elect',
669                               'max_pass',
670                               'n_core',
671                               'nr_years',
672                               'probation_credits',
673                               'promotion_credits',
674                               'start_level',
675                              ]
676            for f in from_certificate:
677                dsc[f] = getattr(cert_doc,f)
678            cpl = cert_path.split('/')
679            dsc['faculty'] = cpl[-4]
680            dsc['department'] = cpl[-3]
681            dsc['study_course'] = cert_id
682            dsc['entry_session'] = jamb.get(csv_d['session'])
683            study_course.getContent().edit(mapping=dsc)
[757]684            student.getContent().createSubObjects()
[775]685            if dp['pume_tot_score']>49:
[780]686                wftool.doActionFor(student,'pume_pass')
[785]687                wftool.doActionFor(student,'admit')
[775]688            else:
[780]689                wftool.doActionFor(student,'pume_fail')
[790]690                wftool.doActionFor(student,'reject_admission')
[757]691            if len(no_import) > 1:
692                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
693                     '\n'.join(no_import))
[742]694        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
695    ###)
696
[398]697    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
[396]698    def loadFullTimeStudentsResultsFromCSV(self):
699        """load Fulltime Studentdata from CSV values"""
700        #return
[723]701        level_wf_actions = {}
702        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
703        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
[727]704        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
705        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
[398]706        import transaction
[723]707        wftool = self.portal_workflow
[398]708        tr_count = 0
709        name = 'short_full_time_results_2004_2005'
[396]710        no_import = False
711        if not no_import:
712            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
713            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
714        logger = logging.getLogger('%s_import' % name)
715        logger.info('Start loading from %s.csv' % name)
716        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
717        try:
718            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
719        except:
720            logger.error('Error reading %s.csv' % name)
721            return
[398]722        l = self.portal_catalog({'meta_type': "Course"})
723        courses = {}
724        for c in l:
725            courses[c.id] = c.getObject()
[723]726        level_changed = False
727        student_changed = False
728        sid = ''
729        #import pdb;pdb.set_trace()
[396]730        for result in results:
[723]731            temp_sid = result.get('Matnumber')
732            if temp_sid != sid:
733                student_changed = True
734                res = self.portal_catalog({'meta_type': "StudentClearance",
735                                         'SearchableText': temp_sid })
736                if not res:
737                    em = 'Student with ID %(Matnumber)s not found\n' % result
738                    logger.info(em)
739                    no_import.write(em)
740                    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)
741                    continue
742                elif len(res) > 1:
743                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
744                    logger.info(em)
745                    no_import.write(em)
746                    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)
747                    continue
748                sid = temp_sid
749                sf = res[0].getObject().aq_parent
750                sc = getattr(sf,'study_course')
751                level = ''
752            else:
753                student_changed = False
[398]754            course = result.get('CosCode')
755            if course not in courses.keys():
756                em = 'Course with ID %(CosCode)s not found\n' % result
[396]757                logger.info(em)
758                no_import.write(em)
[398]759                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]760                continue
[727]761            course_doc = courses[course].getContent()
[723]762            temp_level = result.get('Level')
[742]763            student_id = sf.getId()
764            result['StudentId'] = student_id
[723]765            if temp_level != level:
766                try:
767                    int(temp_level)
768                except:
769                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
770                    logger.info(em)
771                    no_import.write(em)
772                    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)
773                    continue
[727]774                level_changed = True
775                if 'dlev' in vars().keys():
[723]776                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
777                level = temp_level
778                l = getattr(sc,level,None)
779                if l is None:
780                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
781                    sc.invokeFactory('StudentStudyLevel', level)
782                    l = getattr(sc, level)
[742]783                    l.manage_setLocalRoles(student_id, ['Owner',])
[723]784            else:
785                level_changed = False
786            cr = getattr(l,course,None)
787            if cr is None:
788                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
789                l.invokeFactory('StudentCourseResult',course)
790            cr = getattr(l,course)
791            dcr = {}
[727]792            from_course = ['title',
793                           'credits',
794                           'passmark',
795                           ]
796            for f in from_course:
797                dcr[f] = getattr(course_doc,f)
[454]798            dlev = {}
[723]799            dcr['ansbook'] = result.get('Ansbook')
800            dcr['semester'] = getInt(result.get('Semster'))
801            dcr['status'] = result.get('CosStuatus')
802            dcr['score'] = getInt(result.get('Score'))
[454]803            dlev['session'] = result.get('Session')
[723]804            dcr['carry_level'] = result.get('CarryLevel')
805            dcr['grade'] = result.get('Grade')
[725]806            dcr['weight'] = result.get('Weight')
[454]807            dlev['verdict'] = result.get('Verdict')
[725]808            dcr['import_id'] = result.get('id')
809            gpa = result.get('GPA').replace(',','.')
810            dlev['imported_gpa'] = getFloat(gpa)
[723]811            cr.getContent().edit(mapping = dcr)
[742]812            cr.manage_setLocalRoles(student_id, ['Owner',])
[454]813            l.getContent().edit(mapping = dlev)
[398]814            if tr_count > MAX_TRANS:
815                transaction.commit()
816                tr_count = 0
817            tr_count += 1
[723]818            wftool.doActionFor(cr,'close')
819        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
[681]820        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[426]821
[398]822###)
[396]823
[457]824    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
825    def loadJAMBFromCSV(self):
826        """load JAMB data from CSV values"""
827        #return
828        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
829        import transaction
830        tr_count = 0
[572]831        name = 'SampleJAMBDataII'
[511]832        wftool = self.portal_workflow
[457]833        no_import = False
834        if not no_import:
835            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
836            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')
837        logger = logging.getLogger('%s_import' % name)
838        logger.info('Start loading from %s.csv' % name)
839        try:
840            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
841        except:
842            logger.error('Error reading %s.csv' % name)
843            return
844        for jamb in result:
845            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)
846            jamb_reg_no = jamb.get('REG-NO')
[472]847            res = self.portal_catalog({'meta_type': "StudentApplication",
[457]848                                     'jamb_reg_no': jamb_reg_no })
849            if res:
850                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
851                logger.info(em)
852                no_import.write(em)
853                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)
854                continue
[511]855            jamb_name = jamb.get("NAME")
[584]856            jamb_name.replace('>','')
[511]857            names = jamb_name.split()
858            letter = names[-1][0].upper()
[714]859            sid = self.generateStudentId(letter)
[457]860            not_created = True
861            while not_created:
862                try:
863                    students_folder.invokeFactory('Student', sid)
864                    not_created = False
865                except BadRequest:
[714]866                    sid = self.generateStudentId(letter)
[457]867            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
[511]868            student = getattr(self,sid)
[519]869            student.manage_setLocalRoles(sid, ['Owner',])
[511]870            student.invokeFactory('StudentApplication','application')
[472]871            da = {'Title': 'Application Data'}
[457]872            da["jamb_reg_no"] = jamb.get("REG-NO")
[511]873            da["jamb_lastname"] = jamb_name
[457]874            da["jamb_sex"] = jamb.get("SEX")
875            da["jamb_state"] = jamb.get("STATE")
876            da["jamb_lga"] = jamb.get("LGA")
877            da["jamb_score"] = jamb.get("AGGREGATE")
878            da["jamb_first_cos"] = jamb.get("COURSE1")
879            da["jamb_second_cos"] = jamb.get("COURSE2")
880            da["jamb_first_uni"] = jamb.get("UNIV1")
881            da["jamb_second_uni"] = jamb.get("UNIV2")
[511]882            app = student.application
883            app_doc = app.getContent()
884            app_doc.edit(mapping=da)
[658]885            #wftool.doActionFor(app,'open',dest_container=app)
[511]886            app.manage_setLocalRoles(sid, ['Owner',])
887            student.getContent().createSubObjects()
[457]888        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
889    ###)
[426]890
[472]891
[511]892    security.declareProtected(View,"fixOwnership")
893    def fixOwnership(self):
894        """fix Ownership"""
895        for s in self.portal_catalog(meta_type = 'Student'):
896            student = s.getObject()
897            sid = s.getId
898            import pdb;pdb.set_trace()
899            student.application.manage_setLocalRoles(sid, ['Owner',])
900            student.personal.manage_setLocalRoles(sid, ['Owner',])
[603]901
[364]902    security.declareProtected(View,"Title")
903    def Title(self):
904        """compose title"""
[382]905        return "Student Section"
[361]906
[714]907    def generateStudentId(self,letter): ###(
908        import random
909        r = random
910        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
911            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
912        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
913        sid = "%c%d" % (letter,r.randint(99999,1000000))
914        while hasattr(students, sid):
915            sid = "%c%d" % (letter,r.randint(99999,1000000))
[758]916        return sid
[714]917        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
918    ###)
919
[361]920InitializeClass(StudentsFolder)
921
922def addStudentsFolder(container, id, REQUEST=None, **kw):
923    """Add a Student."""
924    ob = StudentsFolder(id, **kw)
925    return CPSBase_adder(container, ob, REQUEST=REQUEST)
926###)
927
[57]928class Student(CPSDocument): ###(
929    """
[154]930    WAeUP Student container for the various student data
[57]931    """
932    meta_type = 'Student'
933    portal_type = meta_type
934    security = ClassSecurityInfo()
[154]935
[152]936    security.declareProtected(View,"Title")
937    def Title(self):
938        """compose title"""
[153]939        reg_nr = self.getId()[1:]
[362]940        data = getattr(self,'personal',None)
[152]941        if data:
942            content = data.getContent()
943            return "%s %s" % (content.firstname,content.lastname)
[472]944        data = getattr(self,'application',None)
[464]945        if data:
946            content = data.getContent()
947            return "%s" % (content.jamb_lastname)
[152]948        return self.title
[154]949
[511]950    security.declarePrivate('makeStudentMember') ###(
951    def makeStudentMember(self,sid,password='uNsEt'):
952        """make the student a member"""
953        membership = self.portal_membership
[603]954        membership.addMember(sid,
[511]955                             password ,
956                             roles=('Member',
957                                     'Student',
[522]958                                     ),
[511]959                             domains='',
[904]960                             properties = {'memberareaCreationFlag': False,
961                                           'homeless': True},)
[511]962        member = membership.getMemberById(sid)
963        self.portal_registration.afterAdd(member, sid, password, None)
964        self.manage_setLocalRoles(sid, ['Owner',])
965
966###)
967
[764]968    security.declareProtected(View,'createSubObjects') ###(
969    def createSubObjects(self):
970        """make the student a member"""
971        dp = {'Title': 'Personal Data'}
972        app_doc = self.application.getContent()
973        names = app_doc.jamb_lastname.split()
974        if len(names) == 3:
975            dp['firstname'] = names[0].capitalize()
976            dp['middlename'] = names[1].capitalize()
977            dp['lastname'] = names[2].capitalize()
978        elif len(names) == 2:
979            dp['firstname'] = names[0].capitalize()
980            dp['lastname'] = names[1].capitalize()
981        else:
982            dp['lastname'] = app_doc.jamb_lastname
983        dp['sex'] = app_doc.jamb_sex == 'F'
984        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
985        proxy = self.aq_parent
986        proxy.invokeFactory('StudentPersonal','personal')
987        per = proxy.personal
988        per_doc = per.getContent()
989        per_doc.edit(mapping = dp)
[927]990        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
[764]991        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]992
[511]993###)
994
[57]995InitializeClass(Student)
996
997def addStudent(container, id, REQUEST=None, **kw):
998    """Add a Student."""
999    ob = Student(id, **kw)
1000    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1001
1002###)
[91]1003
[639]1004class StudentAccommodation(CPSDocument): ###(
1005    """
1006    WAeUP Student container for the various student data
1007    """
1008    meta_type = 'StudentAccommodation'
1009    portal_type = meta_type
1010    security = ClassSecurityInfo()
1011
1012    security.declareProtected(View,"Title")
1013    def Title(self):
1014        """compose title"""
1015        content = self.getContent()
1016        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
1017        return "Accommodation Data for Session %s" % content.session
1018
1019
1020InitializeClass(StudentAccommodation)
1021
1022def addStudentAccommodation(container, id, REQUEST=None, **kw):
1023    """Add a Students personal data."""
1024    ob = StudentAccommodation(id, **kw)
1025    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1026
1027###)
1028
[89]1029class StudentPersonal(CPSDocument): ###(
1030    """
[154]1031    WAeUP Student container for the various student data
[89]1032    """
1033    meta_type = 'StudentPersonal'
1034    portal_type = meta_type
1035    security = ClassSecurityInfo()
[152]1036
1037    security.declareProtected(View,"Title")
1038    def Title(self):
1039        """compose title"""
1040        content = self.getContent()
[364]1041        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
1042        return "Personal Data"
[152]1043
[154]1044
[89]1045InitializeClass(StudentPersonal)
1046
1047def addStudentPersonal(container, id, REQUEST=None, **kw):
1048    """Add a Students personal data."""
1049    ob = StudentPersonal(id, **kw)
1050    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1051
1052###)
1053
[423]1054class StudentClearance(CPSDocument): ###(
1055    """
1056    WAeUP Student container for the various student data
1057    """
1058    meta_type = 'StudentClearance'
1059    portal_type = meta_type
1060    security = ClassSecurityInfo()
1061
1062    security.declareProtected(View,"Title")
1063    def Title(self):
1064        """compose title"""
1065        content = self.getContent()
[840]1066        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
1067        return "Clearance/Eligibility Record"
[423]1068
1069
1070InitializeClass(StudentClearance)
1071
1072def addStudentClearance(container, id, REQUEST=None, **kw):
1073    """Add a Students personal data."""
1074    ob = StudentClearance(id, **kw)
1075    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1076
1077###)
1078
[454]1079class StudentStudyLevel(CPSDocument): ###(
1080    """
1081    WAeUP Student container for the various student data
1082    """
1083    meta_type = 'StudentStudyLevel'
1084    portal_type = meta_type
1085    security = ClassSecurityInfo()
1086
1087    security.declareProtected(View,"Title")
1088    def Title(self):
1089        """compose title"""
1090        return "Level %s" % self.aq_parent.getId()
1091
[723]1092##    security.declarePublic("gpa")
1093##    def gpa(self):
1094##        """calculate the gpa"""
1095##        sum = 0
1096##        course_count = 0
1097##        for sc in self.objectValues():
1098##            result = sc.getContent()
1099##            if not result.grade:
1100##                continue
1101##            res = self.portal_catalog({'meta_type': 'Course',
1102##                                          'id': sc.aq_parent.id})
1103##            if len(res) != 1:
1104##                continue
1105##            course = res[0].getObject().getContent()
1106##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
1107##            course_count += 1
1108##        if course_count:
1109##            return sum/course_count
1110##        return 0.0
[472]1111
[454]1112InitializeClass(StudentStudyLevel)
1113
1114def addStudentStudyLevel(container, id, REQUEST=None, **kw):
1115    """Add a Students personal data."""
1116    ob = StudentStudyLevel(id, **kw)
1117    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1118
1119###)
1120
[362]1121class StudentStudyCourse(CPSDocument): ###(
1122    """
1123    WAeUP Student container for the various student data
1124    """
1125    meta_type = 'StudentStudyCourse'
1126    portal_type = meta_type
1127    security = ClassSecurityInfo()
1128
[364]1129    security.declareProtected(View,"Title")
1130    def Title(self):
1131        """compose title"""
1132        content = self.getContent()
[453]1133        return "Study Course"
[362]1134
1135
1136InitializeClass(StudentStudyCourse)
1137
1138def addStudentStudyCourse(container, id, REQUEST=None, **kw):
1139    """Add a Students personal data."""
1140    ob = StudentStudyCourse(id, **kw)
1141    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1142
1143###)
1144
[472]1145class StudentApplication(CPSDocument): ###(
[179]1146    """
1147    WAeUP Student container for the various student data
1148    """
[472]1149    meta_type = 'StudentApplication'
[179]1150    portal_type = meta_type
1151    security = ClassSecurityInfo()
1152
[181]1153    security.declareProtected(View,"Title")
1154    def Title(self):
1155        """compose title"""
[472]1156        return "Application Data"
[179]1157
[181]1158
[472]1159InitializeClass(StudentApplication)
[179]1160
[472]1161def addStudentApplication(container, id, REQUEST=None, **kw):
[179]1162    """Add a Students eligibility data."""
[472]1163    ob = StudentApplication(id, **kw)
[179]1164    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]1165###)
[179]1166
[758]1167
1168class StudentPume(CPSDocument): ###(
1169    """
1170    WAeUP Student container for the various student data
1171    """
1172    meta_type = 'StudentPume'
1173    portal_type = meta_type
1174    security = ClassSecurityInfo()
1175
1176    security.declareProtected(View,"Title")
1177    def Title(self):
1178        """compose title"""
1179        return "PUME Results"
1180
1181
1182InitializeClass(StudentPume)
1183
1184def addStudentPume(container, id, REQUEST=None, **kw):
1185    """Add a Students PUME data."""
1186    ob = StudentPume(id, **kw)
1187    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[179]1188###)
[181]1189
[565]1190##class StudentSemester(CPSDocument): ###(
1191##    """
1192##    WAeUP StudentSemester containing the courses and students
1193##    """
1194##    meta_type = 'StudentSemester'
1195##    portal_type = meta_type
1196##    security = ClassSecurityInfo()
1197##
1198##InitializeClass(StudentSemester)
1199##
1200##def addStudentSemester(container, id, REQUEST=None, **kw):
1201##    """Add a StudentSemester."""
1202##    ob = StudentSemester(id, **kw)
1203##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1204##
1205#####)
[464]1206
[758]1207##class Semester(CPSDocument): ###(
1208##    """
1209##    WAeUP Semester containing the courses and students
1210##    """
1211##    meta_type = 'Semester'
1212##    portal_type = meta_type
1213##    security = ClassSecurityInfo()
1214##
1215##InitializeClass(Semester)
1216##
1217##def addSemester(container, id, REQUEST=None, **kw):
1218##    """Add a Semester."""
1219##    ob = Semester(id, **kw)
1220##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1221##
1222#####)
[464]1223
1224class StudentCourseResult(CPSDocument): ###(
[89]1225    """
[464]1226    WAeUP StudentCourseResult
[89]1227    """
[464]1228    meta_type = 'StudentCourseResult'
[89]1229    portal_type = meta_type
1230    security = ClassSecurityInfo()
[472]1231
[454]1232    def getCourseEntry(self,cid):
[723]1233        res = self.portal_catalog({'meta_type': "Course",
[454]1234                                           'id': cid})
1235        if res:
1236            return res[-1]
1237        else:
1238            return None
[154]1239
[454]1240    security.declareProtected(View,"Title")
1241    def Title(self):
1242        """compose title"""
[723]1243        cid = self.aq_parent.getId()
[454]1244        ce = self.getCourseEntry(cid)
1245        if ce:
1246            return "%s" % ce.Title
1247        return "No course with id %s" % cid
[152]1248
[464]1249InitializeClass(StudentCourseResult)
[454]1250
[464]1251def addStudentCourseResult(container, id, REQUEST=None, **kw):
1252    """Add a StudentCourseResult."""
1253    ob = StudentCourseResult(id, **kw)
[89]1254    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]1255###)
1256
[579]1257# Backward Compatibility StudyLevel
1258
1259from Products.WAeUP_SRP.Academics import StudyLevel
1260
1261from Products.WAeUP_SRP.Academics import addStudyLevel
1262
Note: See TracBrowser for help on using the repository browser.