source: WAeUP_SRP/base/Students.py @ 2913

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

layout changes

  • Property svn:keywords set to Id
File size: 29.6 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 2912 2007-12-10 20:11:24Z 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
18
19from Products.AdvancedQuery import Eq, Between, Le,In
20import DateTime
21import logging
22import csv,re,os
23import Globals
24p_home = Globals.package_home(globals())
25i_home = Globals.INSTANCE_HOME
26MAX_TRANS = 1000
27from urllib import urlencode
28
29import DateTime
30#import PIL.Image
31from StringIO import StringIO
32
33def makeCertificateCode(code): ###(
34    code = code.replace('.','')
35    code = code.replace('(','')
36    code = code.replace(')','')
37    code = code.replace('/','')
38    code = code.replace(' ','')
39    code = code.replace('_','')
40    return code
41
42###)
43
44def response_write(response,s): ###(
45    response.setHeader('Content-type','text/html; charset=ISO-8859-15')
46    while s.find('<') > -1:
47        s = s.replace('<','&lt;')
48    while s.find('>') > -1:
49        #from pdb import set_trace;set_trace()
50        s = s.replace('>','&gt;')
51    response.write("%s<br>\n" % s)
52
53###)
54
55def getInt(s): ###(
56    try:
57        return int(s)
58    except:
59        return 0
60
61def getFloat(s):
62    try:
63        return float(s)
64    except:
65        return 0.0
66
67###)
68
69def getStudentByRegNo(self,reg_no): ###(
70    """search student by JAMB Reg No and return StudentFolder"""
71    res = self.students_catalog(jamb_reg_no = reg_no.upper())
72    if len(res) == 1:
73        return getattr(self.portal_url.getPortalObject().campus.students,res[0].id)
74    else:
75        return None
76    # don't search in portal_catalog
77    # search = ZCatalog.searchResults(self.portal_catalog_real,{'meta_type': 'StudentApplication',
78    #                               'SearchableText': reg_no,
79    #                               })
80    # if len(search) < 1:
81    #     return None
82    # return search[0].getObject().aq_parent
83
84###)
85
86def checkJambNo(jnr): ###(
87    try:
88        if len(jnr) != 10:
89            return False
90    except:
91        return False
92    try:
93        int(jnr[:8])
94        return True
95    except:
96        return False
97
98###)
99
100def formatLGA(lga,voc=None):
101    if voc is not None:
102        if voc.has_key(lga):
103            state,lga = voc[lga].split(' / ')
104        elif lga.find(' / ') > -1:
105            state,lga = lga.split(' / ')
106        else:
107            state,lga = "",lga
108    return state.upper(),lga.upper()
109
110class StudentsFolder(CPSDocument): ###(
111    """
112    WAeUP container for the various WAeUP containers data
113    """
114    meta_type = 'StudentsFolder'
115    portal_type = meta_type
116    security = ClassSecurityInfo()
117
118
119    security.declareProtected(ModifyPortalContent,"transferStudents")###(
120    def transferStudents(self,filename):
121        """
122        load Interfaculty transferStudents Studentdata from CSV values.
123        """
124        import transaction
125        import random
126        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
127        pm = self.portal_membership
128        member = pm.getAuthenticatedMember()
129        logger = logging.getLogger('Students.StudentsFolder.transferStudents')
130        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
131        students_folder = self.portal_url.getPortalObject().campus.students
132        csv_fields = ('old_matric_no',
133                      'matric_no',
134                      'study_course',
135                      'current_mode',
136                      'current_level',
137                      )
138        tr_count = 0
139        total = 0
140        total_imported = 0
141        total_not_imported = 0
142        imported = []
143        not_imported = []
144        certs = {}
145        try:
146            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,filename),"rb"))
147        except:
148            logger.error('Error reading %s.csv' % filename)
149            return
150        start = True
151        for result in results:
152            total += 1
153            if start:
154                start = False
155                logger.info('%s starts import from %s.csv' % (member,filename))
156                import_keys = [k for k in result.keys() if not k.startswith('ignore')]
157                diff2schema = set(import_keys).difference(set(csv_fields))
158                if diff2schema:
159                    em = "not ignorable key(s) %s found in heading" % diff2schema
160                    return em
161                s = ','.join(['"%s"' % fn for fn in import_keys])
162                open("%s/import/%s_not_imported%s.csv" % (i_home,filename,current),"a").write(s + ',"Error"'+ '\n')
163                s = '"id",' + s
164                open("%s/import/%s_imported%s.csv" % (i_home,filename,current),"a").write(s + '\n')
165                format = ','.join(['"%%(%s)s"' % fn for fn in import_keys])
166                format_error = format + ',"%(Error)s"'
167                format = '"%(id)s",'+ format
168            old_matric_no = result.get('old_matric_no')
169            res = self.students_catalog(matric_no = old_matric_no)
170            result['id'] = "None"
171            if not res:
172                em = 'Student with matric_no %s not found' % old_matric_no
173                logger.info(em)
174                result['Error'] = "Student does not exist"
175                not_imported.append(format_error % result)
176                total_not_imported += 1
177                continue
178            student_brain = res[0]
179            student_object = getattr(students_folder,student_brain.id)
180            result['id'] = student_brain.id
181            cert_id = makeCertificateCode(result.get('study_course'))
182            if cert_id not in certs.keys():
183                res = self.portal_catalog(meta_type = "Certificate",id = cert_id)
184                if not res:
185                    em = 'No certificate with ID %s \n' % cert_id
186                    logger.info(em)
187                    result['Error'] = "No Certificate %s" % cert_id
188                    not_imported.append( format_error % result)
189                    total_not_imported += 1
190                    continue
191                cert = res[0]
192                cert_path = cert.getPath().split('/')
193                certificate = certs[cert_id] = {'faculty': cert_path[-4],
194                                     'department': cert_path[-3]}
195            cert_doc = certs[cert_id]
196            clearance = getattr(student_object,'clearance',None)
197            if clearance is None:
198                em = 'Student has no clearance object'
199                logger.info('%s (%s) %s' % (student_brain.id, old_matric_no, em))
200                result['Error'] = em
201                not_imported.append( format_error % result)
202                total_not_imported += 1
203                continue
204            clearance_doc = clearance.getContent()
205            study_course = student_object.study_course
206            study_course_doc = study_course.getContent()
207            old_study_course = study_course_doc.study_course
208            old_current_level = study_course_doc.current_level
209            current_level = result.get('current_level',None)
210            new_study_course = result.get('study_course',None)
211            try:
212                icl = int(current_level)
213            except:
214                em = 'Invalid new level %s' % current_level
215                logger.info(em)
216                result['Error'] = em
217                not_imported.append( format_error % result)
218                total_not_imported += 1
219                continue
220            try:
221                icl = int(old_current_level)
222                if icl == int(old_current_level) and old_study_course == new_study_course:
223                    em = 'Already transferred'
224                    logger.info('%s (%s) %s' % (student_brain.id, old_matric_no, em))
225                    result['Error'] = em
226                    not_imported.append( format_error % result)
227                    total_not_imported += 1
228                    continue
229            except:
230                pass
231            if study_course.objectIds():
232                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)
233                logger.info('%s (%s) %s' % (student_brain.id, old_matric_no, em))
234                result['Error'] = em
235                not_imported.append( format_error % result)
236                total_not_imported += 1
237                continue
238            #from pdb import set_trace; set_trace()
239            cd = {}
240            matric_no_history = getattr(clearance_doc,'matric_no_history',[])
241            if not matric_no_history:
242                matric_no_history = []
243            matric_no_history.append(old_matric_no)
244            cd['matric_no_history'] = matric_no_history
245            cd['matric_no'] = result.get('matric_no')
246            clearance_doc.edit(mapping = cd)
247            dsc = {}
248            study_course_history = getattr(study_course_doc,'study_course_history',[])
249            if not study_course_history:
250                study_course_history = []
251            study_course_history.append(old_study_course)
252            dsc['study_course_history'] = study_course_history
253            dsc['study_course'] = new_study_course
254            dsc['current_level'] = current_level
255            dsc['current_mode'] = result.get('current_mode')
256            study_course_doc.edit(mapping=dsc)
257            imported.append( format % result)
258            tr_count += 1
259            total_imported += 1
260            if tr_count > 1000:
261                if len(not_imported) > 0:
262                    open("%s/import/%s_not_imported%s.csv" % (i_home,filename,current),"a").write(
263                             '\n'.join(not_imported) + '\n')
264                    not_imported = []
265                if len(imported) > 0:
266                    open("%s/import/%s_imported%s.csv" % (i_home,filename,current),"a").write(
267                             '\n'.join(imported) + '\n')
268                    imported = []
269                em = '%d transactions committed\n' % (tr_count)
270                transaction.commit()
271                regs = []
272                logger.info(em)
273                tr_count = 0
274        if len(imported) > 0:
275            open("%s/import/%s_imported%s.csv" % (i_home,filename,current),"a").write(
276                                                '\n'.join(imported))
277        if len(not_imported) > 0:
278            open("%s/import/%s_not_imported%s.csv" % (i_home,filename,current),"a").write(
279                                                '\n'.join(not_imported))
280        em = "Imported: %d, not imported: %d of total %d" % (total_imported,total_not_imported,total)
281        logger.info(em)
282        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
283    ###)
284
285
286    security.declareProtected(ModifyPortalContent,"dumpStudentsCatalog")###(
287    def dumpStudentsCatalog(self):
288        """dump all data in students_catalog to a csv"""
289        member = self.portal_membership.getAuthenticatedMember()
290        logger = logging.getLogger('Students.dumpStudentsCatalog')
291        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
292        export_file = "%s/export/students_catalog_%s.csv" % (i_home,current)
293        res_list = []
294        lines = []
295        fields = []
296        for f in self.students_catalog.schema():
297            fields.append(f)
298        fields.append('state')
299        headline = ','.join(fields)
300        #open(export_file,"a").write(headline +'\n')
301        out = open(export_file,"wb")
302        out.write(headline +'\n')
303        out.close()
304        out = open(export_file,"a")
305        csv_writer = csv.DictWriter(out,fields,)
306        format = '"%(' + ')s","%('.join(fields) + ')s"'
307        students = self.students_catalog()
308        nr2export = len(students)
309        logger.info('%s starts dumpStudentsCatalog, %s student records to export' % (member,nr2export))
310        chunk = 2000
311        total = 0
312        start = DateTime.DateTime().timeTime()
313        start_chunk = DateTime.DateTime().timeTime()
314        for student in students:
315            not_all = False
316            d = self.getFormattedStudentEntry(student)
317            d['state'],d['lga'] = formatLGA(d['lga'],voc = self.portal_vocabularies.local_gov_areas)
318            #lines.append(format % d)
319            lines.append(d)
320            total += 1
321            if total and not total % chunk or total == len(students):
322                #open(export_file,"a").write('\n'.join(lines) +'\n')
323                csv_writer.writerows(lines)
324                anz = len(lines)
325                logger.info("wrote %(anz)d  total written %(total)d" % vars())
326                end_chunk = DateTime.DateTime().timeTime()
327                duration = end_chunk-start_chunk
328                per_record = duration/anz
329                till_now = end_chunk - start
330                avarage_per_record = till_now/total
331                estimated_end = DateTime.DateTime(start + avarage_per_record * nr2export)
332                estimated_end = estimated_end.strftime("%H:%M:%S")
333                logger.info('%(duration)4.1f, %(per_record)4.3f,end %(estimated_end)s' % vars())
334                start_chunk = DateTime.DateTime().timeTime()
335                lines = []
336        end = DateTime.DateTime().timeTime()
337        logger.info('total time %6.2f m' % ((end-start)/60))
338        filename, extension = os.path.splitext(export_file)
339        from subprocess import call
340        msg = "wrote %(total)d records to %(export_file)s" % vars()
341        try:
342            retcode = call('gzip %s' % (export_file),shell=True)
343            if retcode == 0:
344                msg = "wrote %(total)d records to %(export_file)s.gz" % vars()
345        except OSError, e:
346            retcode = -99
347            logger.info("zip failed with %s" % e)
348        logger.info(msg)
349        args = {'portal_status_message': msg}
350        #url = self.REQUEST.get('URL1') + '?' + urlencode(args)
351        url = self.REQUEST.get('URL2')
352        return self.REQUEST.RESPONSE.redirect(url)
353    ###)
354
355
356    security.declareProtected(ModifyPortalContent,"importResults")###(
357    def importResults(self):
358        """load Returning Students Results from CSV"""
359        import transaction
360        import random
361        #from pdb import set_trace
362        wftool = self.portal_workflow
363        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
364        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
365        students_folder = self.portal_url.getPortalObject().campus.students
366        tr_count = 1
367        total = 0
368        #name = 'pume_results'
369        name = 'Results'
370        table = self.results_import
371        no_import = []
372        imported = []
373        logger = logging.getLogger('Students.StudentsFolder.importResults')
374        try:
375            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
376        except:
377            logger.error('Error reading %s.csv' % name)
378            return
379
380        l = self.portal_catalog({'meta_type': "Course"})
381        courses = [f.getId for f in l]
382        start = True
383        res = table()
384        regs = []
385        if len(res) > 0:
386            regs = [s.key for s in res]
387        no_course = []
388        no_course_list = []
389        course_count = 0
390        for result in results:
391            if start:
392                start = False
393                logger.info('Start loading from %s.csv' % name)
394                s = ','.join(['"%s"' % fn for fn in result.keys()])
395                imported.append(s)
396                no_import.append('%s,"Error"' % s)
397                format = ','.join(['"%%(%s)s"' % fn for fn in result.keys()])
398                format_error = format + ',"%(Error)s"'
399                no_certificate = "no certificate %s" % format
400            course_id = result.get('CosCode')
401            if not course_id:
402                course_id = 'N/A'
403                result['CosCode'] = course_id
404            matric_no = result.get('matric_no').upper()
405            result['matric_no'] = matric_no
406            key = matric_no+course_id
407            if matric_no == '':
408                result['Error'] = "Empty matric_no"
409                no_import.append( format_error % result)
410                continue
411            if key in regs or self.results_import(key = key):
412                result['Error'] = "Duplicate"
413                no_import.append( format_error % result)
414                continue
415            if course_id not in courses:
416                if course_id not in no_course:
417                    course_count +=1
418                    no_course.append(course_id)
419                    no_course_list.append('"%s"' % course_id)
420                    #result['Error'] = "No Course"
421                    #logger.info(format_error % result)
422
423            result['key'] = key
424            try:
425                table.addRecord(**result)
426            except ValueError:
427                #import pdb;pdb.set_trace()
428                result['Error'] = "Duplicate"
429                no_import.append( format_error % result)
430                continue
431
432            regs.append(key)
433            imported.append(format % result)
434            tr_count += 1
435            if tr_count > 1000:
436                if len(no_import) > 0:
437                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
438                             '\n'.join(no_import)+'\n')
439                    no_import = []
440                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
441                                            '\n'.join(imported) + '\n')
442                imported = []
443                if no_course_list:
444                    open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
445                                            '\n'.join(no_course_list) + '\n')
446                    no_course_list = []
447                transaction.commit()
448                regs = []
449                total += tr_count
450                em = '%d transactions totally comitted, %s courses not found ' % (total,course_count)
451                logger.info(em)
452                tr_count = 0
453        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
454                                            '\n'.join(imported))
455        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
456                                                '\n'.join(no_import))
457        if no_course_list:
458            open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
459                                    '\n'.join(no_course_list))
460        em = '%d transactions totally committed, %s courses not found ' % (total,course_count)
461        logger.info(em)
462        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
463    ###)
464
465
466
467    security.declareProtected(View,"fixOwnership") ###(
468    def fixOwnership(self):
469        """fix Ownership"""
470        for s in self.portal_catalog(meta_type = 'Student'):
471            student = s.getObject()
472            sid = s.getId
473            import pdb;pdb.set_trace()
474            student.application.manage_setLocalRoles(sid, ['Owner',])
475            student.personal.manage_setLocalRoles(sid, ['Owner',])
476    ###)
477
478    security.declareProtected(View,"Title") ###(
479    def Title(self):
480        """compose title"""
481        return "Student Section"
482    ###)
483
484    def generateStudentId(self,letter,students = None): ###(
485        import random
486        r = random
487        if students is None:
488            students = self.portal_url.getPortalObject().campus.students
489        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
490            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
491        sid = "%c%d" % (letter,r.randint(99999,1000000))
492        while hasattr(students, sid):
493            sid = "%c%d" % (letter,r.randint(99999,1000000))
494        return sid
495        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
496    ###)
497
498InitializeClass(StudentsFolder)
499
500def addStudentsFolder(container, id, REQUEST=None, **kw): ###(
501    """Add a Student."""
502    ob = StudentsFolder(id, **kw)
503    return CPSBase_adder(container, ob, REQUEST=REQUEST)
504    ###)
505
506###)
507
508class Student(CPSDocument): ###(
509    """
510    WAeUP Student container for the various student data
511    """
512    meta_type = 'Student'
513    portal_type = meta_type
514    security = ClassSecurityInfo()
515
516    security.declareProtected(View,"Title")
517    def Title(self):
518        """compose title"""
519        reg_nr = self.getId()[1:]
520        data = getattr(self,'personal',None)
521        if data:
522            content = data.getContent()
523            return "%s %s %s" % (content.firstname,content.middlename,content.lastname)
524        data = getattr(self,'application',None)
525        if data:
526            content = data.getContent()
527            return "%s" % (content.jamb_lastname)
528        return self.title
529
530    security.declarePrivate('makeStudentMember') ###(
531    def makeStudentMember(self,sid,password='uNsEt'):
532        """make the student a member"""
533        membership = self.portal_membership
534        membership.addMember(sid,
535                             password ,
536                             roles=('Member',
537                                     'Student',
538                                     ),
539                             domains='',
540                             properties = {'memberareaCreationFlag': False,
541                                           'homeless': True},)
542        member = membership.getMemberById(sid)
543        self.portal_registration.afterAdd(member, sid, password, None)
544        self.manage_setLocalRoles(sid, ['Owner',])
545
546###)
547
548    security.declareProtected(View,'createSubObjects') ###(
549    def createSubObjects(self):
550        """make the student a member"""
551        dp = {'Title': 'Personal Data'}
552        app_doc = self.application.getContent()
553        names = app_doc.jamb_lastname.split()
554        if len(names) == 3:
555            dp['firstname'] = names[0].capitalize()
556            dp['middlename'] = names[1].capitalize()
557            dp['lastname'] = names[2].capitalize()
558        elif len(names) == 2:
559            dp['firstname'] = names[0].capitalize()
560            dp['lastname'] = names[1].capitalize()
561        else:
562            dp['lastname'] = app_doc.jamb_lastname
563        dp['sex'] = app_doc.jamb_sex == 'F'
564        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
565        proxy = self.aq_parent
566        proxy.invokeFactory('StudentPersonal','personal')
567        per = proxy.personal
568        per_doc = per.getContent()
569        per_doc.edit(mapping = dp)
570        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
571        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
572
573###)
574
575InitializeClass(Student)
576
577def addStudent(container, id, REQUEST=None, **kw):
578    """Add a Student."""
579    ob = Student(id, **kw)
580    return CPSBase_adder(container, ob, REQUEST=REQUEST)
581
582###)
583
584class StudentAccommodation(CPSDocument): ###(
585    """
586    WAeUP Student container for the various student data
587    """
588    meta_type = 'StudentAccommodation'
589    portal_type = meta_type
590    security = ClassSecurityInfo()
591
592    security.declareProtected(View,"Title")
593    def Title(self):
594        """compose title"""
595        content = self.getContent()
596        session_str = self.portal_vocabularies.sessions.get(content.session)
597        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
598        return "Accommodation Data for Session %s" % session_str
599
600
601InitializeClass(StudentAccommodation)
602
603def addStudentAccommodation(container, id, REQUEST=None, **kw):
604    """Add a Students personal data."""
605    ob = StudentAccommodation(id, **kw)
606    return CPSBase_adder(container, ob, REQUEST=REQUEST)
607
608###)
609
610class StudentPersonal(CPSDocument): ###(
611    """
612    WAeUP Student container for the various student data
613    """
614    meta_type = 'StudentPersonal'
615    portal_type = meta_type
616    security = ClassSecurityInfo()
617
618    security.declareProtected(View,"Title")
619    def Title(self):
620        """compose title"""
621        #content = self.getContent()
622        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
623        return "Personal Data"
624
625
626InitializeClass(StudentPersonal)
627
628def addStudentPersonal(container, id, REQUEST=None, **kw):
629    """Add a Students personal data."""
630    ob = StudentPersonal(id, **kw)
631    return CPSBase_adder(container, ob, REQUEST=REQUEST)
632
633###)
634
635class StudentClearance(CPSDocument): ###(
636    """
637    WAeUP Student container for the various student data
638    """
639    meta_type = 'StudentClearance'
640    portal_type = meta_type
641    security = ClassSecurityInfo()
642
643    security.declareProtected(View,"Title")
644    def Title(self):
645        """compose title"""
646        #content = self.getContent()
647        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
648        return "Clearance/Eligibility Record"
649
650
651InitializeClass(StudentClearance)
652
653def addStudentClearance(container, id, REQUEST=None, **kw):
654    """Add a Students personal data."""
655    ob = StudentClearance(id, **kw)
656    return CPSBase_adder(container, ob, REQUEST=REQUEST)
657
658###)
659
660class StudentStudyLevel(CPSDocument): ###(
661    """
662    WAeUP Student container for the various student data
663    """
664    meta_type = 'StudentStudyLevel'
665    portal_type = meta_type
666    security = ClassSecurityInfo()
667
668    security.declareProtected(View,"Title")
669    def Title(self):
670        """compose title"""
671        return self.portal_vocabularies.student_levels.get(self.aq_parent.getId())
672        #return "Level %s" % self.aq_parent.getId()
673
674    def create_course_results(self,cert_id,current_level): ###(
675        "create all courses in a level"
676        aq_portal = self.portal_catalog.evalAdvancedQuery
677        res = self.portal_catalog(portal_type="Certificate", id = cert_id)
678        l = []
679        import transaction
680        if res:
681            cert = res[0]
682            path = cert.getPath()
683            query = Eq("path","%s/%s" % (path,current_level)) &\
684                    Eq('portal_type','CertificateCourse')
685            courses = aq_portal(query)
686            #from pdb import set_trace;set_trace()
687            self_proxy = self.aq_parent
688            for c in courses:
689                d = self.getCourseInfo(c.getId)
690                cr_id = self_proxy.invokeFactory('StudentCourseResult',c.getId)
691                course_result = getattr(self_proxy,cr_id)
692                self.portal_workflow.doActionFor(course_result,'open')
693                d['core_or_elective'] = getattr(c.getObject().getContent(),'core_or_elective')
694                course_result.getContent().edit(mapping=d)
695                #transaction.commit()
696    ###)
697
698InitializeClass(StudentStudyLevel)
699
700def addStudentStudyLevel(container, id, REQUEST=None, **kw):
701    """Add a Students personal data."""
702    ob = StudentStudyLevel(id, **kw)
703    return CPSBase_adder(container, ob, REQUEST=REQUEST)
704
705###)
706
707class StudentStudyCourse(CPSDocument): ###(
708    """
709    WAeUP Student container for the various student data
710    """
711    meta_type = 'StudentStudyCourse'
712    portal_type = meta_type
713    security = ClassSecurityInfo()
714
715    security.declareProtected(View,"Title")
716    def Title(self):
717        """compose title"""
718        #content = self.getContent()
719        return "Study Course"
720
721
722InitializeClass(StudentStudyCourse)
723
724def addStudentStudyCourse(container, id, REQUEST=None, **kw):
725    """Add a Students personal data."""
726    ob = StudentStudyCourse(id, **kw)
727    return CPSBase_adder(container, ob, REQUEST=REQUEST)
728
729###)
730
731class StudentApplication(CPSDocument): ###(
732    """
733    WAeUP Student container for the various student data
734    """
735    meta_type = 'StudentApplication'
736    portal_type = meta_type
737    security = ClassSecurityInfo()
738
739    security.declareProtected(View,"Title")
740    def Title(self):
741        """compose title"""
742        return "Application Data"
743
744
745InitializeClass(StudentApplication)
746
747def addStudentApplication(container, id, REQUEST=None, **kw):
748    """Add a Students eligibility data."""
749    ob = StudentApplication(id, **kw)
750    return CPSBase_adder(container, ob, REQUEST=REQUEST)
751###)
752
753
754class StudentCourseResult(CPSDocument): ###(
755    """
756    WAeUP StudentCourseResult
757    """
758    meta_type = 'StudentCourseResult'
759    portal_type = meta_type
760    security = ClassSecurityInfo()
761
762    def getCourseEntry(self,cid):
763        res = self.portal_catalog({'meta_type': "Course",
764                                           'id': cid})
765        if res:
766            return res[-1]
767        else:
768            return None
769
770    security.declareProtected(View,"Title")
771    def Title(self):
772        """compose title"""
773        cid = self.aq_parent.getId()
774        ce = self.getCourseEntry(cid)
775        if ce:
776            return "%s" % ce.Title
777        return "No course with id %s" % cid
778
779InitializeClass(StudentCourseResult)
780
781def addStudentCourseResult(container, id, REQUEST=None, **kw):
782    """Add a StudentCourseResult."""
783    ob = StudentCourseResult(id, **kw)
784    return CPSBase_adder(container, ob, REQUEST=REQUEST)
785###)
786
787class StudentPume(CPSDocument): ###(
788    """
789    WAeUP Student container for the various student data
790    """
791    meta_type = 'StudentPume'
792    portal_type = meta_type
793    security = ClassSecurityInfo()
794
795    security.declareProtected(View,"Title")
796    def Title(self):
797        """compose title"""
798        return "PUME Results"
799
800
801InitializeClass(StudentPume)
802
803def addStudentPume(container, id, REQUEST=None, **kw):
804    """Add a Students PUME data."""
805    ob = StudentPume(id, **kw)
806    return CPSBase_adder(container, ob, REQUEST=REQUEST)
807
808
809
810# Backward Compatibility StudyLevel
811
812from Products.WAeUP_SRP.Academics import StudyLevel
813
814from Products.WAeUP_SRP.Academics import addStudyLevel
815
Note: See TracBrowser for help on using the repository browser.