source: WAeUP_SRP/trunk/Academics.py @ 573

Last change on this file since 573 was 569, checked in by joachim, 18 years ago

fix export of courses

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