source: WAeUP_SRP/trunk/Students.py @ 1709

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

added entry_levels dict

  • Property svn:keywords set to Id
File size: 78.4 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 1709 2007-04-25 16:06:28Z 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()
[1709]548        entry_levels = {'ume_ft':'100',
549                        'de_ft': '200',
550                        'ug_pt': '100',
551                        'de_pt': '200',
552                        'pg_ft': '700',
553                        'pg_pt': '700',
554                        }
[1707]555        csv_d = {'jamb_reg_no': "reg_no",
556                 'entry_mode': 'entry_mode',
557                 'jamb_firstname': "firstname",
558                 'jamb_middlename': "middlename",
559                 'jamb_lastname': "lastname",
560                 'jamb_sex': "sex",
561                 'jamb_state': "state",
562                 'birthday': "date_of_birth",
[1700]563                 'app_email': "email",
[1707]564                 'study_course': "study_course",
565                 'perm_address': "address",
[1700]566                 }
567        csv_fields = [f[1] for f in csv_d.items()]
568        tr_count = 0
569        total = 0
570        #name = 'pume_results'
571        name = 'Admitted'
572        no_import = []
573        s = ','.join(['"%s"' % fn for fn in csv_fields])
574        no_import.append('"Error",%s' % s)
575        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
576        no_certificate = "no certificate %s" % format
577        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write('\n'.join(no_import))
578        logger = logging.getLogger('Students.StudentsFolder.createNewStudents')
579        logger.info('Start loading from %s.csv' % name)
580        certs = {}
581        try:
[1707]582            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[1700]583        except:
584            logger.error('Error reading %s.csv' % name)
585            return
[1707]586        for result in results:
587            #result['Error'] = "Processing "
588            #logger.info(format % result)
589            jamb_reg_no = result.get(csv_d['jamb_reg_no'])
590            res = self.students_catalog(jamb_reg_no = jamb_reg_no)
[1700]591            if res:
592                em = 'Student with RegNo %s already exists\n' % jamb_reg_no
593                logger.info(em)
[1707]594                result['Error'] = "Student exists"
595                no_import.append(format % result)
[1700]596                continue
[1707]597            cert_id = makeCertificateCode(result.get(csv_d['study_course']))
[1700]598            if cert_id not in certs.keys():
[1707]599                res = self.portal_catalog(meta_type = "Certificate",id = cert_id)
600                if not res:
601                    em = 'No Certificate with ID %s \n' % cert_id
602                    logger.info(em)
603                    result['Error'] = "No Certificate %s" % cert_id
604                    no_import.append( format % result)
605                    continue
606                cert = res[0]
607                cert_path = cert.getPath().split('/')
608                certificate = certs[cert_id] = {'faculty': cert_path[-4],
609                                     'department': cert_path[-3]}
[1700]610            cert_doc = certs[cert_id]
611            catalog_entry = {}
612            catalog_entry['jamb_reg_no'] = jamb_reg_no
[1707]613            firstname = result.get(csv_d['jamb_firstname'])
614            middlename = result.get(csv_d['jamb_middlename'])
615            lastname = result.get(csv_d['jamb_lastname'])
616            sid = self.generateStudentId('x')
617            students_folder.invokeFactory('Student', sid)
[1700]618            catalog_entry['id'] = sid
619            tr_count += 1
620            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
621            student = getattr(self,sid)
622            student.manage_setLocalRoles(sid, ['Owner',])
623            student.invokeFactory('StudentApplication','application')
624            da = {'Title': 'Application Data'}
[1707]625            da["jamb_firstname"] = firstname
626            da["jamb_middlename"] = middlename
627            da["jamb_lastname"] = lastname
628            catalog_entry['entry_session'] = da["entry_session"] = self.getSessionId()[-2:]
629            catalog_entry['sex'] = sex = result.get(csv_d['jamb_sex']).startswith('F')
[1700]630            da_fields = ('jamb_reg_no',
631                         'jamb_sex',
632                         'jamb_state',
[1707]633                         'entry_mode',
[1700]634                         'app_email',
635                         )
636            for f in da_fields:
[1707]637                da[f] = result.get(csv_d[f])
638            catalog_entry['email'] = da['app_email']
639            catalog_entry['entry_mode'] = da['entry_mode']
[1709]640            catalog_entry['entry_level'] = da["entry_level"] = entry_levels.get(da['entry_mode'],'NA')
[1700]641            app = student.application
642            app_doc = app.getContent()
[1707]643            app.getContent().edit(mapping=da)
[1700]644            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
[1707]645            app.manage_setLocalRoles(sid, ['Owner',])
646            picture_id = da['jamb_reg_no'].replace('/','_')
647            file = None
648            for ext in ('jpg','JPG'):
649                picture ="%s/import/pictures/%s.%s" % (i_home,picture_id,ext)
650                if os.path.exists(picture):
651                    file = open(picture)
652                    break
653            if file is not None:
654                outfile = file.read()
[1700]655                app_doc.manage_addFile('passport',
656                                       file=outfile,
657                                       title="%s.jpg" % jamb_reg_no)
658            #wftool.doActionFor(app,'close')
659            dp = {}
[1707]660            dp['firstname'] = firstname
661            dp['middlename'] = middlename
662            dp['lastname'] = lastname
663            dp['email'] = da['app_email']
664            dp['sex'] = sex
[1700]665            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
666            student.invokeFactory('StudentPersonal','personal')
667            per = student.personal
668            per_doc = per.getContent()
669            per_doc.edit(mapping = dp)
670            per.manage_setLocalRoles(sid, ['Owner',])
[1707]671            wftool.doActionFor(student,'pume_pass')
672            wftool.doActionFor(student,'admit')
[1700]673            #
674            # Clearance
675            #
676            student.invokeFactory('StudentClearance','clearance')
677            #wftool.doActionFor(student.clearance,'open')
[1707]678            clearance = student.clearance
679            dc = {'Title': 'Clearance/Eligibility Record'}
680            clearance = student.clearance
681            date_str = result.get(csv_d['birthday'])
[1709]682            try:
683                date = DateTime.DateTime(date_str)
684            except:
685                #import pdb;pdb.set_trace()
686                date = None
[1707]687            dc['birthday'] = date
688            clearance.getContent().edit(mapping=dc)
689            clearance.manage_setLocalRoles(sid, ['Owner',])
[1700]690            #
691            # Study Course
692            #
693            student.invokeFactory('StudentStudyCourse','study_course')
694            study_course = student.study_course
695            dsc = {}
696            #catalog_entry['level'] = getattr(cert_doc,'start_level')
[1707]697            catalog_entry['session'] = dsc['current_session'] = da['entry_session']
[1709]698            catalog_entry['level'] = dsc['current_level'] = entry_levels.get(da['entry_mode'],'NA')
[1707]699            catalog_entry['mode'] = dsc['current_mode'] = da['entry_mode']
700            catalog_entry['course'] = dsc['study_course'] = cert_id
701            catalog_entry['faculty'] = certificate['faculty']
702            catalog_entry['department'] = certificate['department']
703            catalog_entry['verdict'] = dsc['current_verdict'] = 'NA'
704            catalog_entry['review_state'] = self.portal_workflow.getInfoFor(student,'review_state',None)
[1700]705            study_course.getContent().edit(mapping=dsc)
[1707]706            #import pdb;pdb.set_trace()
[1700]707            self.students_catalog.addRecord(**catalog_entry)
708            if tr_count > 10:
709                if len(no_import) > 0:
710                    open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
711                             '\n'.join(no_import) + "\n")
712                    no_import = []
713                em = '%d transactions commited\n' % tr_count
714                transaction.commit()
715                logger.info(em)
716                total += tr_count
717                tr_count = 0
718        open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
719                                                '\n'.join(no_import))
720        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
721    ###)
722
[1151]723    security.declareProtected(ModifyPortalContent,"importReturningStudents")###(
724    def importReturningStudents(self):
725        """load Returning Studentdata from CSV values"""
[1146]726        import transaction
727        import random
728        #from pdb import set_trace
729        wftool = self.portal_workflow
730        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
[1616]731        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
732        #students_folder = self.portal_url().getPortalObject().campus.students
[1146]733        tr_count = 1
734        total = 0
735        #name = 'pume_results'
[1151]736        name = 'Returning'
737        table = self.returning_import
[1146]738        no_import = []
739        imported = []
[1571]740        logger = logging.getLogger('Students.StudentsFolder.importReturningStudents')
[1146]741        try:
[1151]742            returning = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[1146]743        except:
744            logger.error('Error reading %s.csv' % name)
745            return
746        l = self.portal_catalog({'meta_type': "Certificate"})
747        certs = {}
748        cert_docs = {}
749        for f in l:
750            certs[f.getId] = f.getObject().getContent()
751        start = True
752        res = table()
753        regs = []
754        if len(res) > 0:
755            regs = [s.matric_no for s in res]
[1319]756        #import pdb;pdb.set_trace()
[1151]757        for student in returning:
[1146]758            if start:
759                start = False
[1571]760                logger.info('Start loading from %s.csv' % name)
[1319]761                s = ','.join(['"%s"' % fn for fn in student.keys()])
[1146]762                imported.append(s)
763                no_import.append('%s,"Error"' % s)
764                format = ','.join(['"%%(%s)s"' % fn for fn in student.keys()])
765                format_error = format + ',"%(Error)s"'
766                no_certificate = "no certificate %s" % format
[1319]767            student['matric_no'] = matric_no = student.get('matric_no').upper()
768            student['Mode_of_Entry'] = entry_mode = student.get('Mode of Entry').upper()
769            student['Permanent_Address'] = perm_address = student.get('Permanent Address')
[1168]770            if matric_no == '':
[1252]771                student['Error'] = "Empty matric_no"
[1146]772                no_import.append( format_error % student)
773                continue
[1168]774            if matric_no in regs or self.returning_import(matric_no = matric_no):
[1252]775                student['Error'] = "Duplicate"
[1146]776                no_import.append( format_error % student)
777                continue
778            cert_id = makeCertificateCode(student.get('Coursemajorcode'))
779            if cert_id not in certs.keys():
780                student['Error'] = "No Certificate %s" % cert_id
781                no_import.append( format_error % student)
782                continue
783            try:
784                table.addRecord(**student)
785            except ValueError:
[1252]786                student['Error'] = "Duplicate"
[1146]787                no_import.append( format_error % student)
788                continue
789            regs.append(student.get('matric_no'))
790            imported.append(format % student)
791            tr_count += 1
792            if tr_count > 1000:
793                if len(no_import) > 0:
794                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
[1151]795                             '\n'.join(no_import) + '\n')
[1146]796                    no_import = []
797                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
[1151]798                                            '\n'.join(no_import) + "\n")
799                imported = []
[1146]800                em = '%d transactions commited total %s\n' % (tr_count,total)
801                transaction.commit()
[1168]802                regs = []
[1146]803                logger.info(em)
804                total += tr_count
805                tr_count = 0
806        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
[1252]807                                            '\n'.join(imported))
[1146]808        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
809                                                '\n'.join(no_import))
810        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
811    ###)
812
[1529]813    security.declareProtected(ModifyPortalContent,"fixVerdicts")###(
814    def fixVerdicts(self,csv_file=None):
815        """fix wrong uploaded verdicts"""
816        import transaction
817        import random
818        wftool = self.portal_workflow
819        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
820        students_folder = self.portal_url.getPortalObject().campus.students
821        tr_count = 1
822        total = 0
823        if csv_file is None:
824            name = 'Verdicts'
825        else:
826            name = csv_file
827        st_cat = self.students_catalog
828        no_import = []
829        verdicts_voc = self.portal_vocabularies.verdicts
830        rverdicts = {}
831        for k,v in verdicts_voc.items():
832            rverdicts[v.upper()] = k
[1571]833        rverdicts['STUDENT ON PROBATION'] = 'C'
834        logger = logging.getLogger('Students.StudentsFolder.fixVerdicts')
[1529]835        try:
836            verdicts = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
837        except:
838            logger.error('Error reading %s.csv' % name)
839            return
840        start = True
841        #import pdb;pdb.set_trace()
842        for verdict in verdicts:
843            if start:
844                start = False
[1571]845                logger.info('Start loading from %s.csv' % name)
[1529]846                s = ','.join(['"%s"' % fn for fn in verdict.keys()])
847                no_import.append('%s,"Error"' % s)
848                format = ','.join(['"%%(%s)s"' % fn for fn in verdict.keys()])
849                format_error = format + ',"%(Error)s"'
850            matric_no = verdict.get('MAT NO')
851            if not matric_no:
852                continue
853            matric_no = matric_no.upper()
854            if matric_no == '':
855                continue
856            verdict_code = rverdicts.get(verdict.get('CATEGORY'),None)
857            if verdict_code is None:
858                continue
859            sres = st_cat(matric_no = matric_no)
860            if sres:
861                student_id = sres[0].id
862                student_obj = getattr(students_folder,student_id,None)
863                if student_obj:
864                    study_course = getattr(student_obj,'study_course',None)
865                    if study_course is None:
866                        verdict['Error'] = "Student did not yet log in"
867                        no_import.append( format_error % verdict)
868                        continue
[1571]869                st_cat.modifyRecord(id = student_id,
[1529]870                                    verdict=verdict_code)
[1571]871
[1529]872                dsc = {}
873                dsc['current_verdict'] = verdict_code
874                study_course.getContent().edit(mapping=dsc)
[1571]875            else:
[1577]876                verdict['Error'] = "Not found in students_catalog"
877                no_import.append( format_error % verdict)
[1571]878                continue
[1529]879            tr_count += 1
880            if tr_count > 1000:
881                if len(no_import) > 0:
882                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
883                             '\n'.join(no_import) + '\n')
884                    no_import = []
885                em = '%d transactions commited total %s\n' % (tr_count,total)
886                transaction.commit()
887                regs = []
888                logger.info(em)
889                total += tr_count
890                tr_count = 0
891        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
892                                                '\n'.join(no_import))
893        total += tr_count
894        em = '%d total transactions commited' % (total)
895        logger.info(em)
896        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
897    ###)
898
[1599]899    security.declareProtected(ModifyPortalContent,"fixAllNames")###(
[1601]900    def fixAllNames(self):
[1599]901        "fix all students names"
902        import transaction
903        response = self.REQUEST.RESPONSE
904        logger = logging.getLogger('fixAllNames')
905        logger.info('Start')
906        students = self.portal_catalog(portal_type='Student')
907        count = 0
908        total = 0
909        for student in students:
910            scat_res = self.students_catalog(id = student.getId)
911            if not scat_res:
912                self.students_catalog.addRecord(id = student.getId)
913                scat_res = self.students_catalog(id = student.getId)
914            student_entry = scat_res[0]
915            old_new = self.fixName(student,student_entry)
916            count += 1
[1602]917            response_write(response,'"%d","%s",%s' % (count + total,student_entry.id,old_new))
[1599]918            if count > 2000:
919                transaction.commit()
920                logger.info("%d transactions commited" % count)
921                total += count
922                count = 0
923    ###)
924
925    security.declareProtected(ModifyPortalContent,"fixName")###(
[1601]926    def fixName(self,student_brain, student_entry):
[1599]927        "fix the name of a student"
928        fix = "first"
929        if student_entry.get('name_fixed',None) == fix:
930            return "Name already fixed"
931        student_id = student_entry.id
[1601]932        new_student = student_entry.jamb_reg_no.startswith('6')
[1599]933        student_obj = student_brain.getObject()
934        personal = getattr(student_obj,'personal',None)
935        invalid = ''
936        if personal is None:
[1601]937            return '"%s","Returning","%s","%s"' % (invalid,student_entry.name,"not logged in")
[1599]938        per_doc = personal.getContent()
939        old_first = per_doc.firstname
940        old_middle = per_doc.middlename
941        old_last = per_doc.lastname
942        new_first = ''
943        new_middle = ''
944        new_last = ''
945        if new_student:
946            if not old_first and not old_middle and old_last:
947                new_names = [n.capitalize() for n in old_last.split()]
[1611]948                if len(new_names) > 1:
[1599]949                    old_first = new_names[0]
[1611]950                    old_last = new_names[-1]
951                    old_middle = ' '.join(new_names[1:-1])
952                else:
[1599]953                    old_last = new_names[0]
954                    old_first = ''
955                    old_middle = ''
[1611]956            if old_first:
957                new_first = old_first
[1599]958            if old_middle:
959                new_middle = old_middle
[1611]960            if old_last:
961                new_last = old_last
[1599]962            if old_first.find('<') != -1 or\
963               old_first.find('>') != -1 or\
964               old_middle.find('<') != -1 or\
965               old_middle.find('>') != -1 or\
966               old_last.find('<') != -1 or\
967               old_last.find('>') != -1:
968                   invalid = "invalid characters"
969        else:
[1611]970            new_first = old_first
971            if new_first.strip() == '-':
[1599]972                new_first = ''
[1611]973            new_middle = old_middle
974            if new_middle.strip() == '-':
[1599]975                new_middle = ''
[1611]976            new_last = old_last
977            if new_last.strip() == '-':
[1599]978                new_last = ''
[1611]979        name = "%(new_first)s %(new_middle)s %(new_last)s" % vars()
[1599]980        if new_student:
981            text = "New"
982        else:
983            text = "Returning"
[1601]984        old_new = '"%s","%s","%s","%s"' % (invalid,text,
[1599]985                                           student_entry.name,
986                                           name)
987        if not invalid:
988            self.students_catalog.modifyRecord(id = student_id,
989                                      name_fixed = fix,
990                                      name = name)
991            per_doc.edit(mapping = {'firstname' : new_first,
992                                'middlename' : new_middle,
993                                'lastname' : new_last,
994                                })
995        return old_new
996    ###)
997
[1319]998    security.declareProtected(ModifyPortalContent,"fixAllEntryModeForReturning")###(
999    def fixAllEntryModeForReturning(self):
1000        "read all Returning*.csv"
1001        ipath = "%s/import/" % i_home
1002        names = os.listdir(ipath)
1003        for name in names:
1004            head,tail = os.path.splitext(name)
1005            if head.startswith('Returning')\
1006               and tail == '.csv'\
1007               and name.find('imported') < 0:
1008                self.fixEntryModeForReturning(csv_file=head)
[1322]1009    ###)
[1386]1010
[1319]1011    security.declareProtected(ModifyPortalContent,"fixEntryModeForReturning")###(
1012    def fixEntryModeForReturning(self,csv_file=None):
1013        """load Returning Studentdata from CSV values"""
1014        import transaction
1015        import random
1016        wftool = self.portal_workflow
1017        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
1018        students_folder = self.portal_url.getPortalObject().campus.students
1019        tr_count = 1
1020        total = 0
1021        if csv_file is None:
1022            name = 'Returning'
1023        else:
1024            name = csv_file
1025        table = self.returning_import
1026        st_cat = self.students_catalog
1027        no_import = []
[1571]1028        logger = logging.getLogger('Students.StudentsFolder.fixEntryModeForReturning')
[1319]1029        try:
1030            returning = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1031        except:
1032            logger.error('Error reading %s.csv' % name)
1033            return
1034        start = True
1035        for student in returning:
1036            if start:
1037                start = False
[1571]1038                logger.info('Start loading from %s.csv' % name)
[1321]1039                s = ','.join(['"%s"' % fn for fn in student.keys()])
[1319]1040                no_import.append('%s,"Error"' % s)
1041                format = ','.join(['"%%(%s)s"' % fn for fn in student.keys()])
1042                format_error = format + ',"%(Error)s"'
1043            matric_no = student.get('matric_no')
1044            if not matric_no:
1045                continue
1046            matric_no = matric_no.upper()
1047            student['matric_no'] = matric_no
1048            if matric_no == '':
1049                continue
1050            if not table(matric_no = matric_no):
1051                student['Error'] = "Not imported yet"
1052                no_import.append( format_error % student)
1053                continue
1054            student_id = None
1055            app = None
1056            per = None
1057            if st_cat(matric_no = matric_no):
1058                student_id = st_cat(matric_no = matric_no)[0].id
[1322]1059                student_obj = getattr(students_folder,student_id,None)
1060                if student_obj:
1061                    app = getattr(student_obj,'application',None)
1062                    if app is not None:
1063                        app_doc = app.getContent()
1064                    per = getattr(student_obj,'personal',None)
1065                    if per is not None:
1066                        per_doc = per.getContent()
[1319]1067            student['Mode_of_Entry'] = entry_mode = student.get('Mode of Entry').upper()
1068            student['Permanent_Address'] = perm_address = student.get('Permanent Address')
[1322]1069            #import pdb;pdb.set_trace()
[1319]1070            if not entry_mode:
1071                student['Error'] = "'Mode of Entry' empty"
1072                no_import.append( format_error % student)
1073                continue
1074            try:
1075                table.modifyRecord(matric_no = matric_no,
1076                                   Mode_of_Entry = entry_mode,
1077                                   Permanent_Address = perm_address)
1078            except KeyError:
1079                student['Error'] = "Not found in returning_import"
1080                no_import.append( format_error % student)
1081                continue
1082            if student_id is not None:
1083                try:
1084                    st_cat.modifyRecord(id = student_id,
1085                                        entry_mode=entry_mode)
1086                except KeyError:
1087                    student['Error'] = "Not found in students_catalog"
1088                    no_import.append( format_error % student)
1089                    continue
1090            if app is not None:
1091                da = {}
1092                da['entry_mode'] = entry_mode
1093                app_doc.edit(mapping=da)
1094            if per is not None:
1095                dp = {}
[1350]1096                dp['perm_address'] = perm_address
[1319]1097                per_doc.edit(mapping=dp)
1098            tr_count += 1
1099            if tr_count > 1000:
1100                if len(no_import) > 0:
1101                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
1102                             '\n'.join(no_import) + '\n')
1103                    no_import = []
1104                em = '%d transactions commited total %s\n' % (tr_count,total)
1105                transaction.commit()
1106                regs = []
1107                logger.info(em)
1108                total += tr_count
1109                tr_count = 0
1110        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
1111                                                '\n'.join(no_import))
1112        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1113    ###)
[1289]1114
1115    security.declareProtected(ModifyPortalContent,"updateReturningStudents")###(
1116    def updateReturningStudents(self):
1117        """load and overwrite Returning Student Data from CSV values"""
1118        import transaction
1119        import random
1120        #from pdb import set_trace
1121        wftool = self.portal_workflow
1122        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
1123        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
1124        tr_count = 1
1125        total = 0
1126        #name = 'pume_results'
1127        name = 'Returning_update'
1128        table = self.returning_import
1129        no_import = []
1130        imported = []
[1571]1131        logger = logging.getLogger('Students.StudentsFolder.updateReturningStudents')
[1289]1132        try:
1133            returning = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1134        except:
1135            logger.error('Error reading %s.csv' % name)
1136            return
1137        l = self.portal_catalog({'meta_type': "Certificate"})
1138        certs = {}
1139        cert_docs = {}
1140        for f in l:
1141            certs[f.getId] = f.getObject().getContent()
1142        start = True
1143        res = table()
1144        regs = []
1145        if len(res) > 0:
1146            regs = [s.matric_no for s in res]
1147        for student in returning:
1148            if start:
1149                start = False
[1571]1150                logger.info('Start loading from %s.csv' % name)
[1321]1151                s = ','.join(['"%s"' % fn for fn in student.keys()])
[1289]1152                imported.append(s)
1153                no_import.append('%s,"Error"' % s)
1154                format = ','.join(['"%%(%s)s"' % fn for fn in student.keys()])
1155                format_error = format + ',"%(Error)s"'
1156                no_certificate = "no certificate %s" % format
1157            matric_no = student.get('matric_no').upper()
1158            student['matric_no'] = matric_no
1159            if matric_no == '':
1160                student['Error'] = "Empty matric_no"
1161                no_import.append( format_error % student)
1162                continue
1163#            if matric_no in regs or self.returning_import(matric_no = matric_no):
1164#                student['Error'] = "Duplicate"
1165#                no_import.append( format_error % student)
1166#                continue
1167#            cert_id = makeCertificateCode(student.get('Coursemajorcode'))
1168#            if cert_id not in certs.keys():
1169#                student['Error'] = "No Certificate %s" % cert_id
1170#                no_import.append( format_error % student)
1171#                continue
1172            try:
1173                table.modifyRecord(**student)
1174            except KeyError:
1175                #import pdb;pdb.set_trace()
1176                student['Error'] = "no Student found to update"
1177                no_import.append( format_error % student)
1178                continue
[1386]1179            #s = self.students_catalog(matric_no=matric_no)
1180            #if s:
1181            #    level = "%s" % (int(student.get('Level')) + 100)
1182            #    self.students_catalog.modifyRecord(id = s[0].id,
1183            #                                           level=level)
[1289]1184
1185            regs.append(student.get('matric_no'))
1186            imported.append(format % student)
1187            tr_count += 1
1188            if tr_count > 1000:
1189                if len(no_import) > 0:
1190                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
1191                             '\n'.join(no_import) + '\n')
1192                    no_import = []
1193                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
1194                                            '\n'.join(no_import) + "\n")
1195                imported = []
1196                em = '%d transactions commited total %s\n' % (tr_count,total)
1197                transaction.commit()
1198                regs = []
1199                logger.info(em)
1200                total += tr_count
1201                tr_count = 0
1202        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
1203                                            '\n'.join(imported))
1204        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
1205                                                '\n'.join(no_import))
1206        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1207    ###)
1208
[1146]1209    security.declareProtected(ModifyPortalContent,"importResults")###(
1210    def importResults(self):
[1151]1211        """load Returning Students Results from CSV"""
[1146]1212        import transaction
1213        import random
1214        #from pdb import set_trace
1215        wftool = self.portal_workflow
1216        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
1217        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
1218        tr_count = 1
1219        total = 0
1220        #name = 'pume_results'
1221        name = 'Results'
1222        table = self.results_import
1223        no_import = []
1224        imported = []
[1571]1225        logger = logging.getLogger('Students.StudentsFolder.importResults')
[1146]1226        try:
1227            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1228        except:
1229            logger.error('Error reading %s.csv' % name)
1230            return
1231        l = self.portal_catalog({'meta_type': "Course"})
1232        courses = [f.getId for f in l]
1233        start = True
1234        res = table()
1235        regs = []
1236        if len(res) > 0:
1237            regs = [s.key for s in res]
1238        no_course = []
1239        no_course_list = []
1240        course_count = 0
1241        for result in results:
1242            if start:
1243                start = False
[1571]1244                logger.info('Start loading from %s.csv' % name)
[1321]1245                s = ','.join(['"%s"' % fn for fn in result.keys()])
[1146]1246                imported.append(s)
1247                no_import.append('%s,"Error"' % s)
1248                format = ','.join(['"%%(%s)s"' % fn for fn in result.keys()])
1249                format_error = format + ',"%(Error)s"'
1250                no_certificate = "no certificate %s" % format
1251            course_id = result.get('CosCode')
[1448]1252            if not course_id:
1253                course_id = 'N/A'
1254                result['CosCode'] = course_id
[1168]1255            matric_no = result.get('matric_no').upper()
1256            result['matric_no'] = matric_no
1257            key = matric_no+course_id
1258            if matric_no == '':
[1252]1259                result['Error'] = "Empty matric_no"
[1146]1260                no_import.append( format_error % result)
1261                continue
[1168]1262            if key in regs or self.results_import(key = key):
[1252]1263                result['Error'] = "Duplicate"
[1146]1264                no_import.append( format_error % result)
1265                continue
1266            if course_id not in courses:
1267                if course_id not in no_course:
1268                    course_count +=1
1269                    no_course.append(course_id)
1270                    no_course_list.append('"%s"' % course_id)
1271                    #result['Error'] = "No Course"
1272                    #logger.info(format_error % result)
1273            regs.append(key)
1274            imported.append(format % result)
1275            tr_count += 1
1276            if tr_count > 1000:
1277                if len(no_import) > 0:
1278                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
[1151]1279                             '\n'.join(no_import)+'\n')
[1146]1280                    no_import = []
1281                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
[1151]1282                                            '\n'.join(imported) + '\n')
[1146]1283                imported = []
1284                if no_course_list:
1285                    open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
[1151]1286                                            '\n'.join(no_course_list) + '\n')
[1146]1287                    no_course_list = []
1288                em = '%d transactions commited total %s\n courses not found %s' % (tr_count,total,course_count)
1289                transaction.commit()
1290                logger.info(em)
[1168]1291                regs = []
[1146]1292                total += tr_count
1293                tr_count = 0
1294        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
1295                                            '\n'.join(imported))
1296        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
1297                                                '\n'.join(no_import))
1298        if no_course_list:
1299            open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
1300                                    '\n'.join(no_course_list))
[1393]1301        em = '%d transactions commited total %s\n courses not found %s' % (tr_count,total,course_count)
1302        logger.info(em)
[1146]1303        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1304    ###)
1305
[1700]1306    security.declareProtected(ModifyPortalContent,"importPreviousSessionStudents")###(
1307    def importPreviousSessionStudents(self):
1308        """load and create previous session students from CSV"""
1309        import transaction
1310        import random
1311        wftool = self.portal_workflow
1312        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
1313        students_folder = self.portal_url.getPortalObject().campus.students
1314        tr_count = 1
1315        total = 0
1316        #name = 'pume_results'
1317        name = 'Previous'
1318        keys = self.portal_schemas.import_student.keys()
1319        keys += self.portal_schemas.import_student_level_data.keys()
1320        not_imported = []
1321        imported = []
1322        certificates = {}
1323        logger = logging.getLogger('Students.StudentsFolder.importPreviousSessionStudents')
1324        try:
1325            records = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1326        except:
1327            logger.error('Error reading %s.csv' % name)
1328            return
1329        start = True
1330        for record in records:
1331            if start:
1332                start = False
1333                logger.info('Start loading from %s.csv' % name)
1334                false_keys = [k for k in record.keys() if k not in keys]
1335                right_keys = [k for k in record.keys() if k in keys]
1336                if false_keys:
1337                    logger.info('Fields %s not in schema' % false_keys)
1338                s = ','.join(['"%s"' % k for k in right_keys])
1339                imported.append(s)
1340                not_imported.append('%s,"error"' % s)
1341                format = ','.join(['"%%(%s)s"' % k for k in right_keys])
1342                format_error = format + ',"%(error)s"'
1343            study_course = record.get('study_course')
1344            matric_no = record.get('matric_no')
1345            student_res = self.students_catalog(matric_no = matric_no)
1346            if student_res:
1347                record['error'] = "Student exists"
1348                not_imported.append(format_error % record)
1349                continue
1350            if study_course not in certificates.keys():
1351                cert_res = self.portal_catalog(portal_type='Certificate',
1352                                                   id = study_course)
1353                if not cert_res:
1354                    record['error'] = "No such studycourse"
1355                    not_imported.append(format_error % record)
1356                    continue
1357                certificates[cert_res[0].id] = cert_res[0]
1358            sid = self.generateStudentId('x',students_folder)
1359            students_folder.invokeFactory('Student', sid)
1360            #from pdb import set_trace;set_trace()
1361            record['student_id'] = sid
1362            student = getattr(self,sid)
1363            student.manage_setLocalRoles(sid, ['Owner',])
1364            student.invokeFactory('StudentApplication','application')
1365            app = student.application
1366            app_doc = app.getContent()
1367            dict = {'Title': 'Application Data'}
1368            dict["jamb_lastname"] = "%(firstname)s %(lastname)s %(middlename)s" % record
1369            r2d = [
1370                   ('entry_mode','entry_mode'),
1371                   ('sex','jamb_sex'),
1372                   ('jamb_score','jamb_score'),
1373                   ('jamb_reg_no','jamb_reg_no'),
1374                   ]
1375            for r,d in r2d:
1376                dict[d] = record[r]
1377            app_doc.edit(mapping=dict)
1378            app.manage_setLocalRoles(sid, ['Owner',])
1379            wftool.doActionFor(app,'close')
1380            record['sex'] = record['sex'] == 'F'
1381            student.invokeFactory('StudentPersonal','personal')
1382            dict = {}
1383            r2d = [('firstname','firstname'),
1384                   ('middlename','middlename'),
1385                   ('lastname','lastname'),
1386                   ('sex','sex'),
1387                   ('email','email'),
1388                   ('phone','phone'),
1389                   ('address','perm_address'),
1390                   ]
1391            for r,d in r2d:
1392                dict[d] = record[r]
1393            per = student.personal
1394            per_doc = per.getContent()
1395            per_doc.edit(mapping = dict)
1396            per.manage_setLocalRoles(sid, ['Owner',])
1397            #
1398            # Clearance
1399            #
1400            student.invokeFactory('StudentClearance','clearance')
1401            #wftool.doActionFor(student.clearance,'open')
1402            clearance = getattr(student,'clearance')
1403            dict = {'Title': 'Clearance/Eligibility Record'}
1404            clearance.getContent().edit(mapping = dict)
1405            student.clearance.manage_setLocalRoles(sid, ['Owner',])
1406            #
1407            # Study Course
1408            #
1409            student.invokeFactory('StudentStudyCourse','study_course')
1410            study_course = student.study_course
1411            dict = {}
1412            r2d = [('session','current_session'),
1413                   ('level','current_level'),
1414                   ('verdict','current_verdict'),
1415                   ('study_course','study_course'),
1416                   ]
1417            for r,d in r2d:
1418                dict[d] = record[r]
1419            study_course.getContent().edit(mapping=dict)
1420            #
1421            # Study Level
1422            #
1423            level = record['level']
1424            study_course.invokeFactory('StudentStudyLevel',level)
1425            study_level = getattr(study_course,level)
1426            dict = {}
1427            r2d = [('session','session'),
1428                   ('level','code'),
1429                   ('verdict','verdict'),
1430                   ]
1431            for r,d in r2d:
1432                dict[d] = record[r]
1433            study_level.getContent().edit(mapping=dict)
1434            wftool.doActionFor(student,'return')
1435            imported.append(format % record)
1436            tr_count += 1
1437            record['tr_count'] = tr_count
1438            record['total'] = total
1439            logger.info('%(total)s+%(tr_count)s: Creating Student %(student_id)s %(matric_no)s %(jamb_reg_no)s' % record)
1440            if tr_count > 1000:
1441                if len(not_imported) > 0:
1442                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
1443                             '\n'.join(not_imported)+'\n')
1444                    not_imported = []
1445                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
1446                                            '\n'.join(imported) + '\n')
1447                imported = []
1448                em = '%d transactions commited total %s' % (tr_count,total)
1449                transaction.commit()
1450                logger.info(em)
1451                regs = []
1452                total += tr_count
1453                tr_count = 0
1454        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
1455                                            '\n'.join(imported))
1456        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
1457                                                '\n'.join(not_imported))
1458        em = '%d transactions commited total %d' % (tr_count,total)
1459        logger.info(em)
1460        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1461    ###)
1462
[1065]1463    security.declareProtected(ModifyPortalContent,"updateStudyCourse")###(
1464    def updateStudyCourse(self):
1465        """update StudyCourse from CSV values"""
1466        import transaction
1467        import random
1468        from pdb import set_trace
1469        wftool = self.portal_workflow
1470        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
1471        csv_d = {'jamb_reg_no': "RegNumber",
1472                 'jamb_lastname': "Name",
1473                 'session': "Session",
1474                 'pume_tot_score': "PUME SCORE",
1475                 'jamb_score': "JambScore",
1476                 'jamb_sex': "Sex",
1477                 'jamb_state': "State",
1478##                 'jamb_first_cos': "AdminCourse",
1479                 'faculty': "AdminFaculty",
1480                 'course_code': "AdmitCoscode",
1481                 'stud_status':"AdmitStatus",
1482                 'department': "AdmitDept",
1483                 'jamb_lga': "LGA",
1484                 'app_email': "email",
1485                 'app_mobile': "PhoneNumbers",
1486                 }
1487        csv_fields = [f[1] for f in csv_d.items()]
1488        tr_count = 0
1489        total = 0
1490        #name = 'pume_results'
1491        name = 'StudyCourseChange'
1492        no_import = []
[1321]1493        s = ','.join(['"%s"' % fn for fn in csv_fields])
[1065]1494        no_import.append('"Error",%s' % s)
1495        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
1496        no_certificate = "no certificate %s" % format
1497        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
1498                    '\n'.join(no_import))
[1571]1499        logger = logging.getLogger('Students.StudentsFolder.updateStudyCourse')
[1065]1500        logger.info('Start loading from %s.csv' % name)
1501        l = self.portal_catalog({'meta_type': "Certificate"})
1502        try:
1503            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1504        except:
1505            logger.error('Error reading %s.csv' % name)
1506            return
1507        for jamb in result:
1508            jamb['Error'] = "Processing "
1509            logger.info(format % jamb)
1510            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
1511            res = self.portal_catalog({'portal_type': "StudentApplication",
1512                                     'SearchableText': jamb_reg_no })
1513            if not res:
[1571]1514                em = 'Student with jamb_reg_no %s does not exists\n' % jamb_reg_no
[1065]1515                logger.info(em)
[1571]1516                jamb['Error'] = "Student does not exist"
[1065]1517                no_import.append(format % jamb)
1518                continue
1519            sid = res[0].getPath().split('/')[-2]
1520            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
1521            res = self.portal_catalog(portal_type = "Certificate", id = cert_id)
1522            if not res:
1523                em = 'No Certificate with ID %s \n' % cert_id
1524                logger.info(em)
1525                jamb['Error'] = "No Certificate %s" % cert_id
1526                no_import.append( format % jamb)
1527                continue
1528            cert_brain = res[0]
1529            catalog_entry = {}
1530            student = getattr(self,sid)
1531            #
1532            # Study Course
1533            #
1534            study_course = student.study_course
1535            dsc = {}
1536            cert_pl = cert_brain.getPath().split('/')
1537            catalog_entry['id'] = sid
1538            catalog_entry['faculty'] = cert_pl[-4]
1539            catalog_entry['department'] = cert_pl[-3]
1540            catalog_entry['course'] = cert_id
1541            dsc['study_course'] = cert_id
1542            study_course.getContent().edit(mapping=dsc)
1543            self.students_catalog.modifyRecord(**catalog_entry)
1544            if tr_count > 10:
1545                if len(no_import) > 1:
1546                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
1547                             '\n'.join(no_import))
1548                    no_import = []
1549                em = '%d transactions commited\n' % tr_count
1550                transaction.commit()
1551                logger.info(em)
1552                total += tr_count
1553                tr_count = 0
1554            tr_count += 1
1555        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1556    ###)
1557
[1594]1558    security.declareProtected(View,"fixOwnership") ###(
[511]1559    def fixOwnership(self):
1560        """fix Ownership"""
1561        for s in self.portal_catalog(meta_type = 'Student'):
1562            student = s.getObject()
1563            sid = s.getId
1564            import pdb;pdb.set_trace()
1565            student.application.manage_setLocalRoles(sid, ['Owner',])
1566            student.personal.manage_setLocalRoles(sid, ['Owner',])
[1594]1567    ###)
[603]1568
[1594]1569    security.declareProtected(View,"Title") ###(
[364]1570    def Title(self):
1571        """compose title"""
[382]1572        return "Student Section"
[1594]1573    ###)
[361]1574
[1700]1575    def generateStudentId(self,letter,students = None): ###(
[714]1576        import random
1577        r = random
[1700]1578        if students is None:
1579            students = self.portal_url.getPortalObject().campus.students
[714]1580        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
1581            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
1582        sid = "%c%d" % (letter,r.randint(99999,1000000))
1583        while hasattr(students, sid):
1584            sid = "%c%d" % (letter,r.randint(99999,1000000))
[758]1585        return sid
[714]1586        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
1587    ###)
1588
[361]1589InitializeClass(StudentsFolder)
1590
[1594]1591def addStudentsFolder(container, id, REQUEST=None, **kw): ###(
[361]1592    """Add a Student."""
1593    ob = StudentsFolder(id, **kw)
1594    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[1594]1595    ###)
1596
[361]1597###)
1598
[57]1599class Student(CPSDocument): ###(
1600    """
[154]1601    WAeUP Student container for the various student data
[57]1602    """
1603    meta_type = 'Student'
1604    portal_type = meta_type
1605    security = ClassSecurityInfo()
[154]1606
[152]1607    security.declareProtected(View,"Title")
1608    def Title(self):
1609        """compose title"""
[153]1610        reg_nr = self.getId()[1:]
[362]1611        data = getattr(self,'personal',None)
[152]1612        if data:
1613            content = data.getContent()
[1143]1614            return "%s %s %s" % (content.firstname,content.middlename,content.lastname)
[472]1615        data = getattr(self,'application',None)
[464]1616        if data:
1617            content = data.getContent()
1618            return "%s" % (content.jamb_lastname)
[152]1619        return self.title
[154]1620
[511]1621    security.declarePrivate('makeStudentMember') ###(
1622    def makeStudentMember(self,sid,password='uNsEt'):
1623        """make the student a member"""
1624        membership = self.portal_membership
[603]1625        membership.addMember(sid,
[511]1626                             password ,
1627                             roles=('Member',
1628                                     'Student',
[522]1629                                     ),
[511]1630                             domains='',
[904]1631                             properties = {'memberareaCreationFlag': False,
1632                                           'homeless': True},)
[511]1633        member = membership.getMemberById(sid)
1634        self.portal_registration.afterAdd(member, sid, password, None)
1635        self.manage_setLocalRoles(sid, ['Owner',])
1636
1637###)
1638
[764]1639    security.declareProtected(View,'createSubObjects') ###(
1640    def createSubObjects(self):
1641        """make the student a member"""
1642        dp = {'Title': 'Personal Data'}
1643        app_doc = self.application.getContent()
1644        names = app_doc.jamb_lastname.split()
1645        if len(names) == 3:
1646            dp['firstname'] = names[0].capitalize()
1647            dp['middlename'] = names[1].capitalize()
1648            dp['lastname'] = names[2].capitalize()
1649        elif len(names) == 2:
1650            dp['firstname'] = names[0].capitalize()
1651            dp['lastname'] = names[1].capitalize()
1652        else:
1653            dp['lastname'] = app_doc.jamb_lastname
1654        dp['sex'] = app_doc.jamb_sex == 'F'
1655        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
1656        proxy = self.aq_parent
1657        proxy.invokeFactory('StudentPersonal','personal')
1658        per = proxy.personal
1659        per_doc = per.getContent()
1660        per_doc.edit(mapping = dp)
[927]1661        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
[764]1662        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]1663
[511]1664###)
1665
[57]1666InitializeClass(Student)
1667
1668def addStudent(container, id, REQUEST=None, **kw):
1669    """Add a Student."""
1670    ob = Student(id, **kw)
1671    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1672
1673###)
[91]1674
[639]1675class StudentAccommodation(CPSDocument): ###(
1676    """
1677    WAeUP Student container for the various student data
1678    """
1679    meta_type = 'StudentAccommodation'
1680    portal_type = meta_type
1681    security = ClassSecurityInfo()
1682
1683    security.declareProtected(View,"Title")
1684    def Title(self):
1685        """compose title"""
1686        content = self.getContent()
1687        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
1688        return "Accommodation Data for Session %s" % content.session
1689
1690
1691InitializeClass(StudentAccommodation)
1692
1693def addStudentAccommodation(container, id, REQUEST=None, **kw):
1694    """Add a Students personal data."""
1695    ob = StudentAccommodation(id, **kw)
1696    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1697
1698###)
1699
[89]1700class StudentPersonal(CPSDocument): ###(
1701    """
[154]1702    WAeUP Student container for the various student data
[89]1703    """
1704    meta_type = 'StudentPersonal'
1705    portal_type = meta_type
1706    security = ClassSecurityInfo()
[152]1707
1708    security.declareProtected(View,"Title")
1709    def Title(self):
1710        """compose title"""
1711        content = self.getContent()
[364]1712        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
1713        return "Personal Data"
[152]1714
[154]1715
[89]1716InitializeClass(StudentPersonal)
1717
1718def addStudentPersonal(container, id, REQUEST=None, **kw):
1719    """Add a Students personal data."""
1720    ob = StudentPersonal(id, **kw)
1721    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1722
1723###)
1724
[423]1725class StudentClearance(CPSDocument): ###(
1726    """
1727    WAeUP Student container for the various student data
1728    """
1729    meta_type = 'StudentClearance'
1730    portal_type = meta_type
1731    security = ClassSecurityInfo()
1732
1733    security.declareProtected(View,"Title")
1734    def Title(self):
1735        """compose title"""
1736        content = self.getContent()
[840]1737        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
1738        return "Clearance/Eligibility Record"
[423]1739
1740
1741InitializeClass(StudentClearance)
1742
1743def addStudentClearance(container, id, REQUEST=None, **kw):
1744    """Add a Students personal data."""
1745    ob = StudentClearance(id, **kw)
1746    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1747
1748###)
1749
[454]1750class StudentStudyLevel(CPSDocument): ###(
1751    """
1752    WAeUP Student container for the various student data
1753    """
1754    meta_type = 'StudentStudyLevel'
1755    portal_type = meta_type
1756    security = ClassSecurityInfo()
1757
1758    security.declareProtected(View,"Title")
1759    def Title(self):
1760        """compose title"""
1761        return "Level %s" % self.aq_parent.getId()
1762
[1700]1763    def create_course_results(self,cert_id,current_level): ###(
[1649]1764        "create all courses in a level"
1765        aq_portal = self.portal_catalog.evalAdvancedQuery
1766        res = self.portal_catalog(portal_type="Certificate", id = cert_id)
1767        l = []
1768        import transaction
1769        if res:
1770            cert = res[0]
1771            path = cert.getPath()
1772            query = Eq("path","%s/%s" % (path,current_level)) &\
1773                    Eq('portal_type','CertificateCourse')
1774            courses = aq_portal(query)
1775            #from pdb import set_trace;set_trace()
1776            self_proxy = self.aq_parent
1777            for c in courses:
1778                d = self.getCourseInfo(c.getId)
1779                cr_id = self_proxy.invokeFactory('StudentCourseResult',c.getId)
1780                course_result = getattr(self_proxy,cr_id)
1781                self.portal_workflow.doActionFor(course_result,'open')
1782                d['core_or_elective'] = getattr(c.getObject().getContent(),'core_or_elective')
1783                course_result.getContent().edit(mapping=d)
1784                transaction.commit()
[1700]1785    ###)
[472]1786
[454]1787InitializeClass(StudentStudyLevel)
1788
1789def addStudentStudyLevel(container, id, REQUEST=None, **kw):
1790    """Add a Students personal data."""
1791    ob = StudentStudyLevel(id, **kw)
1792    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1793
1794###)
1795
[362]1796class StudentStudyCourse(CPSDocument): ###(
1797    """
1798    WAeUP Student container for the various student data
1799    """
1800    meta_type = 'StudentStudyCourse'
1801    portal_type = meta_type
1802    security = ClassSecurityInfo()
1803
[364]1804    security.declareProtected(View,"Title")
1805    def Title(self):
1806        """compose title"""
1807        content = self.getContent()
[453]1808        return "Study Course"
[362]1809
1810
1811InitializeClass(StudentStudyCourse)
1812
1813def addStudentStudyCourse(container, id, REQUEST=None, **kw):
1814    """Add a Students personal data."""
1815    ob = StudentStudyCourse(id, **kw)
1816    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1817
1818###)
1819
[472]1820class StudentApplication(CPSDocument): ###(
[179]1821    """
1822    WAeUP Student container for the various student data
1823    """
[472]1824    meta_type = 'StudentApplication'
[179]1825    portal_type = meta_type
1826    security = ClassSecurityInfo()
1827
[181]1828    security.declareProtected(View,"Title")
1829    def Title(self):
1830        """compose title"""
[472]1831        return "Application Data"
[179]1832
[181]1833
[472]1834InitializeClass(StudentApplication)
[179]1835
[472]1836def addStudentApplication(container, id, REQUEST=None, **kw):
[179]1837    """Add a Students eligibility data."""
[472]1838    ob = StudentApplication(id, **kw)
[179]1839    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]1840###)
[179]1841
[758]1842class StudentPume(CPSDocument): ###(
1843    """
1844    WAeUP Student container for the various student data
1845    """
1846    meta_type = 'StudentPume'
1847    portal_type = meta_type
1848    security = ClassSecurityInfo()
1849
1850    security.declareProtected(View,"Title")
1851    def Title(self):
1852        """compose title"""
1853        return "PUME Results"
1854
1855
1856InitializeClass(StudentPume)
1857
1858def addStudentPume(container, id, REQUEST=None, **kw):
1859    """Add a Students PUME data."""
1860    ob = StudentPume(id, **kw)
1861    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[179]1862###)
[181]1863
[565]1864##class StudentSemester(CPSDocument): ###(
1865##    """
1866##    WAeUP StudentSemester containing the courses and students
1867##    """
1868##    meta_type = 'StudentSemester'
1869##    portal_type = meta_type
1870##    security = ClassSecurityInfo()
1871##
1872##InitializeClass(StudentSemester)
1873##
1874##def addStudentSemester(container, id, REQUEST=None, **kw):
1875##    """Add a StudentSemester."""
1876##    ob = StudentSemester(id, **kw)
1877##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1878##
1879#####)
[464]1880
[758]1881##class Semester(CPSDocument): ###(
1882##    """
1883##    WAeUP Semester containing the courses and students
1884##    """
1885##    meta_type = 'Semester'
1886##    portal_type = meta_type
1887##    security = ClassSecurityInfo()
1888##
1889##InitializeClass(Semester)
1890##
1891##def addSemester(container, id, REQUEST=None, **kw):
1892##    """Add a Semester."""
1893##    ob = Semester(id, **kw)
1894##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1895##
1896#####)
[464]1897
1898class StudentCourseResult(CPSDocument): ###(
[89]1899    """
[464]1900    WAeUP StudentCourseResult
[89]1901    """
[464]1902    meta_type = 'StudentCourseResult'
[89]1903    portal_type = meta_type
1904    security = ClassSecurityInfo()
[472]1905
[454]1906    def getCourseEntry(self,cid):
[723]1907        res = self.portal_catalog({'meta_type': "Course",
[454]1908                                           'id': cid})
1909        if res:
1910            return res[-1]
1911        else:
1912            return None
[154]1913
[454]1914    security.declareProtected(View,"Title")
1915    def Title(self):
1916        """compose title"""
[723]1917        cid = self.aq_parent.getId()
[454]1918        ce = self.getCourseEntry(cid)
1919        if ce:
1920            return "%s" % ce.Title
1921        return "No course with id %s" % cid
[152]1922
[464]1923InitializeClass(StudentCourseResult)
[454]1924
[464]1925def addStudentCourseResult(container, id, REQUEST=None, **kw):
1926    """Add a StudentCourseResult."""
1927    ob = StudentCourseResult(id, **kw)
[89]1928    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]1929###)
1930
[579]1931# Backward Compatibility StudyLevel
1932
1933from Products.WAeUP_SRP.Academics import StudyLevel
1934
1935from Products.WAeUP_SRP.Academics import addStudyLevel
1936
Note: See TracBrowser for help on using the repository browser.