source: WAeUP_SRP/base/Students.py @ 3077

Last change on this file since 3077 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
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 2923 2007-12-11 21:04:18Z 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
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:
[1834]185                    em = 'No certificate with ID %s \n' % cert_id
[1820]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'
[2124]199                logger.info('%s (%s) %s' % (student_brain.id, old_matric_no, em))
[1820]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)
[1834]210            new_study_course = result.get('study_course',None)
[1820]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
[2662]220            try:
[2912]221                icl = int(old_current_level)
[2662]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
[1880]231            if study_course.objectIds():
[1834]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)
[2124]233                logger.info('%s (%s) %s' % (student_brain.id, old_matric_no, em))
[1820]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
[1834]253            dsc['study_course'] = new_study_course
[1820]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
[1146]285
[1970]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)
[2083]298        fields.append('state')
[1970]299        headline = ','.join(fields)
[2128]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,)
[1970]306        format = '"%(' + ')s","%('.join(fields) + ')s"'
307        students = self.students_catalog()
308        nr2export = len(students)
[2012]309        logger.info('%s starts dumpStudentsCatalog, %s student records to export' % (member,nr2export))
[1970]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)
[2125]317            d['state'],d['lga'] = formatLGA(d['lga'],voc = self.portal_vocabularies.local_gov_areas)
[2128]318            #lines.append(format % d)
319            lines.append(d)
[1970]320            total += 1
321            if total and not total % chunk or total == len(students):
[2128]322                #open(export_file,"a").write('\n'.join(lines) +'\n')
323                csv_writer.writerows(lines)
[1970]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
[1146]356    security.declareProtected(ModifyPortalContent,"importResults")###(
357    def importResults(self):
[1151]358        """load Returning Students Results from CSV"""
[1146]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")
[1802]364        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
365        students_folder = self.portal_url.getPortalObject().campus.students
[1146]366        tr_count = 1
[2072]367        total = 0
[1146]368        #name = 'pume_results'
369        name = 'Results'
370        table = self.results_import
371        no_import = []
372        imported = []
[1571]373        logger = logging.getLogger('Students.StudentsFolder.importResults')
[1146]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
[2071]379
[1146]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
[1571]393                logger.info('Start loading from %s.csv' % name)
[1321]394                s = ','.join(['"%s"' % fn for fn in result.keys()])
[1146]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')
[1448]401            if not course_id:
402                course_id = 'N/A'
403                result['CosCode'] = course_id
[1168]404            matric_no = result.get('matric_no').upper()
405            result['matric_no'] = matric_no
406            key = matric_no+course_id
407            if matric_no == '':
[1252]408                result['Error'] = "Empty matric_no"
[1146]409                no_import.append( format_error % result)
410                continue
[1168]411            if key in regs or self.results_import(key = key):
[1252]412                result['Error'] = "Duplicate"
[1146]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)
[1829]422
[1816]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
[1829]431
[1146]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(
[1151]438                             '\n'.join(no_import)+'\n')
[1146]439                    no_import = []
440                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
[1151]441                                            '\n'.join(imported) + '\n')
[1146]442                imported = []
443                if no_course_list:
444                    open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
[1151]445                                            '\n'.join(no_course_list) + '\n')
[1146]446                    no_course_list = []
447                transaction.commit()
[1168]448                regs = []
[2072]449                total += tr_count
[2080]450                em = '%d transactions totally comitted, %s courses not found ' % (total,course_count)
451                logger.info(em)
[2072]452                tr_count = 0
[1146]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))
[2072]460        em = '%d transactions totally committed, %s courses not found ' % (total,course_count)
[1393]461        logger.info(em)
[1146]462        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
463    ###)
464
[1065]465
[2654]466
[1594]467    security.declareProtected(View,"fixOwnership") ###(
[511]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',])
[1594]476    ###)
[603]477
[1594]478    security.declareProtected(View,"Title") ###(
[364]479    def Title(self):
480        """compose title"""
[382]481        return "Student Section"
[1594]482    ###)
[361]483
[1700]484    def generateStudentId(self,letter,students = None): ###(
[714]485        import random
486        r = random
[1700]487        if students is None:
488            students = self.portal_url.getPortalObject().campus.students
[714]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))
[758]494        return sid
[714]495        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
496    ###)
497
[361]498InitializeClass(StudentsFolder)
499
[1594]500def addStudentsFolder(container, id, REQUEST=None, **kw): ###(
[361]501    """Add a Student."""
502    ob = StudentsFolder(id, **kw)
503    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[1594]504    ###)
505
[361]506###)
507
[57]508class Student(CPSDocument): ###(
509    """
[154]510    WAeUP Student container for the various student data
[57]511    """
512    meta_type = 'Student'
513    portal_type = meta_type
514    security = ClassSecurityInfo()
[154]515
[152]516    security.declareProtected(View,"Title")
517    def Title(self):
518        """compose title"""
[153]519        reg_nr = self.getId()[1:]
[362]520        data = getattr(self,'personal',None)
[152]521        if data:
522            content = data.getContent()
[1143]523            return "%s %s %s" % (content.firstname,content.middlename,content.lastname)
[472]524        data = getattr(self,'application',None)
[464]525        if data:
526            content = data.getContent()
527            return "%s" % (content.jamb_lastname)
[152]528        return self.title
[154]529
[511]530    security.declarePrivate('makeStudentMember') ###(
531    def makeStudentMember(self,sid,password='uNsEt'):
532        """make the student a member"""
533        membership = self.portal_membership
[603]534        membership.addMember(sid,
[511]535                             password ,
536                             roles=('Member',
537                                     'Student',
[522]538                                     ),
[511]539                             domains='',
[904]540                             properties = {'memberareaCreationFlag': False,
541                                           'homeless': True},)
[511]542        member = membership.getMemberById(sid)
543        self.portal_registration.afterAdd(member, sid, password, None)
544        self.manage_setLocalRoles(sid, ['Owner',])
545
546###)
547
[764]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)
[927]570        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
[764]571        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
[603]572
[511]573###)
574
[57]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###)
[91]583
[639]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()
[2920]596        session_id = content.session
597        try:
[2923]598            y = int(session_id[-2:])
[2920]599        except:
600            return "Accommodation Data for Session %s" % session_id
601        session_str = self.portal_vocabularies.sessions.get(y)
[639]602        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
[2912]603        return "Accommodation Data for Session %s" % session_str
[639]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
[89]615class StudentPersonal(CPSDocument): ###(
616    """
[154]617    WAeUP Student container for the various student data
[89]618    """
619    meta_type = 'StudentPersonal'
620    portal_type = meta_type
621    security = ClassSecurityInfo()
[152]622
623    security.declareProtected(View,"Title")
624    def Title(self):
625        """compose title"""
[2912]626        #content = self.getContent()
[364]627        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
628        return "Personal Data"
[152]629
[154]630
[89]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
[423]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"""
[2912]651        #content = self.getContent()
[840]652        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
653        return "Clearance/Eligibility Record"
[423]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
[454]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"""
[2640]676        return self.portal_vocabularies.student_levels.get(self.aq_parent.getId())
677        #return "Level %s" % self.aq_parent.getId()
[454]678
[1700]679    def create_course_results(self,cert_id,current_level): ###(
[1649]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)
[1820]700                #transaction.commit()
[1700]701    ###)
[472]702
[454]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
[362]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
[364]720    security.declareProtected(View,"Title")
721    def Title(self):
722        """compose title"""
[2912]723        #content = self.getContent()
[453]724        return "Study Course"
[362]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
[472]736class StudentApplication(CPSDocument): ###(
[179]737    """
738    WAeUP Student container for the various student data
739    """
[472]740    meta_type = 'StudentApplication'
[179]741    portal_type = meta_type
742    security = ClassSecurityInfo()
743
[181]744    security.declareProtected(View,"Title")
745    def Title(self):
746        """compose title"""
[472]747        return "Application Data"
[179]748
[181]749
[472]750InitializeClass(StudentApplication)
[179]751
[472]752def addStudentApplication(container, id, REQUEST=None, **kw):
[179]753    """Add a Students eligibility data."""
[472]754    ob = StudentApplication(id, **kw)
[179]755    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[763]756###)
[179]757
[758]758
[464]759class StudentCourseResult(CPSDocument): ###(
[89]760    """
[464]761    WAeUP StudentCourseResult
[89]762    """
[464]763    meta_type = 'StudentCourseResult'
[89]764    portal_type = meta_type
765    security = ClassSecurityInfo()
[472]766
[454]767    def getCourseEntry(self,cid):
[723]768        res = self.portal_catalog({'meta_type': "Course",
[454]769                                           'id': cid})
770        if res:
771            return res[-1]
772        else:
773            return None
[154]774
[454]775    security.declareProtected(View,"Title")
776    def Title(self):
777        """compose title"""
[723]778        cid = self.aq_parent.getId()
[454]779        ce = self.getCourseEntry(cid)
780        if ce:
781            return "%s" % ce.Title
782        return "No course with id %s" % cid
[152]783
[464]784InitializeClass(StudentCourseResult)
[454]785
[464]786def addStudentCourseResult(container, id, REQUEST=None, **kw):
787    """Add a StudentCourseResult."""
788    ob = StudentCourseResult(id, **kw)
[89]789    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[139]790###)
791
[2912]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
[579]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.