source: WAeUP_SRP/trunk/Academics.py @ 594

Last change on this file since 594 was 593, checked in by joachim, 18 years ago

export File now written should work now

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