source: WAeUP_SRP/base/Students.py @ 2994

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

fix title for accommodation object

  • Property svn:keywords set to Id
File size: 29.8 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 2923 2007-12-11 21:04:18Z 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_id = content.session
597        try:
598            y = int(session_id[-2:])
599        except:
600            return "Accommodation Data for Session %s" % session_id
601        session_str = self.portal_vocabularies.sessions.get(y)
602        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
603        return "Accommodation Data for Session %s" % session_str
604
605
606InitializeClass(StudentAccommodation)
607
608def addStudentAccommodation(container, id, REQUEST=None, **kw):
609    """Add a Students personal data."""
610    ob = StudentAccommodation(id, **kw)
611    return CPSBase_adder(container, ob, REQUEST=REQUEST)
612
613###)
614
615class StudentPersonal(CPSDocument): ###(
616    """
617    WAeUP Student container for the various student data
618    """
619    meta_type = 'StudentPersonal'
620    portal_type = meta_type
621    security = ClassSecurityInfo()
622
623    security.declareProtected(View,"Title")
624    def Title(self):
625        """compose title"""
626        #content = self.getContent()
627        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
628        return "Personal Data"
629
630
631InitializeClass(StudentPersonal)
632
633def addStudentPersonal(container, id, REQUEST=None, **kw):
634    """Add a Students personal data."""
635    ob = StudentPersonal(id, **kw)
636    return CPSBase_adder(container, ob, REQUEST=REQUEST)
637
638###)
639
640class StudentClearance(CPSDocument): ###(
641    """
642    WAeUP Student container for the various student data
643    """
644    meta_type = 'StudentClearance'
645    portal_type = meta_type
646    security = ClassSecurityInfo()
647
648    security.declareProtected(View,"Title")
649    def Title(self):
650        """compose title"""
651        #content = self.getContent()
652        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
653        return "Clearance/Eligibility Record"
654
655
656InitializeClass(StudentClearance)
657
658def addStudentClearance(container, id, REQUEST=None, **kw):
659    """Add a Students personal data."""
660    ob = StudentClearance(id, **kw)
661    return CPSBase_adder(container, ob, REQUEST=REQUEST)
662
663###)
664
665class StudentStudyLevel(CPSDocument): ###(
666    """
667    WAeUP Student container for the various student data
668    """
669    meta_type = 'StudentStudyLevel'
670    portal_type = meta_type
671    security = ClassSecurityInfo()
672
673    security.declareProtected(View,"Title")
674    def Title(self):
675        """compose title"""
676        return self.portal_vocabularies.student_levels.get(self.aq_parent.getId())
677        #return "Level %s" % self.aq_parent.getId()
678
679    def create_course_results(self,cert_id,current_level): ###(
680        "create all courses in a level"
681        aq_portal = self.portal_catalog.evalAdvancedQuery
682        res = self.portal_catalog(portal_type="Certificate", id = cert_id)
683        l = []
684        import transaction
685        if res:
686            cert = res[0]
687            path = cert.getPath()
688            query = Eq("path","%s/%s" % (path,current_level)) &\
689                    Eq('portal_type','CertificateCourse')
690            courses = aq_portal(query)
691            #from pdb import set_trace;set_trace()
692            self_proxy = self.aq_parent
693            for c in courses:
694                d = self.getCourseInfo(c.getId)
695                cr_id = self_proxy.invokeFactory('StudentCourseResult',c.getId)
696                course_result = getattr(self_proxy,cr_id)
697                self.portal_workflow.doActionFor(course_result,'open')
698                d['core_or_elective'] = getattr(c.getObject().getContent(),'core_or_elective')
699                course_result.getContent().edit(mapping=d)
700                #transaction.commit()
701    ###)
702
703InitializeClass(StudentStudyLevel)
704
705def addStudentStudyLevel(container, id, REQUEST=None, **kw):
706    """Add a Students personal data."""
707    ob = StudentStudyLevel(id, **kw)
708    return CPSBase_adder(container, ob, REQUEST=REQUEST)
709
710###)
711
712class StudentStudyCourse(CPSDocument): ###(
713    """
714    WAeUP Student container for the various student data
715    """
716    meta_type = 'StudentStudyCourse'
717    portal_type = meta_type
718    security = ClassSecurityInfo()
719
720    security.declareProtected(View,"Title")
721    def Title(self):
722        """compose title"""
723        #content = self.getContent()
724        return "Study Course"
725
726
727InitializeClass(StudentStudyCourse)
728
729def addStudentStudyCourse(container, id, REQUEST=None, **kw):
730    """Add a Students personal data."""
731    ob = StudentStudyCourse(id, **kw)
732    return CPSBase_adder(container, ob, REQUEST=REQUEST)
733
734###)
735
736class StudentApplication(CPSDocument): ###(
737    """
738    WAeUP Student container for the various student data
739    """
740    meta_type = 'StudentApplication'
741    portal_type = meta_type
742    security = ClassSecurityInfo()
743
744    security.declareProtected(View,"Title")
745    def Title(self):
746        """compose title"""
747        return "Application Data"
748
749
750InitializeClass(StudentApplication)
751
752def addStudentApplication(container, id, REQUEST=None, **kw):
753    """Add a Students eligibility data."""
754    ob = StudentApplication(id, **kw)
755    return CPSBase_adder(container, ob, REQUEST=REQUEST)
756###)
757
758
759class StudentCourseResult(CPSDocument): ###(
760    """
761    WAeUP StudentCourseResult
762    """
763    meta_type = 'StudentCourseResult'
764    portal_type = meta_type
765    security = ClassSecurityInfo()
766
767    def getCourseEntry(self,cid):
768        res = self.portal_catalog({'meta_type': "Course",
769                                           'id': cid})
770        if res:
771            return res[-1]
772        else:
773            return None
774
775    security.declareProtected(View,"Title")
776    def Title(self):
777        """compose title"""
778        cid = self.aq_parent.getId()
779        ce = self.getCourseEntry(cid)
780        if ce:
781            return "%s" % ce.Title
782        return "No course with id %s" % cid
783
784InitializeClass(StudentCourseResult)
785
786def addStudentCourseResult(container, id, REQUEST=None, **kw):
787    """Add a StudentCourseResult."""
788    ob = StudentCourseResult(id, **kw)
789    return CPSBase_adder(container, ob, REQUEST=REQUEST)
790###)
791
792class StudentPume(CPSDocument): ###(
793    """
794    WAeUP Student container for the various student data
795    """
796    meta_type = 'StudentPume'
797    portal_type = meta_type
798    security = ClassSecurityInfo()
799
800    security.declareProtected(View,"Title")
801    def Title(self):
802        """compose title"""
803        return "PUME Results"
804
805
806InitializeClass(StudentPume)
807
808def addStudentPume(container, id, REQUEST=None, **kw):
809    """Add a Students PUME data."""
810    ob = StudentPume(id, **kw)
811    return CPSBase_adder(container, ob, REQUEST=REQUEST)
812
813
814
815# Backward Compatibility StudyLevel
816
817from Products.WAeUP_SRP.Academics import StudyLevel
818
819from Products.WAeUP_SRP.Academics import addStudyLevel
820
Note: See TracBrowser for help on using the repository browser.