source: WAeUP_SRP/trunk/Students.py @ 1596

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

cosmetic changes

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