source: WAeUP_SRP/trunk/Academics.py @ 754

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

fixed dupplicate certificate id for certificate courses import

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