source: WAeUP_SRP/trunk/Students.py @ 967

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

created new catalog pumeresults for pumeresult checking
modified pume_anon_view and pume_anon_slip to use it.

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