source: WAeUP_SRP/trunk/Students.py @ 1894

Last change on this file since 1894 was 1894, checked in by Henrik Bettermann, 17 years ago

fixed

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