source: WAeUP_SRP/base/Students.py @ 3164

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

resolve #90 fc

  • Property svn:keywords set to Id
File size: 29.7 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 3164 2008-02-14 12:29:53Z henrik $
[708]3from string import Template
[45]4from Globals import InitializeClass
5from AccessControl import ClassSecurityInfo
[164]6from AccessControl.SecurityManagement import newSecurityManager
[429]7from zExceptions import BadRequest
[502]8from Products.ZCatalog.ZCatalog import ZCatalog
[47]9from Products.CMFCore.utils import UniqueObject, getToolByName
[45]10from Products.CMFCore.permissions import View
11from Products.CMFCore.permissions import ModifyPortalContent
[154]12from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
13#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
14from Products.CPSDocument.CPSDocument import CPSDocument
15from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
[164]16from Products.CPSCore.CPSMembershipTool import CPSUnrestrictedUser
[361]17from Products.WAeUP_SRP.Academics import makeCertificateCode
[2125]18
[1649]19from Products.AdvancedQuery import Eq, Between, Le,In
[1820]20import DateTime
[362]21import logging
[971]22import csv,re,os
[362]23import Globals
24p_home = Globals.package_home(globals())
25i_home = Globals.INSTANCE_HOME
[981]26MAX_TRANS = 1000
[1599]27from urllib import urlencode
28
[966]29import DateTime
[1801]30#import PIL.Image
[971]31from StringIO import StringIO
[154]32
[958]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
[1939]44def response_write(response,s): ###(
[1599]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
[1939]53###)
54
[958]55def getInt(s): ###(
[723]56    try:
57        return int(s)
58    except:
59        return 0
[422]60
[725]61def getFloat(s):
62    try:
63        return float(s)
64    except:
65        return 0.0
66
[958]67###)
68
[714]69def getStudentByRegNo(self,reg_no): ###(
[502]70    """search student by JAMB Reg No and return StudentFolder"""
[1969]71    res = self.students_catalog(jamb_reg_no = reg_no.upper())
[1902]72    if len(res) == 1:
73        return getattr(self.portal_url.getPortalObject().campus.students,res[0].id)
74    else:
[502]75        return None
[1902]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
[502]83
[714]84###)
85
[1939]86def checkJambNo(jnr): ###(
[1111]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
[1119]97
[1939]98###)
99
[2125]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()
[1939]109
[361]110class StudentsFolder(CPSDocument): ###(
111    """
112    WAeUP container for the various WAeUP containers data
113    """
[362]114    meta_type = 'StudentsFolder'
[361]115    portal_type = meta_type
116    security = ClassSecurityInfo()
[154]117
[1799]118
[1820]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:
[1834]172                em = 'Student with matric_no %s not found' % old_matric_no
[1820]173                logger.info(em)
[1834]174                result['Error'] = "Student does not exist"
[1820]175                not_imported.append(format_error % result)
176                total_not_imported += 1
177                continue
[3164]178            student_record = res[0]
179            if getattr(student_record,'review_state','') in ('courses_registered','courses_validated'):
[3146]180                em = 'already registered course list'
[3164]181                logger.info('%s (%s) %s' % (student_record.id, old_matric_no, em))
[3146]182                result['Error'] = em
183                not_imported.append( format_error % result)
184                total_not_imported += 1
[3164]185                continue
186            student_object = getattr(students_folder,student_record.id)
187            result['id'] = student_record.id
[1820]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:
[1834]192                    em = 'No certificate with ID %s \n' % cert_id
[1820]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'
[3164]206                logger.info('%s (%s) %s' % (student_record.id, old_matric_no, em))
[1820]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)
[1834]217            new_study_course = result.get('study_course',None)
[1820]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
[2662]227            try:
[2912]228                icl = int(old_current_level)
[2662]229                if icl == int(old_current_level) and old_study_course == new_study_course:
230                    em = 'Already transferred'
[3164]231                    logger.info('%s (%s) %s' % (student_record.id, old_matric_no, em))
[2662]232                    result['Error'] = em
233                    not_imported.append( format_error % result)
234                    total_not_imported += 1
235                    continue
236            except:
237                pass
[3146]238
[1820]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
[1834]254            dsc['study_course'] = new_study_course
[1820]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
[1146]286
[1970]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)
[2083]299        fields.append('state')
[1970]300        headline = ','.join(fields)
[2128]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,)
[1970]307        format = '"%(' + ')s","%('.join(fields) + ')s"'
308        students = self.students_catalog()
309        nr2export = len(students)
[2012]310        logger.info('%s starts dumpStudentsCatalog, %s student records to export' % (member,nr2export))
[1970]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)
[2125]318            d['state'],d['lga'] = formatLGA(d['lga'],voc = self.portal_vocabularies.local_gov_areas)
[2128]319            #lines.append(format % d)
320            lines.append(d)
[1970]321            total += 1
322            if total and not total % chunk or total == len(students):
[2128]323                #open(export_file,"a").write('\n'.join(lines) +'\n')
324                csv_writer.writerows(lines)
[1970]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
[1146]357    security.declareProtected(ModifyPortalContent,"importResults")###(
358    def importResults(self):
[1151]359        """load Returning Students Results from CSV"""
[1146]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")
[1802]365        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
366        students_folder = self.portal_url.getPortalObject().campus.students
[1146]367        tr_count = 1
[2072]368        total = 0
[1146]369        #name = 'pume_results'
370        name = 'Results'
371        table = self.results_import
372        no_import = []
373        imported = []
[1571]374        logger = logging.getLogger('Students.StudentsFolder.importResults')
[1146]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
[2071]380
[1146]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
[1571]394                logger.info('Start loading from %s.csv' % name)
[1321]395                s = ','.join(['"%s"' % fn for fn in result.keys()])
[1146]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')
[1448]402            if not course_id:
403                course_id = 'N/A'
404                result['CosCode'] = course_id
[1168]405            matric_no = result.get('matric_no').upper()
406            result['matric_no'] = matric_no
407            key = matric_no+course_id
408            if matric_no == '':
[1252]409                result['Error'] = "Empty matric_no"
[1146]410                no_import.append( format_error % result)
411                continue
[1168]412            if key in regs or self.results_import(key = key):
[1252]413                result['Error'] = "Duplicate"
[1146]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)
[1829]423
[1816]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
[1829]432
[1146]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(
[1151]439                             '\n'.join(no_import)+'\n')
[1146]440                    no_import = []
441                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
[1151]442                                            '\n'.join(imported) + '\n')
[1146]443                imported = []
444                if no_course_list:
445                    open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
[1151]446                                            '\n'.join(no_course_list) + '\n')
[1146]447                    no_course_list = []
448                transaction.commit()
[1168]449                regs = []
[2072]450                total += tr_count
[2080]451                em = '%d transactions totally comitted, %s courses not found ' % (total,course_count)
452                logger.info(em)
[2072]453                tr_count = 0
[1146]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))
[2072]461        em = '%d transactions totally committed, %s courses not found ' % (total,course_count)
[1393]462        logger.info(em)
[1146]463        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
464    ###)
465
[1065]466
[2654]467
[1594]468    security.declareProtected(View,"fixOwnership") ###(
[511]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',])
[1594]477    ###)
[603]478
[1594]479    security.declareProtected(View,"Title") ###(
[364]480    def Title(self):
481        """compose title"""
[382]482        return "Student Section"
[1594]483    ###)
[361]484
[1700]485    def generateStudentId(self,letter,students = None): ###(
[714]486        import random
487        r = random
[1700]488        if students is None:
489            students = self.portal_url.getPortalObject().campus.students
[714]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))
[758]495        return sid
[714]496        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
497    ###)
498
[361]499InitializeClass(StudentsFolder)
500
[1594]501def addStudentsFolder(container, id, REQUEST=None, **kw): ###(
[361]502    """Add a Student."""
503    ob = StudentsFolder(id, **kw)
504    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[1594]505    ###)
506
[361]507###)
508
[57]509class Student(CPSDocument): ###(
510    """
[154]511    WAeUP Student container for the various student data
[57]512    """
513    meta_type = 'Student'
514    portal_type = meta_type
515    security = ClassSecurityInfo()
[154]516
[152]517    security.declareProtected(View,"Title")
518    def Title(self):
519        """compose title"""
[153]520        reg_nr = self.getId()[1:]
[362]521        data = getattr(self,'personal',None)
[152]522        if data:
523            content = data.getContent()
[1143]524            return "%s %s %s" % (content.firstname,content.middlename,content.lastname)
[472]525        data = getattr(self,'application',None)
[464]526        if data:
527            content = data.getContent()
528            return "%s" % (content.jamb_lastname)
[152]529        return self.title
[154]530
[511]531    security.declarePrivate('makeStudentMember') ###(
532    def makeStudentMember(self,sid,password='uNsEt'):
533        """make the student a member"""
534        membership = self.portal_membership
[603]535        membership.addMember(sid,
[511]536                             password ,
537                             roles=('Member',
538                                     'Student',
[522]539                                     ),
[511]540                             domains='',
[904]541                             properties = {'memberareaCreationFlag': False,
542                                           'homeless': True},)
[511]543        member = membership.getMemberById(sid)
544        self.portal_registration.afterAdd(member, sid, password, None)
545        self.manage_setLocalRoles(sid, ['Owner',])
546
547###)
548
[764]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)
[927]571        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
[764]572        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]573
[511]574###)
575
[57]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###)
[91]584
[639]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()
[2920]597        session_id = content.session
598        try:
[2923]599            y = int(session_id[-2:])
[2920]600        except:
601            return "Accommodation Data for Session %s" % session_id
602        session_str = self.portal_vocabularies.sessions.get(y)
[639]603        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
[2912]604        return "Accommodation Data for Session %s" % session_str
[639]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
[89]616class StudentPersonal(CPSDocument): ###(
617    """
[154]618    WAeUP Student container for the various student data
[89]619    """
620    meta_type = 'StudentPersonal'
621    portal_type = meta_type
622    security = ClassSecurityInfo()
[152]623
624    security.declareProtected(View,"Title")
625    def Title(self):
626        """compose title"""
[2912]627        #content = self.getContent()
[364]628        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
629        return "Personal Data"
[152]630
[154]631
[89]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
[423]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"""
[2912]652        #content = self.getContent()
[840]653        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
654        return "Clearance/Eligibility Record"
[423]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
[454]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"""
[2640]677        return self.portal_vocabularies.student_levels.get(self.aq_parent.getId())
678        #return "Level %s" % self.aq_parent.getId()
[454]679
[1700]680    def create_course_results(self,cert_id,current_level): ###(
[1649]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)
[1820]701                #transaction.commit()
[1700]702    ###)
[472]703
[454]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
[362]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
[364]721    security.declareProtected(View,"Title")
722    def Title(self):
723        """compose title"""
[2912]724        #content = self.getContent()
[453]725        return "Study Course"
[362]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
[472]737class StudentApplication(CPSDocument): ###(
[179]738    """
739    WAeUP Student container for the various student data
740    """
[472]741    meta_type = 'StudentApplication'
[179]742    portal_type = meta_type
743    security = ClassSecurityInfo()
744
[181]745    security.declareProtected(View,"Title")
746    def Title(self):
747        """compose title"""
[472]748        return "Application Data"
[179]749
[181]750
[472]751InitializeClass(StudentApplication)
[179]752
[472]753def addStudentApplication(container, id, REQUEST=None, **kw):
[179]754    """Add a Students eligibility data."""
[472]755    ob = StudentApplication(id, **kw)
[179]756    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]757###)
[179]758
[758]759
[464]760class StudentCourseResult(CPSDocument): ###(
[89]761    """
[464]762    WAeUP StudentCourseResult
[89]763    """
[464]764    meta_type = 'StudentCourseResult'
[89]765    portal_type = meta_type
766    security = ClassSecurityInfo()
[472]767
[454]768    def getCourseEntry(self,cid):
[723]769        res = self.portal_catalog({'meta_type': "Course",
[454]770                                           'id': cid})
771        if res:
772            return res[-1]
773        else:
774            return None
[154]775
[454]776    security.declareProtected(View,"Title")
777    def Title(self):
778        """compose title"""
[723]779        cid = self.aq_parent.getId()
[454]780        ce = self.getCourseEntry(cid)
781        if ce:
782            return "%s" % ce.Title
783        return "No course with id %s" % cid
[152]784
[464]785InitializeClass(StudentCourseResult)
[454]786
[464]787def addStudentCourseResult(container, id, REQUEST=None, **kw):
788    """Add a StudentCourseResult."""
789    ob = StudentCourseResult(id, **kw)
[89]790    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]791###)
792
[2912]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
[579]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.