source: WAeUP_SRP/trunk/Academics.py @ 684

Last change on this file since 684 was 602, checked in by Henrik Bettermann, 18 years ago

exportLocalRoles fixed by Uli

  • 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
[361]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
[278]35class AcademicsFolder(CPSDocument): ###(
36    """
[319]37    WAeUP AcademicsFolder containing StudyCourses
[278]38    """
39    meta_type = 'AcademicsFolder'
40    portal_type = meta_type
41    security = ClassSecurityInfo()
[440]42    use_catalog_for_folder_contents = True
[278]43
[364]44    security.declareProtected(View,"Title")
45    def Title(self):
46        """compose title"""
[382]47        return "Academic Section"
[256]48
[592]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")
[602]53        logger.info('Start importing %(name)s to %(name)s_%(current)s.csv' % vars())
[592]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}):
[602]65            odict[f.getId] = f.getObject()
[592]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
[351]78    security.declareProtected(ModifyPortalContent,"loadFacultiesFromCSV")###(
[319]79    def loadFacultiesFromCSV(self):
[278]80        """install Universityspecific Faculies from CSV values"""
81        #return
[592]82        if self.REQUEST.get('localroles'):
83            self.importLocalRoles('Faculty')
84            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[549]85        name = 'Faculties'
[282]86        no_import = False
[563]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
[592]129        if self.REQUEST.get('localroles'):
130            self.importLocalRoles('Department')
131            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[563]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)
[602]179
[563]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
[602]408            cert_course['core_or_elective'] = eval(cert_course['core_or_elective'])
[563]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
[282]428        logger = logging.getLogger('%s_import' % name)
429        logger.info('Start loading from %s.csv' % name)
[278]430        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
431        try:
[282]432            faculties = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
[278]433        except:
[282]434            logger.error('Error reading %s.csv' % name)
[278]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)
[282]449                d = {'Title': faculty['Description']}
450            else:
[369]451                d = {}
452            d['bank_code'] = faculty.get("Bankcode")
453            d["degree_grade"] = faculty.get("degree_grade")
[371]454            d['institution_type'] = 'faculty'
[379]455            d['Description'] = ''
456            d['college_code'] = faculty.get('CollegeCode')
[369]457            f.getContent().edit(mapping=d)
[526]458        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[278]459    ###)
460
461    security.declareProtected(ModifyPortalContent,"yamlDumpFaculties")###(
[319]462    def yamlDumpFaculties(self):
[278]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)
[526]477        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[319]478
[278]479    ###)
480
[563]481    security.declareProtected(ModifyPortalContent,"loadDepartmentsFromOrgCSV")###(
482    def loadDepartmentsFromOrgCSV(self):
[278]483        """install Universityspecific Faculies from CSV values"""
484        #return
[549]485        name = 'Departments'
[282]486        no_import = False
[278]487        logger = logging.getLogger('loaddepartments')
488        try:
489            deps = csv.DictReader(open("%s/import/departments.csv" % i_home,"rb"))
490        except:
[280]491            logger.error('Error reading departments.csv')
[278]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)
[282]503                if not no_import:
504                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
[287]505                    no_import.write('"Session","DeptCode","Description","FacultyCode"\n')
506                no_import.write( "No Faculty with ID: %s\n" % fid)
[282]507                no_import.write('"%(Session)s","%(DeptCode)s","%(Description)s","%(FacultyCode)s"\n' % dep)
[278]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)
[295]515                    dict = {'Title': dep['Description']}
516                    d.getContent().edit(mapping=dict)
[319]517                    d.invokeFactory('CoursesFolder','courses')
[324]518                    courses = getattr(d,'courses')
[295]519                    dict = {'Title': 'Courses'}
520                    courses.getContent().edit(mapping=dict)
[319]521                    d.invokeFactory('CertificatesFolder','certificates')
[321]522                    certificates = getattr(d,'certificates')
[295]523                    dict = {'Title': 'Certificates'}
524                    certificates.getContent().edit(mapping=dict)
[526]525        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[278]526    ###)
[319]527
[563]528    security.declareProtected(ModifyPortalContent,"loadCoursesFromOrgCSV")###(
529    def loadCoursesFromOrgCSV(self):
[278]530        """install Universityspecific Courses from CSV values"""
531        #return
[549]532        name = 'Courses'
[282]533        no_import = False
[278]534        logger = logging.getLogger('loadcourses')
535        try:
536            courses = csv.DictReader(open("%s/import/courses.csv" % i_home,"rb"))
537        except:
[280]538            logger.error('Error reading courses.csv')
[278]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:
[296]551            logger.info('Processing %(CourseCode)s %(Description)s %(Credits)s %(Dept)s %(Semester)s %(Session)s %(PassMark)s %(Category)s %(AdmStatus)s' % course)
[282]552##            if course.get("FORMERCODE").endswith('BITS'):
553##                continue
[278]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)
[282]561                if not no_import:
562                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
[296]563                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","Category","AdmStatus"\n')
[287]564                no_import.write("Dep %(Dept)s for Course %(CourseCode)s not found\n" % course)
[296]565                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(Category)s","%(AdmStatus)s"\n' % course)
[278]566                continue
567            course_id = ''.join(re.split('\W+',course.get('CourseCode')))
568            if len(course_id) == 3:
569                course_id = "%s000" % course_id
[296]570            elif len(course_id) > 10:
[278]571                logger.info("invalid course_code %(CourseCode)s" % course)
[282]572                if not no_import:
573                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
[296]574                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","Category","AdmStatus"\n')
[287]575                no_import.write("invalid course_code %(CourseCode)s\n" % course)
[296]576                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(Category)s","%(AdmStatus)s"\n' % course)
[278]577                continue
[323]578            courses = dept.courses
[295]579            c = getattr(courses,course_id,None)
[278]580            if c is None:
581                logger.info('Creating Course %(CourseCode)s  %(Description)s in Department %(Dept)s' % course)
[295]582                courses.invokeFactory('Course', course_id)
583                c = getattr(courses,course_id)
[278]584            dict = {'Title': course['Description']}
585            dict['code'] = course_id
[319]586            dict['org_code'] = course.get('CourseCode')
[282]587            dict['credits'] = course.get('Credits')
[278]588            dict['semester'] = course.get('Semester')
589            dict['session'] = course.get('Session')
590            dict['category'] = course.get('Category')
[379]591            dict['adm_status'] = course.get('AdmStatus')
592            dict['former_code'] = course.get('FORMERCODE')
[282]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
[278]602            c.getContent().edit(mapping=dict)
[526]603        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[278]604    ###)
605
[563]606    security.declareProtected(ModifyPortalContent,"loadCertificatesFromOrgCSV")###(
[290]607
[563]608    def loadCertificatesFromOrgCSV(self):
[278]609        """install Universityspecific Certificates from CSV values"""
610        #return
[549]611        name = 'Certificates'
[287]612        no_import = False
[278]613        logger = logging.getLogger('loadcertificates')
614        try:
615            certificates = csv.DictReader(open("%s/import/certificates.csv" % i_home,"rb"))
616        except:
[280]617            logger.error('Error reading certificates.csv')
[278]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)
[287]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)
[278]636                continue
637            if not deps.has_key(depid):
638                logger.info('Department %(Dept)s for %(CertCode)s %(Description)s not found' % certificate)
[287]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)
[278]644                continue
[296]645            #certificate_id = "%(category)s_%(Admstatus)s_%(Dept)s" % certificate
[278]646            dep = deps[depid]
[323]647            certificates = dep.certificates
[361]648            code = makeCertificateCode(certificate.get('CertCode'))
[296]649            certificate_id = code
[295]650            c = getattr(certificates,certificate_id,None)
[278]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)
[295]654                certificates.invokeFactory('Certificate', certificate_id)
655                c = getattr(certificates,certificate_id)
[370]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')
[382]678            print
[278]679            c.getContent().edit(mapping=dict)
[526]680        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[278]681    ###)
682
[563]683    security.declareProtected(ModifyPortalContent,"loadCertificateCoursesFromOrgCSV")###(
684    def loadCertificateCoursesFromOrgCSV(self):
[278]685        """install Certificate Courses from CSV values"""
686        #return
687        logger = logging.getLogger('loadcertificatecourses')
[549]688        name = 'Certificate_courses'
[290]689        no_import = False
[278]690        try:
691            cert_courses = csv.DictReader(open("%s/import/course_level_courses.csv" % i_home,"rb"))
692        except:
[280]693            logger.error('Error reading course_level_courses.csv')
[278]694            return
695        d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
[290]696        c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
[296]697        l = self.portal_catalog({'meta_type': "Certificate"})
698        certs = {}
699        for f in l:
700            certs[f.id] = f.getObject()
[278]701        for cert_course in cert_courses:
[296]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)
[278]703            depid = cert_course.get('Dept')
[290]704            course_code = cert_course.get('CosCode')
[278]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('_','')
[290]712##            if cert_course.get('Session') != '2002/2003':
713##                continue
[296]714##            certificate = self.portal_catalog({'meta_type': "Certificate",
715##                                               'SearchableText': code})
716##            if not certificate:
717            if not code in certs.keys():
[290]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")
[296]723                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
[290]724                no_import.write(em)
[296]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)
[278]726                continue
[309]727            certificate = certs[code]
[278]728            certificate_code = certificate.getId()
[290]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")
[296]734                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
[290]735                no_import.write(em)
[296]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)
[290]737                continue
[278]738            if depid not in d_ids:
[290]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")
[296]743                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
[290]744                no_import.write(em)
[296]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)
[278]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)
[329]754                l.getContent().edit(mapping={'Title': "Level %s" % level})
[278]755                l.invokeFactory('Semester','first')
756                l.invokeFactory('Semester','second')
[290]757            certificate.orderObjects('id')
[278]758            first_s = getattr(l,'first')
[332]759            first_s.getContent().edit(mapping={'Title': 'First Semester'})
[278]760            second_s = getattr(l,'second')
[332]761            second_s.getContent().edit(mapping={'Title': 'Second Semester'})
[278]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)
[290]768                if not no_import:
769                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
[296]770                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
[295]771##                no_import.write('Duplicate %(CosCode)s in Level %(Level)s' % cert_course)
[296]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)
[278]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
[319]779            dict['certificate_code_org'] = cert_course.get('CertCode')
780            dict['department'] = cert_course.get('Dept')
[278]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')
[295]788            cc.getContent().edit(mapping=dict)
[526]789        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[278]790    ###)
791
[592]792    def exportLocalRoles(self,portal_type): ###(
[593]793        name = '%sLocalRoles' % portal_type
[592]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())
[595]797        objects = [f.getObject() for f in self.portal_catalog({'meta_type': portal_type})]
[592]798        export = []
799        export.append('"code","users"')
[593]800        #import pdb;pdb.set_trace()
[592]801        for obj in objects:
[602]802            lr = {}
803            for (username, roles) in obj.get_local_roles():
804                lr[ 'user:' + username ] = [x for x in roles]
805            for (groupname, roles) in obj.get_local_group_roles():
806                lr[ 'group:' + group ] = [x for x in roles]
[592]807            logger.info('exporting %s %s ' % (obj.id, lr))
808            export.append('"%s","%s"' % (obj.getId(),lr))
809        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
810###)
[602]811
[526]812    security.declareProtected(ModifyPortalContent,"exportFacultiesToCSV")###(
813    def exportFacultiesToCSV(self):
814        """export Faculies to CSV"""
815        #return
[592]816        if self.REQUEST.get('localroles'):
817            self.exportLocalRoles('Faculty')
818            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[549]819        name = 'Faculties'
[526]820        no_import = False
821        logger = logging.getLogger('%s_export' % name)
822        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
823        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
[557]824        objects = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
[526]825        export = []
826        export.append('"code","review_state","title","title_prefix","college_code","degree_grade","bank_code"')
827        for obj in objects:
828            logger.info('exporting %s %s ' % (obj.id, obj.title))
829            obj_d = obj.getContent()
830            di = {}
831            di['code'] = obj_d.code
832            di['title'] = obj_d.title
833            di['title_prefix'] = obj_d.title_prefix
834            di['college_code'] = obj_d.college_code
835            di['degree_grade'] = obj_d.degree_grade
836            di['bank_code'] = obj_d.bank_code
837            di['code'] = di['code'] or obj.id
838            di['review_state'] = self.portal_workflow.getInfoFor(obj,'review_state','no_state')
839            export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(college_code)s","%(degree_grade)s","%(bank_code)s"' % di)
840        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
841        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
842
843    ###)
844
845    security.declareProtected(ModifyPortalContent,"exportDepartmentsToCSV")###(
846    def exportDepartmentsToCSV(self):
847        """export Faculies to CSV"""
848        #return
[592]849        if self.REQUEST.get('localroles'):
850            self.exportLocalRoles('Department')
851            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[549]852        name = 'Departments'
[526]853        no_import = False
854        logger = logging.getLogger('%s_export' % name)
855        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
856        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
857        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
858        export = []
859        export.append('"code","review_state","title","title_prefix","faculty_code"')
860        #import pdb;pdb.set_trace()
861        for faculty in faculties:
862            di = {}
863            di['faculty_code'] = faculty.id
864            for department in faculty.objectValues():
865                department_d = department.getContent()
866                try:
[576]867                    di['code'] =  department.getId()
[526]868                    di['title'] = department_d.title
869                    di['title_prefix'] = department_d.title_prefix
870                    di['review_state'] = self.portal_workflow.getInfoFor(department,'review_state','no_state')
[527]871                    export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(faculty_code)s"' % di)
[526]872                    logger.info('exporting %s %s ' % (department.id, department.title))
873                except:
874                    logger.info('could not export %s %s ' % (department.id, department.title))
875                    continue
876        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
877        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
878    ###)
879
880    security.declareProtected(ModifyPortalContent,"exportCoursesToCSV")###(
881    def exportCoursesToCSV(self):
882        """export Courses to CSV"""
883        #return
[549]884        name = 'Courses'
[526]885        no_import = False
886        logger = logging.getLogger('%s_export' % name)
887        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
888        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
889        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
890        export = []
891        heading = '"code","review_state","title","faculty_code","department_code",'
892        heading += '"credits","org_code","passmark","semester","session"'
893        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
894        dataline += '"%(credits)s","%(org_code)s","%(passmark)s","%(semester)s","%(session)s"'
895        export.append(heading)
896        #import pdb;pdb.set_trace()
[576]897        fields = ("title",
[567]898                  "credits",
899                  "org_code",
900                  "passmark",
901                  "semester",
902                  "session",
903                  )
[526]904        for faculty in faculties:
905            di = {}
906            di['faculty_code'] = faculty.id
907            for department in faculty.objectValues():
908                di['department_code'] = department.id
[527]909                for course in department.courses.objectValues():
[576]910                    di['code'] = course.getId()
[526]911                    course_d = course.getContent()
[567]912                    for f in fields:
913                        di[f] = getattr(course_d,f,None)
[569]914                    di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
[567]915                    export.append(dataline % di)
916                    logger.info('exporting %s %s ' % (course.id, course.title))
[526]917                    continue
918        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
919        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
920    ###)
921
922    security.declareProtected(ModifyPortalContent,"exportCertificatesToCSV")###(
923    def exportCertificatesToCSV(self):
924        """export Certificates to CSV"""
925        #return
[549]926        name = 'Certificates'
[526]927        no_import = False
928        logger = logging.getLogger('%s_export' % name)
929        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
930        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
931        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
932        export = []
933        heading = '"code","review_state","title","faculty_code","department_code",'
934        heading += '"category","end_level","m_prefix","max_elect","max_pass",'
935        heading += '"n_core","nr_years","original_code","probation_credits",'
936        heading += '"promotion_credits","start_level","admin_status"'
[527]937        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
[526]938        dataline += '"%(category)s","%(end_level)s","%(m_prefix)s","%(max_elect)s","%(max_pass)s",'
939        dataline += '"%(n_core)s","%(nr_years)s","%(original_code)s","%(probation_credits)s",'
940        dataline += '"%(promotion_credits)s","%(start_level)s","%(admin_status)s"'
941        export.append(heading)
942        #import pdb;pdb.set_trace()
943        for faculty in faculties:
944            di = {}
945            di['faculty_code'] = faculty.id
946            for department in faculty.objectValues():
947                di['department_code'] = department.id
[527]948                for certificate in department.certificates.objectValues():
[526]949                    certificate_d = certificate.getContent()
[576]950                    di['code'] = certificate.id
951                    #di['code'] = getattr(certificate_d,'code',None)
[529]952                    di['title'] = getattr(certificate_d,'title',None)
953                    di['category'] = getattr(certificate_d,'category',None)
954                    di['admin_status'] = getattr(certificate_d,'admin_status',None)
955                    di['end_level'] = getattr(certificate_d,'end_level',None)
956                    di['m_prefix'] = getattr(certificate_d,'m_prefix',None)
957                    di['max_elect'] = getattr(certificate_d,'max_elect',None)
958                    di['max_load'] = getattr(certificate_d,'max_load',None)
959                    di['max_pass'] = getattr(certificate_d,'max_pass',None)
960                    di['n_core'] = getattr(certificate_d,'n_core',None)
961                    di['nr_years'] = getattr(certificate_d,'nr_years',None)
962                    di['original_code'] = getattr(certificate_d,'original_code',None)
963                    di['probation_credits'] = getattr(certificate_d,'probation_credits',None)
964                    di['promotion_credits'] = getattr(certificate_d,'promotion_credits',None)
965                    di['start_level'] = getattr(certificate_d,'start_level',None)
[526]966                    di['code'] = di['code'] or certificate.id
967                    di['review_state'] = self.portal_workflow.getInfoFor(certificate,'review_state','no_state')
968                    try:
969                        export.append(dataline % di)
970                        logger.info('exporting %s %s ' % (certificate.id, certificate.title))
971                    except:
972                        logger.info('could not export %s %s ' % (certificate.id, certificate.title))
973                    continue
974        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
975        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
976    ###)
977
978    security.declareProtected(ModifyPortalContent,"exportCertificateCoursesToCSV")###(
979    def exportCertificateCoursesToCSV(self):
980        """export CertificateCourses to CSV"""
981        #return
[549]982        name = 'CertificateCourses'
[526]983        no_import = False
984        logger = logging.getLogger('%s_export' % name)
985        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
986        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
987        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
988        export = []
989        heading = '"code","review_state","faculty_code","department_code",'
990        heading += '"certificate_code","level","semester","core_or_elective"'
991        dataline = '"%(code)s","%(review_state)s","%(faculty_code)s","%(department_code)s",'
[527]992        dataline += '"%(certificate_code)s","%(level)s","%(semester)s","%(core_or_elective)s"'
[526]993        export.append(heading)
994        #import pdb;pdb.set_trace()
995        semesters = ['first','second']
996        for faculty in faculties:
997            di = {}
998            di['faculty_code'] = faculty.id
999            for department in faculty.objectValues():
1000                di['department_code'] = department.id
[527]1001                for certificate in department.certificates.objectValues():
[526]1002                    di['certificate_code'] = certificate.id
1003                    for level in certificate.objectValues():
1004                        di['level'] = level.id
1005                        for sem in semesters:
1006                            semester = getattr(level,sem,None)
1007                            if semester is not None:
[527]1008                                di['semester'] = semesters.index(sem) + 1
[526]1009                                for course in semester.objectValues():
[576]1010                                    di['code'] = course.getId()
[526]1011                                    course_d = course.getContent()
[529]1012                                    di['core_or_elective'] = getattr(course_d,'core_or_elective',None)
[526]1013                                    di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
1014                                    try:
1015                                        export.append(dataline % di)
1016                                        logger.info('exporting %s %s ' % (certificate.id, certificate.title))
1017                                    except:
1018                                        logger.info('could not export %s %s ' % (certificate.id, certificate.title))
1019                                        continue
1020        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
1021        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1022    ###)
1023
1024
[278]1025InitializeClass(AcademicsFolder)
1026
1027def addAcademicsFolder(container, id, REQUEST=None, **kw):
1028    """Add a AcademicsFolder."""
1029    ob = AcademicsFolder(id, **kw)
1030    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1031
1032###)
1033
[256]1034class Certificate(CPSDocument): ###(
[238]1035    """
[319]1036    WAeUP Certificate
[238]1037    """
[256]1038    meta_type = 'Certificate'
[238]1039    portal_type = meta_type
1040    security = ClassSecurityInfo()
[319]1041
[238]1042    def __init__(self, id, **kw):
1043        CPSDocument.__init__(self, id, **kw)
1044
[256]1045##    security.declareProtected(View,"Title")
1046##    def Title(self):
1047##        """compose title"""
1048##        return "Certificate of %s" % (self.title)
[238]1049
[256]1050InitializeClass(Certificate)
[238]1051
[256]1052def addCertificate(container, id, REQUEST=None, **kw):
1053    """Add a Certificate."""
1054    ob = Certificate(id, **kw)
[238]1055    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1056
1057###)
1058
[454]1059class StudyLevel(CPSDocument): ###(
1060    """
1061    WAeUP StudyLevel containing the courses and students
1062    """
1063    meta_type = 'StudyLevel'
1064    portal_type = meta_type
1065    security = ClassSecurityInfo()
1066
1067    security.declareProtected(View,"Title")
1068    def Title(self):
1069        """compose title"""
[458]1070        try:
1071            return "Level %s" % self.aq_parent.getId()
1072        except:
1073            return "no Title for %s" % self.getId()
[454]1074
[527]1075
[454]1076InitializeClass(StudyLevel)
1077
1078def addStudyLevel(container, id, REQUEST=None, **kw):
1079    """Add a StudyLevel."""
1080    ob = StudyLevel(id, **kw)
1081    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1082
1083###)
1084
[256]1085class CertificateCourse(CPSDocument): ###(
[238]1086    """
[319]1087    WAeUP CertificateCourse
[238]1088    """
[256]1089    meta_type = 'CertificateCourse'
[238]1090    portal_type = meta_type
1091    security = ClassSecurityInfo()
[319]1092
[279]1093    def getCourseEntry(self,cid):
1094        res = self.portal_catalog({'meta_type': "Course",
1095                                           'id': cid})
1096        if res:
[319]1097            return res[-1]
[279]1098        else:
1099            return None
[319]1100
[256]1101    security.declareProtected(View,"Title")
1102    def Title(self):
1103        """compose title"""
[583]1104        #import pdb;pdb.set_trace()
1105        ce = self.getCourseEntry(self.aq_parent.getId())
[454]1106        #print self.id, self.aq_parent.id
[279]1107        if ce:
1108            return "%s" % ce.Title
1109        return "No such course"
[238]1110
[279]1111    security.declareProtected(View,"credits")
1112    def credits(self):
1113        """credits from course"""
1114        ce = self.getCourseEntry(self.id)
1115        if ce:
1116            return "%s" % ce.credits
[280]1117        return "0"
[319]1118
[279]1119    security.declareProtected(View,"passmark")
1120    def passmark(self):
1121        """passmark from course"""
1122        ce = self.getCourseEntry(self.id)
[296]1123        if ce is not None and hasattr(ce,"passmark"):
1124            return ce.passmark
[319]1125
1126
[280]1127    security.declareProtected(View,"coursepath")
1128    def coursepath(self):
1129        """coursepath from course"""
1130        ce = self.getCourseEntry(self.id)
1131        if ce:
1132            return ce.getPath()
1133        return "?"
[279]1134
[319]1135
[256]1136InitializeClass(CertificateCourse)
[238]1137
[256]1138def addCertificateCourse(container, id, REQUEST=None, **kw):
1139    """Add a CertificateCourse."""
1140    ob = CertificateCourse(id, **kw)
[238]1141    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1142###)
1143
[68]1144class Faculty(CPSDocument): ###(
1145    """
[319]1146    WAeUP Faculty containing Departments
[68]1147    """
1148    meta_type = 'Faculty'
1149    portal_type = meta_type
1150    security = ClassSecurityInfo()
[319]1151
[238]1152##    def __init__(self, id, **kw):
1153##        CPSDocument.__init__(self, id, **kw)
[173]1154
[200]1155    security.declareProtected(View,"Title")
1156    def Title(self):
1157        """compose title"""
[238]1158        return "%s" % (self.title)
[319]1159
[389]1160
[296]1161    security.declareProtected(View,"LongTitle")
1162    def LongTitle(self):
1163        """compose long_title"""
[389]1164        prefix = getattr(self,'title_prefix',None)
1165        if prefix is None:
1166            prefix = getattr(self,'institution_type','faculty')
1167            self.getContent().edit(mapping = {'title_prefix': prefix})
1168        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Faculty of")
[296]1169        return "%s %s" % (itype,self.title)
[200]1170
[68]1171InitializeClass(Faculty)
1172
1173def addFaculty(container, id, REQUEST=None, **kw):
1174    """Add a Faculty."""
1175    ob = Faculty(id, **kw)
1176    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1177
1178###)
1179
1180class Department(CPSDocument): ###(
1181    """
1182    WAeUP Department containing the courses and students
1183    """
1184    meta_type = 'Department'
1185    portal_type = meta_type
1186    security = ClassSecurityInfo()
[173]1187
[296]1188    security.declareProtected(View,"LongTitle")
1189    def LongTitle(self):
1190        """compose long_title"""
[389]1191        prefix = getattr(self,'title_prefix',None)
1192        if prefix is None:
1193            prefix = getattr(self,'institution_type','department')
1194            self.getContent().edit(mapping = {'title_prefix': prefix})
1195        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Department of")
[296]1196        return "%s %s" % (itype,self.title)
1197
[68]1198InitializeClass(Department)
1199
1200def addDepartment(container, id, REQUEST=None, **kw):
1201    """Add a Department."""
[296]1202    object = Department(id, **kw)
[295]1203    id = object.getId()
[319]1204    container._setObject(id, object)
[309]1205##    dep = getattr(container,id).getEditableContent()   #getContent()
1206##    dep.invokeFactory('CoursesFolder','Courses')
1207##    o = getattr(dep,'Courses')
1208##    dict = {'Title': 'Courses'}
1209##    o.getContent().edit(mapping=dict)
1210##    dep.invokeFactory('CertificatesFolder','Certificates')
1211##    o = getattr(dep,'Certificates')
1212##    dict = {'Title': 'Certificates'}
1213##    o.geetContent().edit(mapping=dict)
[295]1214    if REQUEST is not None:
1215        url = container.absolute_url()
1216        REQUEST.RESPONSE.redirect('%s/manage_main' % url)
[309]1217
[68]1218###)
1219
1220class Course(CPSDocument): ###(
1221    """
[319]1222    WAeUP Course
[68]1223    """
1224    meta_type = 'Course'
1225    portal_type = meta_type
1226    security = ClassSecurityInfo()
[152]1227
1228    security.declareProtected(View,"Title")
1229    def Title(self):
1230        """compose title"""
[238]1231        return self.title
[319]1232
[68]1233InitializeClass(Course)
1234
1235def addCourse(container, id, REQUEST=None, **kw):
1236    """Add a Course."""
1237    ob = Course(id, **kw)
1238    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1239###)
[139]1240
[319]1241
Note: See TracBrowser for help on using the repository browser.