source: WAeUP_SRP/base/Students.py @ 3222

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

resolve #90 fc

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