source: WAeUP_SRP/trunk/Academics.py @ 589

Last change on this file since 589 was 583, checked in by joachim, 18 years ago

fixed no such course issue

  • Property svn:keywords set to Id
File size: 53.5 KB
Line 
1#-*- mode: python; mode: fold -*-
2from Globals import InitializeClass
3from AccessControl import ClassSecurityInfo
4
5from Products.CMFCore.utils import UniqueObject, getToolByName
6from Products.CMFCore.permissions import View
7from Products.CMFCore.permissions import ModifyPortalContent
8from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
9#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
10from Products.CPSDocument.CPSDocument import CPSDocument
11#from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
12#from Products.CPSCore.CPSBase import CPSBaseBTreeDocument as BaseBTreeDocument
13#from Products.CMFCore.DirectoryView import registerDirectory
14
15#registerDirectory('skins', globals())
16#registerDirectory('skins/waeup_default', globals())
17#registerDirectory('skins/waeup_faculty', globals())
18
19import DateTime
20import csv,re
21import logging
22import Globals
23p_home = Globals.package_home(globals())
24i_home = Globals.INSTANCE_HOME
25
26def makeCertificateCode(code):
27    code = code.replace('.','')
28    code = code.replace('(','')
29    code = code.replace(')','')
30    code = code.replace('/','')
31    code = code.replace(' ','')
32    code = code.replace('_','')
33    return code
34
35class AcademicsFolder(CPSDocument): ###(
36    """
37    WAeUP AcademicsFolder containing StudyCourses
38    """
39    meta_type = 'AcademicsFolder'
40    portal_type = meta_type
41    security = ClassSecurityInfo()
42    use_catalog_for_folder_contents = True
43
44    security.declareProtected(View,"Title")
45    def Title(self):
46        """compose title"""
47        return "Academic Section"
48
49    security.declareProtected(ModifyPortalContent,"loadFacultiesFromCSV")###(
50    def loadFacultiesFromCSV(self):
51        """install Universityspecific Faculies from CSV values"""
52        #return
53        name = 'Faculties'
54        no_import = False
55        logger = logging.getLogger('%s_csv_import' % name)
56        logger.info('Start loading from %s.csv' % name)
57        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
58        try:
59            faculties = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
60        except:
61            logger.error('Error reading %s.csv' % name)
62            return
63        l = self.portal_catalog({'meta_type': "Faculty"})
64        facs = {}
65        for f in l:
66            facs[f.id] = f.getObject()
67        fields = ("code",
68                  "review_state",
69                  "title",
70                  "title_prefix",
71                  "college_code",
72                  "degree_grade",
73                  "bank_code",
74                  )
75        format = ' '.join(['%%(%s)s ' % fn for fn in fields])
76        for faculty in faculties:
77            processing = "processing %s" % format
78            logger.info(processing % faculty)
79            fid = faculty.get('code')
80            f = facs.get(fid,None)
81            if f is None:
82                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
83                logger.info('Creating Faculty with ID %(code)s %(title)s' % faculty)
84                academics.invokeFactory('Faculty', fid)
85                f = getattr(self,fid)
86                d = {'Title': faculty.get('title')}
87            else:
88                d = {}
89            f.getContent().edit(mapping=faculty)
90        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
91    ###)
92
93    security.declareProtected(ModifyPortalContent,"loadDepartmentsFromCSV")###(
94    def loadDepartmentsFromCSV(self):
95        """install Universityspecific Faculies from CSV values"""
96        #return
97        name = 'Departments'
98        no_import = False
99        logger = logging.getLogger('loaddepartments')
100        fields = ("code",
101                  "review_state",
102                  "title",
103                  "title_prefix",
104                  "faculty_code",
105                  )
106        format = ' '.join(['%%(%s)s ' % fn for fn in fields])
107        try:
108            deps = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
109        except:
110            logger.error('Error reading %s.csv' % name)
111            return
112        no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
113        heading = ' '.join(['"%s"' % fn for fn in fields])
114        no_import.write('%s\n' % heading)
115        l = self.portal_catalog({'meta_type': "Faculty"})
116        facs = {}
117        for f in l:
118            facs[f.id] = f.getObject()
119        for dep in deps:
120            processing = "processing %s" % format
121            logger.info(processing % dep)
122            fid = dep['faculty_code']
123            f = facs.get(fid,None)
124            if f is None:
125                logger.info( "No Faculty with ID: %s" % fid)
126                no_import.write( "No Faculty with ID: %s\n" % fid)
127                no_import.write(format % dep + "\n")
128            else:
129                did = dep.get('code')
130                d = getattr(f,did,None)
131                if d is None or d.portal_type == "Faculty":
132                    logger.info('Creating Department %(code)s = %(title)s' % dep)
133                    f.invokeFactory('Department', did)
134                    d = getattr(f,did)
135                    d.invokeFactory('CoursesFolder','courses')
136                    courses = getattr(d,'courses')
137                    dict = {'Title': 'Courses'}
138                    courses.getContent().edit(mapping=dict)
139                    d.invokeFactory('CertificatesFolder','certificates')
140                    certificates = getattr(d,'certificates')
141                    dict = {'Title': 'Certificates'}
142                    certificates.getContent().edit(mapping=dict)
143                d.getContent().edit(mapping=dep)
144                   
145        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
146    ###)
147
148    security.declareProtected(ModifyPortalContent,"loadCoursesFromCSV")###(
149    def loadCoursesFromCSV(self):
150        """install Universityspecific Courses from CSV values"""
151        #return
152        wf = self.portal_workflow
153        name = 'Courses'
154        no_import = False
155        logger = logging.getLogger('loadcourses')
156        fields = ("code",
157                  "review_state",
158                  "title",
159                  "faculty_code",
160                  "department_code",
161                  "credits",
162                  "org_code",
163                  "passmark",
164                  "semester",
165                  "session",
166                  )
167        format = ' '.join(['%%(%s)s ' % fn for fn in fields])
168        try:
169            courses = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
170        except:
171            logger.error('Error reading %s.csv' % name)
172            return
173        no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
174        heading = ' '.join(['"%s"' % fn for fn in fields])
175        no_import.write('%s\n' % heading)
176        l = self.portal_catalog({'meta_type': "Faculty"})
177        facs = {}
178        for f in l:
179            facs[f.id] = f.getObject()
180        dl = self.portal_catalog({'meta_type': "Department"})
181        deps = {}
182        for d in dl:
183            deps[d.id] = d.getObject()
184        cl = self.portal_catalog({'meta_type': "Course"})
185        course_list = [ c.id for c in cl]
186        for course in courses:
187            processing = "processing %s" % format
188            logger.info(processing % course)
189            depid = course.get('department_code').upper()
190            if depid in deps.keys():
191                dept= deps.get(depid)
192            else:
193                msg = "Department %(department_code)s for Course %(code)s not found" % course
194                logger.info(msg)
195                no_import.write(msg)
196                no_import.write(format % course + "\n")
197                continue
198            course_id = course.get('code')
199            cf = dept.courses
200            c = getattr(cf,course_id,None)
201            if c is None:
202                logger.info('Creating Course %(code)s  %(title)s in Department %(department_code)s' % course)
203                cf.invokeFactory('Course', course_id)
204                c = getattr(cf,course_id)
205            c.getContent().edit(mapping=course)
206            review_state = course.get('review_state')
207            if review_state == "checked" and wf.getInfoFor(c,'review_state',None) != 'checked':
208                self.portal_workflow.doActionFor(c,'approve')
209        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
210    ###)
211
212    security.declareProtected(ModifyPortalContent,"loadCertificatesFromCSV")###(
213
214    def loadCertificatesFromCSV(self):
215        """install Universityspecific Certificates from CSV values"""
216        #return
217        name = 'Certificates'
218        wf = self.portal_workflow
219        no_import_list = []
220        logger = logging.getLogger('loadcertificates')
221        fields = ("code",
222                  "review_state",
223                  "title",
224                  "faculty_code",
225                  "department_code",
226                  "category",
227                  "end_level",
228                  "m_prefix",
229                  "max_elect",
230                  "max_pass",
231                  "n_core",
232                  "nr_years",
233                  "original_code",
234                  "probation_credits",
235                  "promotion_credits",
236                  "start_level",
237                  "admin_status",
238                  )
239        format = ' '.join(['%%(%s)s ' % fn for fn in fields])
240        try:
241            courses = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
242        except:
243            logger.error('Error reading %s.csv' % name)
244            return
245        try:
246            certificates = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
247        except:
248            logger.error('Error reading %s.csv' % name)
249            return
250        f_ids = [f.id for f in self.portal_catalog({'meta_type': "Faculty"})]
251        dl = self.portal_catalog({'meta_type': "Department"})
252        deps = {}
253        for d in dl:
254            deps[d.id] = d.getObject()
255        for certificate in certificates:
256            processing = "processing %s" % format
257            logger.info(processing % certificate)
258            depid = certificate.get('department_code')
259            facid = certificate.get('faculty_code')
260            if facid not in f_ids:
261                msg = 'Faculty %(faculty_code)s for %(code)s %(title)s not found' % certificate
262                logger.info(msg)
263                no_import_list.append(msg)
264                no_import_list.append(format % certificate + "\n")
265                continue
266            if not deps.has_key(depid):
267                msg = 'Department %(department_code)s for %(code)s %(title)s not found' % certificate
268                logger.info(msg)
269                no_import_list.append(msg)
270                no_import_list.append(format % certificate + "\n")
271                continue
272            dep = deps[depid]
273            cf= dep.certificates
274            code = certificate.get('code')
275            certificate_id = code
276            c = getattr(cf,certificate_id,None)
277            if c is None:
278                logger.info('Creating certificate %(code)s  %(title)s in Department %(department_code)s' % certificate)
279                cf.invokeFactory('Certificate', certificate_id)
280                c = getattr(cf,certificate_id)
281            c.getContent().edit(mapping=certificate)
282            review_state = c.get('review_state')
283            if review_state == "checked" and wf.getInfoFor(c,'review_state',None) != 'checked':
284                self.portal_workflow.doActionFor(c,'approve')
285        if no_import_list:
286            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
287            heading = ' '.join(['"%s"' % fn for fn in fields])
288            no_import.write('%s\n' % heading)
289            for line in no_import_list:
290                no_import.write(line)
291        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
292    ###)
293
294    security.declareProtected(ModifyPortalContent,"loadCertificateCoursesFromCSV")###(
295    def loadCertificateCoursesFromCSV(self):
296        """install Certificate Courses from CSV values"""
297        #return
298        logger = logging.getLogger('loadcertificatecourses')
299        name = 'CertificateCourses'
300        wf = self.portal_workflow
301        no_import_list = []
302        logger = logging.getLogger('loadcertificates')
303        fields = ("code",
304                  "review_state",
305                  "faculty_code",
306                  "department_code",
307                  "certificate_code",
308                  "level",
309                  "semester",
310                  "core_or_elective",
311                  )
312        format = ' '.join(['%%(%s)s ' % fn for fn in fields])
313        try:
314            cert_courses = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
315        except:
316            logger.error('Error reading %s.csv' % name)
317            return
318        d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
319        c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
320        l = self.portal_catalog({'meta_type': "Certificate"})
321        certs = {}
322        for f in l:
323            certs[f.id] = f.getObject()
324        for cert_course in cert_courses:
325            processing = "processing %s" % format
326            logger.info(processing % cert_course)
327            depid = cert_course.get('department_code')
328            course_code = cert_course.get('code')
329            code = cert_course.get('certificate_code')
330            if not code in certs.keys():
331                em = 'CertCode %(certificate_code)s for %(code)s not found\n' % cert_course
332                logger.info(em)
333                no_import_list.append(em)
334                no_import_list.append(format % cert_course + "\n")
335                continue
336            certificate = certs[code]
337            certificate_code = certificate.getId()
338            if course_code not in c_ids:
339                em = 'Course %(code)s for %(certificate_code)s Level %(level)s not found in Courses\n' % cert_course
340                logger.info(em)
341                no_import_list.append(em)
342                no_import_list.append(format % cert_course + "\n")
343                continue
344            if depid not in d_ids:
345                em = 'Department %(department_code)s for %(certificate_code)s not found\n' % cert_course
346                logger.info(em)
347                no_import_list.append(em)
348                no_import_list.append(format % cert_course + "\n")
349                continue
350            level = cert_course.get('level')
351            l = getattr(certificate,level,None)
352            if l is None:
353                logger.info('Creating Level %(level)s in certificate %(certificate_code)s' % cert_course)
354                certificate.invokeFactory('StudyLevel', level)
355                l = getattr(certificate, level)
356                l.getContent().edit(mapping={'Title': "Level %s" % level})
357            certificate.orderObjects('id')
358            if hasattr(l,course_code):
359                msg = 'Duplicate %(code)s in Level %(level)s' % cert_course
360                logger.info(msg)
361                no_import_list.append(msg + "\n")
362                no_import_list.append(format % cert_course + "\n")
363                continue
364            l.invokeFactory('CertificateCourse',course_code)
365            logger.info('Creating CertificateCourse %(code)s in certificate %(certificate_code)s Level %(level)s' % cert_course)
366            cc = getattr(l,course_code)
367            semester = 'first'
368            try:
369                sem = int(cert_course.get('semester'))
370                cert_course['semester'] = ('first','second')[sem - 1]
371            except:
372                pass
373            cert_course['core_or_elective'] = eval(cert_course['core_or_elective'])
374            cc.getContent().edit(mapping=cert_course)
375            review_state = cc.get('review_state')
376            if review_state == "checked" and wf.getInfoFor(cc,'review_state',None) != 'checked':
377                self.portal_workflow.doActionFor(cc,'approve')
378        if no_import_list:
379            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
380            heading = ' '.join(['"%s"' % fn for fn in fields])
381            no_import.write('%s\n' % heading)
382            for line in no_import_list:
383                no_import.write(line)
384        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
385    ###)
386
387    security.declareProtected(ModifyPortalContent,"loadFacultiesFromOrgCSV")###(
388    def loadFacultiesFromOrgCSV(self):
389        """install Universityspecific Faculies from CSV values"""
390        #return
391        name = 'Faculties'
392        no_import = False
393        logger = logging.getLogger('%s_import' % name)
394        logger.info('Start loading from %s.csv' % name)
395        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
396        try:
397            faculties = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
398        except:
399            logger.error('Error reading %s.csv' % name)
400            return
401        l = self.portal_catalog({'meta_type': "Faculty"})
402        facs = {}
403        for f in l:
404            facs[f.id] = f.getObject()
405        for faculty in faculties:
406            logger.info('processing %(Session)s %(FacultyCode)s %(Description)s %(CollegeCode)s %(FacultyKey)s %(Status)s %(degree_grade)s %(Bankcode)s' % faculty)
407            fid = faculty['FacultyCode']
408            f = facs.get(fid,None)
409            if f is None:
410                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
411                logger.info('Creating Faculty with ID %(FacultyCode)s %(Description)s' % faculty)
412                academics.invokeFactory('Faculty', fid)
413                f = getattr(self,fid)
414                d = {'Title': faculty['Description']}
415            else:
416                d = {}
417            d['bank_code'] = faculty.get("Bankcode")
418            d["degree_grade"] = faculty.get("degree_grade")
419            d['institution_type'] = 'faculty'
420            d['Description'] = ''
421            d['college_code'] = faculty.get('CollegeCode')
422            f.getContent().edit(mapping=d)
423        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
424    ###)
425
426    security.declareProtected(ModifyPortalContent,"yamlDumpFaculties")###(
427    def yamlDumpFaculties(self):
428        """dump Faculies to Yaml"""
429        #return
430        import yaml
431        logger = logging.getLogger('dumpfaculties')
432        logger.info('Start dumping Faculties')
433        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
434        l = self.portal_catalog({'meta_type': "Faculty"})
435        facs = {}
436        for f in l:
437            facs[f.id] = f.getObject()
438        for fid in facs.keys():
439            faculty = facs.get(fid).aq_self
440            logger.info('dumping %s %s ' % (faculty.id, faculty.title))
441            print yaml.dump(faculty)
442        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
443
444    ###)
445
446    security.declareProtected(ModifyPortalContent,"loadDepartmentsFromOrgCSV")###(
447    def loadDepartmentsFromOrgCSV(self):
448        """install Universityspecific Faculies from CSV values"""
449        #return
450        name = 'Departments'
451        no_import = False
452        logger = logging.getLogger('loaddepartments')
453        try:
454            deps = csv.DictReader(open("%s/import/departments.csv" % i_home,"rb"))
455        except:
456            logger.error('Error reading departments.csv')
457            return
458        l = self.portal_catalog({'meta_type': "Faculty"})
459        facs = {}
460        for f in l:
461            facs[f.id] = f.getObject()
462        for dep in deps:
463            logger.info('Processing %(Session)s %(DeptCode)s %(Description)s %(FacultyCode)s' % dep)
464            fid = dep['FacultyCode']
465            f = facs.get(fid,None)
466            if f is None:
467                logger.info( "No Faculty with ID: %s" % fid)
468                if not no_import:
469                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
470                    no_import.write('"Session","DeptCode","Description","FacultyCode"\n')
471                no_import.write( "No Faculty with ID: %s\n" % fid)
472                no_import.write('"%(Session)s","%(DeptCode)s","%(Description)s","%(FacultyCode)s"\n' % dep)
473            else:
474                did = dep.get('DeptCode')
475                d = getattr(f,did,None)
476                if d is None or d.portal_type == "Faculty":
477                    logger.info('Creating Department %(DeptCode)s = %(Description)s' % dep)
478                    f.invokeFactory('Department', did)
479                    d = getattr(f,did)
480                    dict = {'Title': dep['Description']}
481                    d.getContent().edit(mapping=dict)
482                    d.invokeFactory('CoursesFolder','courses')
483                    courses = getattr(d,'courses')
484                    dict = {'Title': 'Courses'}
485                    courses.getContent().edit(mapping=dict)
486                    d.invokeFactory('CertificatesFolder','certificates')
487                    certificates = getattr(d,'certificates')
488                    dict = {'Title': 'Certificates'}
489                    certificates.getContent().edit(mapping=dict)
490        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
491    ###)
492
493    security.declareProtected(ModifyPortalContent,"loadCoursesFromOrgCSV")###(
494    def loadCoursesFromOrgCSV(self):
495        """install Universityspecific Courses from CSV values"""
496        #return
497        name = 'Courses'
498        no_import = False
499        logger = logging.getLogger('loadcourses')
500        try:
501            courses = csv.DictReader(open("%s/import/courses.csv" % i_home,"rb"))
502        except:
503            logger.error('Error reading courses.csv')
504            return
505        l = self.portal_catalog({'meta_type': "Faculty"})
506        facs = {}
507        for f in l:
508            facs[f.id] = f.getObject()
509        dl = self.portal_catalog({'meta_type': "Department"})
510        deps = {}
511        for d in dl:
512            deps[d.id] = d.getObject()
513        cl = self.portal_catalog({'meta_type': "Course"})
514        course_list = [ c.id for c in cl]
515        for course in courses:
516            logger.info('Processing %(CourseCode)s %(Description)s %(Credits)s %(Dept)s %(Semester)s %(Session)s %(PassMark)s %(Category)s %(AdmStatus)s' % course)
517##            if course.get("FORMERCODE").endswith('BITS'):
518##                continue
519            depid = course.get('Dept').upper()
520            if depid in deps.keys():
521                dept= deps.get(depid)
522    ##        elif depid in facs.keys():
523    ##            dept= facs.get(depid)
524            else:
525                logger.info("Dep %(Dept)s for Course %(CourseCode)s not found" % course)
526                if not no_import:
527                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
528                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","Category","AdmStatus"\n')
529                no_import.write("Dep %(Dept)s for Course %(CourseCode)s not found\n" % course)
530                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(Category)s","%(AdmStatus)s"\n' % course)
531                continue
532            course_id = ''.join(re.split('\W+',course.get('CourseCode')))
533            if len(course_id) == 3:
534                course_id = "%s000" % course_id
535            elif len(course_id) > 10:
536                logger.info("invalid course_code %(CourseCode)s" % course)
537                if not no_import:
538                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
539                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","Category","AdmStatus"\n')
540                no_import.write("invalid course_code %(CourseCode)s\n" % course)
541                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(Category)s","%(AdmStatus)s"\n' % course)
542                continue
543            courses = dept.courses
544            c = getattr(courses,course_id,None)
545            if c is None:
546                logger.info('Creating Course %(CourseCode)s  %(Description)s in Department %(Dept)s' % course)
547                courses.invokeFactory('Course', course_id)
548                c = getattr(courses,course_id)
549            dict = {'Title': course['Description']}
550            dict['code'] = course_id
551            dict['org_code'] = course.get('CourseCode')
552            dict['credits'] = course.get('Credits')
553            dict['semester'] = course.get('Semester')
554            dict['session'] = course.get('Session')
555            dict['category'] = course.get('Category')
556            dict['adm_status'] = course.get('AdmStatus')
557            dict['former_code'] = course.get('FORMERCODE')
558            pm = course.get('PassMark')
559            if pm.find(',') > -1:
560                pm.replace(',','.')
561            elif pm == "":
562                pm = "0.0"
563            try:
564                dict['passmark'] = int(float(pm))
565            except:
566                dict['passmark'] = 0
567            c.getContent().edit(mapping=dict)
568        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
569    ###)
570
571    security.declareProtected(ModifyPortalContent,"loadCertificatesFromOrgCSV")###(
572
573    def loadCertificatesFromOrgCSV(self):
574        """install Universityspecific Certificates from CSV values"""
575        #return
576        name = 'Certificates'
577        no_import = False
578        logger = logging.getLogger('loadcertificates')
579        try:
580            certificates = csv.DictReader(open("%s/import/certificates.csv" % i_home,"rb"))
581        except:
582            logger.error('Error reading certificates.csv')
583            return
584        f_ids = [f.id for f in self.portal_catalog({'meta_type': "Faculty"})]
585        #d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
586        dl = self.portal_catalog({'meta_type': "Department"})
587        deps = {}
588        for d in dl:
589            deps[d.id] = d.getObject()
590        for certificate in certificates:
591            logger.info('Processing %(CertCode)s %(Description)s %(Faculty)s %(MaxPass)s %(MaxLoad)s %(session)s %(PromotionCredits)s %(Probationcredits)s %(StartLevel)s %(endLevel)s %(Nyears)s %(Ncore)s %(MaxElect)s %(MPREFIX)s %(Dept)s %(Admstatus)s %(category)s' % certificate)
592            depid = certificate.get('Dept')
593            facid = certificate.get('Faculty')
594            if facid not in f_ids:
595                logger.info('Faculty %(Faculty)s for %(CertCode)s %(Description)s not found' % certificate)
596                if not no_import:
597                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
598                    no_import.write('"CertCode","Description","Faculty","MaxPass","MaxLoad","session","PromotionCredits","Probationcredits","StartLevel","endLevel","Nyears","Ncore","MaxElect","MPREFIX","Dept","Admstatus","category"\n')
599                no_import.write('Faculty %(Faculty)s for %(CertCode)s %(Description)s not found\n' % certificate)
600                no_import.write('"%(CertCode)s","%(Description)s","%(Faculty)s","%(MaxPass)s","%(MaxLoad)s","%(session)s","%(PromotionCredits)s","%(Probationcredits)s","%(StartLevel)s","%(endLevel)s","%(Nyears)s","%(Ncore)s","%(MaxElect)s","%(MPREFIX)s","%(Dept)s","%(Admstatus)s","%(category)s"\n' % certificate)
601                continue
602            if not deps.has_key(depid):
603                logger.info('Department %(Dept)s for %(CertCode)s %(Description)s not found' % certificate)
604                if not no_import:
605                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
606                    no_import.write('"CertCode","Description","Faculty","MaxPass","MaxLoad","session","PromotionCredits","Probationcredits","StartLevel","endLevel","Nyears","Ncore","MaxElect","MPREFIX","Dept","Admstatus","category"\n')
607                no_import.write('Department %(Dept)s for %(CertCode)s %(Description)s not found\n' % certificate)
608                no_import.write('"%(CertCode)s","%(Description)s","%(Faculty)s","%(MaxPass)s","%(MaxLoad)s","%(session)s","%(PromotionCredits)s","%(Probationcredits)s","%(StartLevel)s","%(endLevel)s","%(Nyears)s","%(Ncore)s","%(MaxElect)s","%(MPREFIX)s","%(Dept)s","%(Admstatus)s","%(category)s"\n' % certificate)
609                continue
610            #certificate_id = "%(category)s_%(Admstatus)s_%(Dept)s" % certificate
611            dep = deps[depid]
612            certificates = dep.certificates
613            code = makeCertificateCode(certificate.get('CertCode'))
614            certificate_id = code
615            c = getattr(certificates,certificate_id,None)
616            if c is None:
617                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
618                logger.info('Creating certificate %(CertCode)s  %(Description)s in Department %(Dept)s' % certificate)
619                certificates.invokeFactory('Certificate', certificate_id)
620                c = getattr(certificates,certificate_id)
621                dict = {'Title': certificate['Description']}
622                dict['code'] = code
623                dict['faculty'] = certificate.get('Faculty')
624                dict['department'] = certificate.get('Dept')
625                dict['max_pass'] = certificate.get('MaxPass')
626                dict['max_load'] = certificate.get('MaxLoad')
627                dict['admin_status'] = certificate.get('Admstatus')
628                dict['category'] = certificate.get('category')
629                dict['m_prefix'] = certificate.get('MPREFIX')
630                dict['nr_years'] = int(certificate.get('Nyears'))
631                nc = certificate.get('Ncore','1')
632                try:
633                    dict['n_core'] = int(nc)
634                except:
635                    dict['n_core'] = 1
636                dict['start_level'] = certificate.get('StartLevel')
637                dict['end_level'] = certificate.get('endLevel')
638                dict['promotion_credits'] = certificate.get('PromotionCredits')
639                dict['probation_credits'] = certificate.get('ProbationCredits')
640            else:
641                dict = {}
642            dict['original_code'] = certificate.get('CertCode')
643            print
644            c.getContent().edit(mapping=dict)
645        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
646    ###)
647
648    security.declareProtected(ModifyPortalContent,"loadCertificateCoursesFromOrgCSV")###(
649    def loadCertificateCoursesFromOrgCSV(self):
650        """install Certificate Courses from CSV values"""
651        #return
652        logger = logging.getLogger('loadcertificatecourses')
653        name = 'Certificate_courses'
654        no_import = False
655        try:
656            cert_courses = csv.DictReader(open("%s/import/course_level_courses.csv" % i_home,"rb"))
657        except:
658            logger.error('Error reading course_level_courses.csv')
659            return
660        d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
661        c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
662        l = self.portal_catalog({'meta_type': "Certificate"})
663        certs = {}
664        for f in l:
665            certs[f.id] = f.getObject()
666        for cert_course in cert_courses:
667            logger.info('Processing %(CosCode)s %(CertCode)s %(Session)s %(Level)s %(Core)s %(Elective)s %(Mandatory)s %(AdmStatus)s %(Dept)s %(Semester)s' % cert_course)
668            depid = cert_course.get('Dept')
669            course_code = cert_course.get('CosCode')
670            code = cert_course.get('CertCode')
671            code = code.replace('.','')
672            code = code.replace('(','')
673            code = code.replace(')','')
674            code = code.replace('/','')
675            code = code.replace(' ','')
676            code = code.replace('_','')
677##            if cert_course.get('Session') != '2002/2003':
678##                continue
679##            certificate = self.portal_catalog({'meta_type': "Certificate",
680##                                               'SearchableText': code})
681##            if not certificate:
682            if not code in certs.keys():
683                #print code
684                em = 'CertCode %(CertCode)s for %(CosCode)s not found\n' % cert_course
685                logger.info(em)
686                if not no_import:
687                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
688                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
689                no_import.write(em)
690                no_import.write('"%(CosCode)s","%(CertCode)s","%(Session)s","%(Level)s","%(Core)s","%(Elective)s","%(Mandatory)s","%(AdmStatus)s","%(Dept)s","%(Semester)s"\n' % cert_course)
691                continue
692            certificate = certs[code]
693            certificate_code = certificate.getId()
694            if course_code not in c_ids:
695                em = 'CorseCode %(CosCode)s for %(CertCode)s not found in Courses\n' % cert_course
696                logger.info(em)
697                if not no_import:
698                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
699                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
700                no_import.write(em)
701                no_import.write('"%(CosCode)s","%(CertCode)s","%(Session)s","%(Level)s","%(Core)s","%(Elective)s","%(Mandatory)s","%(AdmStatus)s","%(Dept)s","%(Semester)s"\n' % cert_course)
702                continue
703            if depid not in d_ids:
704                em = 'Department %(Dept)s for %(CertCode)s not found\n' % cert_course
705                logger.info(em)
706                if not no_import:
707                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
708                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
709                no_import.write(em)
710                no_import.write('"%(CosCode)s","%(CertCode)s","%(Session)s","%(Level)s","%(Core)s","%(Elective)s","%(Mandatory)s","%(AdmStatus)s","%(Dept)s","%(Semester)s"\n' % cert_course)
711                continue
712            level = cert_course.get('Level')
713            l = getattr(certificate,level,None)
714            if l is None:
715                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
716                logger.info('Creating Level %(Level)s in certificate %(CertCode)s' % cert_course)
717                certificate.invokeFactory('StudyLevel', level)
718                l = getattr(certificate, level)
719                l.getContent().edit(mapping={'Title': "Level %s" % level})
720                l.invokeFactory('Semester','first')
721                l.invokeFactory('Semester','second')
722            certificate.orderObjects('id')
723            first_s = getattr(l,'first')
724            first_s.getContent().edit(mapping={'Title': 'First Semester'})
725            second_s = getattr(l,'second')
726            second_s.getContent().edit(mapping={'Title': 'Second Semester'})
727            if cert_course.get('Semester') == '1':
728                semester = first_s
729            else:
730                semester = second_s
731            if hasattr(semester,course_code):
732                logger.info('Duplicate %(CosCode)s in Level %(Level)s' % cert_course)
733                if not no_import:
734                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
735                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
736##                no_import.write('Duplicate %(CosCode)s in Level %(Level)s' % cert_course)
737##                no_import.write('"%(CosCode)s","%(CertCode)s","%(Session)s","%(Level)s","%(Core)s","%(Elective)s","%(Mandatory)s","%(AdmStatus)s","%(Dept)s","%(Semester)s"\n' % cert_course)
738                continue
739            semester.invokeFactory('CertificateCourse',course_code)
740            cc = getattr(semester,course_code)
741            dict = {}
742            dict['code'] = cert_course.get('CosCode')
743            dict['certificate_code'] = code
744            dict['certificate_code_org'] = cert_course.get('CertCode')
745            dict['department'] = cert_course.get('Dept')
746            dict['admin_status'] = cert_course.get('Admstatus')
747            dict['session'] = cert_course.get('Session')
748            if cert_course.get('Core') != '':
749                dict['core_or_elective'] = True
750            else:
751                dict['core_or_elective'] = False
752            dict['level'] = cert_course.get('Level')
753            cc.getContent().edit(mapping=dict)
754        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
755    ###)
756
757    security.declareProtected(ModifyPortalContent,"exportFacultiesToCSV")###(
758    def exportFacultiesToCSV(self):
759        """export Faculies to CSV"""
760        #return
761        name = 'Faculties'
762        no_import = False
763        logger = logging.getLogger('%s_export' % name)
764        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
765        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
766        objects = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
767        export = []
768        export.append('"code","review_state","title","title_prefix","college_code","degree_grade","bank_code"')
769        for obj in objects:
770            logger.info('exporting %s %s ' % (obj.id, obj.title))
771            obj_d = obj.getContent()
772            di = {}
773            di['code'] = obj_d.code
774            di['title'] = obj_d.title
775            di['title_prefix'] = obj_d.title_prefix
776            di['college_code'] = obj_d.college_code
777            di['degree_grade'] = obj_d.degree_grade
778            di['bank_code'] = obj_d.bank_code
779            di['code'] = di['code'] or obj.id
780            di['review_state'] = self.portal_workflow.getInfoFor(obj,'review_state','no_state')
781            export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(college_code)s","%(degree_grade)s","%(bank_code)s"' % di)
782        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
783        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
784
785    ###)
786
787    security.declareProtected(ModifyPortalContent,"exportDepartmentsToCSV")###(
788    def exportDepartmentsToCSV(self):
789        """export Faculies to CSV"""
790        #return
791        import copy
792        name = 'Departments'
793        no_import = False
794        logger = logging.getLogger('%s_export' % name)
795        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
796        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
797        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
798        export = []
799        export.append('"code","review_state","title","title_prefix","faculty_code"')
800        #import pdb;pdb.set_trace()
801        for faculty in faculties:
802            di = {}
803            di['faculty_code'] = faculty.id
804            for department in faculty.objectValues():
805                department_d = department.getContent()
806                try:
807                    di['code'] =  department.getId()
808                    di['title'] = department_d.title
809                    di['title_prefix'] = department_d.title_prefix
810                    di['review_state'] = self.portal_workflow.getInfoFor(department,'review_state','no_state')
811                    export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(faculty_code)s"' % di)
812                    logger.info('exporting %s %s ' % (department.id, department.title))
813                except:
814                    logger.info('could not export %s %s ' % (department.id, department.title))
815                    continue
816        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
817        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
818    ###)
819
820    security.declareProtected(ModifyPortalContent,"exportCoursesToCSV")###(
821    def exportCoursesToCSV(self):
822        """export Courses to CSV"""
823        #return
824        name = 'Courses'
825        no_import = False
826        logger = logging.getLogger('%s_export' % name)
827        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
828        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
829        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
830        export = []
831        heading = '"code","review_state","title","faculty_code","department_code",'
832        heading += '"credits","org_code","passmark","semester","session"'
833        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
834        dataline += '"%(credits)s","%(org_code)s","%(passmark)s","%(semester)s","%(session)s"'
835        export.append(heading)
836        #import pdb;pdb.set_trace()
837        fields = ("title",
838                  "credits",
839                  "org_code",
840                  "passmark",
841                  "semester",
842                  "session",
843                  )
844        for faculty in faculties:
845            di = {}
846            di['faculty_code'] = faculty.id
847            for department in faculty.objectValues():
848                di['department_code'] = department.id
849                for course in department.courses.objectValues():
850                    di['code'] = course.getId()
851                    course_d = course.getContent()
852                    for f in fields:
853                        di[f] = getattr(course_d,f,None)
854                    di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
855                    export.append(dataline % di)
856                    logger.info('exporting %s %s ' % (course.id, course.title))
857                    continue
858        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
859        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
860    ###)
861
862    security.declareProtected(ModifyPortalContent,"exportCertificatesToCSV")###(
863    def exportCertificatesToCSV(self):
864        """export Certificates to CSV"""
865        #return
866        name = 'Certificates'
867        no_import = False
868        logger = logging.getLogger('%s_export' % name)
869        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
870        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
871        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
872        export = []
873        heading = '"code","review_state","title","faculty_code","department_code",'
874        heading += '"category","end_level","m_prefix","max_elect","max_pass",'
875        heading += '"n_core","nr_years","original_code","probation_credits",'
876        heading += '"promotion_credits","start_level","admin_status"'
877        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
878        dataline += '"%(category)s","%(end_level)s","%(m_prefix)s","%(max_elect)s","%(max_pass)s",'
879        dataline += '"%(n_core)s","%(nr_years)s","%(original_code)s","%(probation_credits)s",'
880        dataline += '"%(promotion_credits)s","%(start_level)s","%(admin_status)s"'
881        export.append(heading)
882        #import pdb;pdb.set_trace()
883        for faculty in faculties:
884            di = {}
885            di['faculty_code'] = faculty.id
886            for department in faculty.objectValues():
887                di['department_code'] = department.id
888                for certificate in department.certificates.objectValues():
889                    certificate_d = certificate.getContent()
890                    di['code'] = certificate.id
891                    #di['code'] = getattr(certificate_d,'code',None)
892                    di['title'] = getattr(certificate_d,'title',None)
893                    di['category'] = getattr(certificate_d,'category',None)
894                    di['admin_status'] = getattr(certificate_d,'admin_status',None)
895                    di['end_level'] = getattr(certificate_d,'end_level',None)
896                    di['m_prefix'] = getattr(certificate_d,'m_prefix',None)
897                    di['max_elect'] = getattr(certificate_d,'max_elect',None)
898                    di['max_load'] = getattr(certificate_d,'max_load',None)
899                    di['max_pass'] = getattr(certificate_d,'max_pass',None)
900                    di['n_core'] = getattr(certificate_d,'n_core',None)
901                    di['nr_years'] = getattr(certificate_d,'nr_years',None)
902                    di['original_code'] = getattr(certificate_d,'original_code',None)
903                    di['probation_credits'] = getattr(certificate_d,'probation_credits',None)
904                    di['promotion_credits'] = getattr(certificate_d,'promotion_credits',None)
905                    di['start_level'] = getattr(certificate_d,'start_level',None)
906                    di['code'] = di['code'] or certificate.id
907                    di['review_state'] = self.portal_workflow.getInfoFor(certificate,'review_state','no_state')
908                    try:
909                        export.append(dataline % di)
910                        logger.info('exporting %s %s ' % (certificate.id, certificate.title))
911                    except:
912                        logger.info('could not export %s %s ' % (certificate.id, certificate.title))
913                    continue
914        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
915        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
916    ###)
917
918    security.declareProtected(ModifyPortalContent,"exportCertificateCoursesToCSV")###(
919    def exportCertificateCoursesToCSV(self):
920        """export CertificateCourses to CSV"""
921        #return
922        name = 'CertificateCourses'
923        no_import = False
924        logger = logging.getLogger('%s_export' % name)
925        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
926        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
927        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
928        export = []
929        heading = '"code","review_state","faculty_code","department_code",'
930        heading += '"certificate_code","level","semester","core_or_elective"'
931        dataline = '"%(code)s","%(review_state)s","%(faculty_code)s","%(department_code)s",'
932        dataline += '"%(certificate_code)s","%(level)s","%(semester)s","%(core_or_elective)s"'
933        export.append(heading)
934        #import pdb;pdb.set_trace()
935        semesters = ['first','second']
936        for faculty in faculties:
937            di = {}
938            di['faculty_code'] = faculty.id
939            for department in faculty.objectValues():
940                di['department_code'] = department.id
941                for certificate in department.certificates.objectValues():
942                    di['certificate_code'] = certificate.id
943                    for level in certificate.objectValues():
944                        di['level'] = level.id
945                        for sem in semesters:
946                            semester = getattr(level,sem,None)
947                            if semester is not None:
948                                di['semester'] = semesters.index(sem) + 1
949                                for course in semester.objectValues():
950                                    di['code'] = course.getId()
951                                    course_d = course.getContent()
952                                    di['core_or_elective'] = getattr(course_d,'core_or_elective',None)
953                                    di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
954                                    try:
955                                        export.append(dataline % di)
956                                        logger.info('exporting %s %s ' % (certificate.id, certificate.title))
957                                    except:
958                                        logger.info('could not export %s %s ' % (certificate.id, certificate.title))
959                                        continue
960        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
961        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
962    ###)
963
964
965InitializeClass(AcademicsFolder)
966
967def addAcademicsFolder(container, id, REQUEST=None, **kw):
968    """Add a AcademicsFolder."""
969    ob = AcademicsFolder(id, **kw)
970    return CPSBase_adder(container, ob, REQUEST=REQUEST)
971
972###)
973
974class Certificate(CPSDocument): ###(
975    """
976    WAeUP Certificate
977    """
978    meta_type = 'Certificate'
979    portal_type = meta_type
980    security = ClassSecurityInfo()
981
982    def __init__(self, id, **kw):
983        CPSDocument.__init__(self, id, **kw)
984
985##    security.declareProtected(View,"Title")
986##    def Title(self):
987##        """compose title"""
988##        return "Certificate of %s" % (self.title)
989
990InitializeClass(Certificate)
991
992def addCertificate(container, id, REQUEST=None, **kw):
993    """Add a Certificate."""
994    ob = Certificate(id, **kw)
995    return CPSBase_adder(container, ob, REQUEST=REQUEST)
996
997###)
998
999class StudyLevel(CPSDocument): ###(
1000    """
1001    WAeUP StudyLevel containing the courses and students
1002    """
1003    meta_type = 'StudyLevel'
1004    portal_type = meta_type
1005    security = ClassSecurityInfo()
1006
1007    security.declareProtected(View,"Title")
1008    def Title(self):
1009        """compose title"""
1010        try:
1011            return "Level %s" % self.aq_parent.getId()
1012        except:
1013            return "no Title for %s" % self.getId()
1014
1015
1016InitializeClass(StudyLevel)
1017
1018def addStudyLevel(container, id, REQUEST=None, **kw):
1019    """Add a StudyLevel."""
1020    ob = StudyLevel(id, **kw)
1021    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1022
1023###)
1024
1025class CertificateCourse(CPSDocument): ###(
1026    """
1027    WAeUP CertificateCourse
1028    """
1029    meta_type = 'CertificateCourse'
1030    portal_type = meta_type
1031    security = ClassSecurityInfo()
1032
1033    def getCourseEntry(self,cid):
1034        res = self.portal_catalog({'meta_type': "Course",
1035                                           'id': cid})
1036        if res:
1037            return res[-1]
1038        else:
1039            return None
1040
1041    security.declareProtected(View,"Title")
1042    def Title(self):
1043        """compose title"""
1044        #import pdb;pdb.set_trace()
1045        ce = self.getCourseEntry(self.aq_parent.getId())
1046        #print self.id, self.aq_parent.id
1047        if ce:
1048            return "%s" % ce.Title
1049        return "No such course"
1050
1051    security.declareProtected(View,"credits")
1052    def credits(self):
1053        """credits from course"""
1054        ce = self.getCourseEntry(self.id)
1055        if ce:
1056            return "%s" % ce.credits
1057        return "0"
1058
1059    security.declareProtected(View,"passmark")
1060    def passmark(self):
1061        """passmark from course"""
1062        ce = self.getCourseEntry(self.id)
1063        if ce is not None and hasattr(ce,"passmark"):
1064            return ce.passmark
1065
1066
1067    security.declareProtected(View,"coursepath")
1068    def coursepath(self):
1069        """coursepath from course"""
1070        ce = self.getCourseEntry(self.id)
1071        if ce:
1072            return ce.getPath()
1073        return "?"
1074
1075
1076InitializeClass(CertificateCourse)
1077
1078def addCertificateCourse(container, id, REQUEST=None, **kw):
1079    """Add a CertificateCourse."""
1080    ob = CertificateCourse(id, **kw)
1081    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1082###)
1083
1084class Faculty(CPSDocument): ###(
1085    """
1086    WAeUP Faculty containing Departments
1087    """
1088    meta_type = 'Faculty'
1089    portal_type = meta_type
1090    security = ClassSecurityInfo()
1091
1092##    def __init__(self, id, **kw):
1093##        CPSDocument.__init__(self, id, **kw)
1094
1095    security.declareProtected(View,"Title")
1096    def Title(self):
1097        """compose title"""
1098        return "%s" % (self.title)
1099
1100
1101    security.declareProtected(View,"LongTitle")
1102    def LongTitle(self):
1103        """compose long_title"""
1104        prefix = getattr(self,'title_prefix',None)
1105        if prefix is None:
1106            prefix = getattr(self,'institution_type','faculty')
1107            self.getContent().edit(mapping = {'title_prefix': prefix})
1108        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Faculty of")
1109        return "%s %s" % (itype,self.title)
1110
1111InitializeClass(Faculty)
1112
1113def addFaculty(container, id, REQUEST=None, **kw):
1114    """Add a Faculty."""
1115    ob = Faculty(id, **kw)
1116    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1117
1118###)
1119
1120class Department(CPSDocument): ###(
1121    """
1122    WAeUP Department containing the courses and students
1123    """
1124    meta_type = 'Department'
1125    portal_type = meta_type
1126    security = ClassSecurityInfo()
1127
1128    security.declareProtected(View,"LongTitle")
1129    def LongTitle(self):
1130        """compose long_title"""
1131        prefix = getattr(self,'title_prefix',None)
1132        if prefix is None:
1133            prefix = getattr(self,'institution_type','department')
1134            self.getContent().edit(mapping = {'title_prefix': prefix})
1135        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Department of")
1136        return "%s %s" % (itype,self.title)
1137
1138InitializeClass(Department)
1139
1140def addDepartment(container, id, REQUEST=None, **kw):
1141    """Add a Department."""
1142    object = Department(id, **kw)
1143    id = object.getId()
1144    container._setObject(id, object)
1145##    dep = getattr(container,id).getEditableContent()   #getContent()
1146##    dep.invokeFactory('CoursesFolder','Courses')
1147##    o = getattr(dep,'Courses')
1148##    dict = {'Title': 'Courses'}
1149##    o.getContent().edit(mapping=dict)
1150##    dep.invokeFactory('CertificatesFolder','Certificates')
1151##    o = getattr(dep,'Certificates')
1152##    dict = {'Title': 'Certificates'}
1153##    o.geetContent().edit(mapping=dict)
1154    if REQUEST is not None:
1155        url = container.absolute_url()
1156        REQUEST.RESPONSE.redirect('%s/manage_main' % url)
1157
1158###)
1159
1160class Course(CPSDocument): ###(
1161    """
1162    WAeUP Course
1163    """
1164    meta_type = 'Course'
1165    portal_type = meta_type
1166    security = ClassSecurityInfo()
1167
1168    security.declareProtected(View,"Title")
1169    def Title(self):
1170        """compose title"""
1171        return self.title
1172
1173InitializeClass(Course)
1174
1175def addCourse(container, id, REQUEST=None, **kw):
1176    """Add a Course."""
1177    ob = Course(id, **kw)
1178    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1179###)
1180
1181
Note: See TracBrowser for help on using the repository browser.