source: WAeUP_SRP/trunk/Students.py @ 1708

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

new import function for createStudents,
catalog fields added

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