source: WAeUP_SRP/trunk/Academics.py @ 717

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

fix csv-format

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