source: WAeUP_SRP/base/Students.py @ 2692

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

catch ValueError?: invalid literal for int()

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