source: WAeUP_SRP/trunk/Academics.py @ 17569

Last change on this file since 17569 was 3983, checked in by Henrik Bettermann, 16 years ago

exportCertificateCoursesToCSV: don't log all

  • Property svn:keywords set to Id
File size: 39.2 KB
Line 
1#-*- mode: python; mode: fold -*-
2from Globals import InitializeClass
3from AccessControl import ClassSecurityInfo
4
5from Products.CMFCore.utils import UniqueObject, getToolByName
6from Products.CMFCore.permissions import View
7from Products.CMFCore.permissions import ModifyPortalContent
8from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
9#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
10from Products.CPSDocument.CPSDocument import CPSDocument
11#from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
12#from Products.CPSCore.CPSBase import CPSBaseBTreeDocument as BaseBTreeDocument
13#from Products.CMFCore.DirectoryView import registerDirectory
14
15#registerDirectory('skins', globals())
16#registerDirectory('skins/waeup_default', globals())
17#registerDirectory('skins/waeup_faculty', globals())
18
19import DateTime
20import csv,re
21import logging
22import Globals
23p_home = Globals.package_home(globals())
24i_home = Globals.INSTANCE_HOME
25
26def makeCertificateCode(code): ###(
27    code = code.replace('.','')
28    code = code.replace('(','')
29    code = code.replace(')','')
30    code = code.replace('/','')
31    code = code.replace(' ','')
32    code = code.replace('_','')
33    return code
34
35###)
36
37class AcademicsFolder(CPSDocument): ###(
38    """
39    WAeUP AcademicsFolder containing StudyCourses
40    """
41    meta_type = 'AcademicsFolder'
42    portal_type = meta_type
43    security = ClassSecurityInfo()
44    use_catalog_for_folder_contents = True
45
46    security.declareProtected(View,"Title")
47    def Title(self):
48        """compose title"""
49        return "Academic Section"
50
51    def importLocalRoles(self,portal_type): ###(
52        name = '%sLocalRoles' % portal_type
53        logger = logging.getLogger('Academics.AcademicsFolder.importLocalRoles')
54        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
55        logger.info('Start importing %(name)s to %(name)s_%(current)s.csv' % vars())
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}):
67            odict[f.getId] = f.getObject()
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
80    security.declareProtected(ModifyPortalContent,"loadFacultiesFromCSV")###(
81    def loadFacultiesFromCSV(self):
82        """install Universityspecific Faculies from CSV values"""
83        #return
84        if self.REQUEST.get('localroles'):
85            self.importLocalRoles('Faculty')
86            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
87        name = 'Faculties'
88        no_import = False
89        logger = logging.getLogger('Academics.AcademicsFolder.loadFacultiesFromCSV')
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                  )
109        format = ','.join(['"%%(%s)s"' % fn for fn in fields])
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
131        if self.REQUEST.get('localroles'):
132            self.importLocalRoles('Department')
133            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
134        name = 'Departments'
135        no_import = False
136        logger = logging.getLogger('Academics.AcademicsFolder.loadDepartmentsFromCSV')
137        fields = ("code",
138                  "review_state",
139                  "title",
140                  "title_prefix",
141                  "faculty_code",
142                  )
143        format = ','.join(['"%%(%s)s"' % fn for fn in fields])
144        try:
145            deps = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
146        except:
147            logger.error('Error reading %s.csv' % name)
148            return
149        no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
150        heading = ','.join(['"%s"' % fn for fn in fields])
151        no_import.write('%s\n' % heading)
152        l = self.portal_catalog({'meta_type': "Faculty"})
153        facs = {}
154        for f in l:
155            facs[f.id] = f.getObject()
156        for dep in deps:
157            processing = "processing %s" % format
158            logger.info(processing % dep)
159            fid = dep['faculty_code']
160            f = facs.get(fid,None)
161            if f is None:
162                logger.info( "No Faculty with ID: %s" % fid)
163                no_import.write( "No Faculty with ID: %s\n" % fid)
164                no_import.write(format % dep + "\n")
165            else:
166                did = dep.get('code')
167                d = getattr(f,did,None)
168                if d is None or d.portal_type == "Faculty":
169                    logger.info('Creating Department %(code)s = %(title)s' % dep)
170                    f.invokeFactory('Department', did)
171                    d = getattr(f,did)
172                    d.invokeFactory('CoursesFolder','courses')
173                    courses = getattr(d,'courses')
174                    dict = {'Title': 'Courses'}
175                    courses.getContent().edit(mapping=dict)
176                    d.invokeFactory('CertificatesFolder','certificates')
177                    certificates = getattr(d,'certificates')
178                    dict = {'Title': 'Certificates'}
179                    certificates.getContent().edit(mapping=dict)
180                d.getContent().edit(mapping=dep)
181
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        not_allowed =re.compile('[^A-Z0-9]')
190        wf = self.portal_workflow
191        name = 'Courses'
192        no_import = False
193        logger = logging.getLogger('Academics.AcademicsFolder.loadCoursesFromCSV')
194        fields = ("code",
195                  "review_state",
196                  "title",
197                  "faculty_code",
198                  "department_code",
199                  "credits",
200                  "org_code",
201                  "passmark",
202                  "semester",
203                  "session",
204                  )
205        format = ','.join(['"%%(%s)s"' % fn for fn in fields])
206        try:
207            courses = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
208        except:
209            logger.error('Error reading %s.csv' % name)
210            return
211        imported = []
212        not_imported = []
213        heading = ','.join(['"%s"' % fn for fn in fields])
214        imported.append(heading)
215        not_imported.append(heading)
216        #no_import.write('%s\n' % heading)
217        #l = self.portal_catalog({'meta_type': "Faculty"})
218        #facs = {}
219        #for f in l:
220        #    facs[f.id] = f.getObject()
221        dl = self.portal_catalog({'meta_type': "Department"})
222        deps = {}
223        for d in dl:
224            deps[d.id] = d.getObject()
225        cl = self.portal_catalog({'meta_type': "Course"})
226        course_list = [ c.id for c in cl]
227        for course in courses:
228            #processing = "processing %s" % format
229            #logger.info(processing % course)
230            course_id = course.get('code')
231            if not_allowed.search(course_id):
232                msg = ',"Invalid Course Code"'
233                #logger.info(msg)
234                #not_imported.append('"%s",' % msg)
235                not_imported.append(format % course + msg)
236                continue
237            depid = course.get('department_code').upper()
238            if depid in deps.keys():
239                dept= deps.get(depid)
240            else:
241                msg = ',"Department not found"'
242                #logger.info(msg)
243                #not_imported.append('"%s",' % msg)
244                not_imported.append(format % course + msg)
245                continue
246            if course_id in course_list:
247                msg = ',"Multiple Course Code"'
248                #logger.info(msg)
249                #not_imported.append('"%s",' % msg)
250                not_imported.append(format % course + msg)
251                continue
252            level = "%c00" % course_id[-3]
253            course['level'] = level
254            cf = dept.courses
255            c = getattr(cf,course_id,None)
256            #cd_fields = (('code','code'),
257            #             ('faculty','faculty_code'),
258            #             ('department','department_code'),
259            #             ('title','title'),
260            #             ('credits','credits'),
261            #             ('level','level'),
262            #             ('semester','semester'),
263            #             )
264            #cd = {}
265            #for t,f in cd_fields:
266            #    cd[t] = course[f]
267            #import pdb;pdb.set_trace()
268            if c is None:
269                logger.info('Creating Course %(code)s  %(title)s in Department %(department_code)s' % course)
270                cf.invokeFactory('Course', course_id)
271                course_list.append(course_id)
272                imported.append(format % course)
273                c = getattr(cf,course_id)
274                #self.courses_catalog.addRecord(**cd)
275            #else:
276            #    self.courses_catalog.modifyRecord(**cd)
277            c.getContent().edit(mapping=course)
278            review_state = course.get('review_state')
279            if review_state == "checked" and wf.getInfoFor(c,'review_state',None) != 'checked':
280                self.portal_workflow.doActionFor(c,'approve')
281        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
282        if len(not_imported) > 1:
283            open("%s/import/%s_%s_not_imported.csv" % (i_home,name,current),"w")\
284                .write('\n'.join(not_imported))
285        open("%s/import/%s_%s_imported.csv" % (i_home,name,current),"w")\
286                .write('\n'.join(imported))
287        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
288    ###)
289
290    security.declareProtected(ModifyPortalContent,"loadCertificatesFromCSV")###(
291
292    def loadCertificatesFromCSV(self):
293        """install Universityspecific Certificates from CSV values"""
294        #return
295        name = 'Certificates'
296        wf = self.portal_workflow
297        no_import_list = []
298        logger = logging.getLogger('Academics.AcademicsFolder.loadCertificatesFromCSV')
299        fields = ("code",
300                  "review_state",
301                  "title",
302                  "faculty_code",
303                  "department_code",
304                  "category",
305                  "end_level",
306                  "m_prefix",
307                  "max_elect",
308                  "max_pass",
309                  "n_core",
310                  "nr_years",
311                  "original_code",
312                  "probation_credits",
313                  "promotion_credits",
314                  "start_level",
315                  "admin_status",
316                  )
317        format = ','.join(['"%%(%s)s"' % fn for fn in fields])
318        try:
319            courses = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
320        except:
321            logger.error('Error reading %s.csv' % name)
322            return
323        try:
324            certificates = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
325        except:
326            logger.error('Error reading %s.csv' % name)
327            return
328        f_ids = [f.id for f in self.portal_catalog({'meta_type': "Faculty"})]
329        dl = self.portal_catalog({'meta_type': "Department"})
330        deps = {}
331        for d in dl:
332            deps[d.id] = d.getObject()
333        for certificate in certificates:
334            processing = "processing %s" % format
335            logger.info(processing % certificate)
336            depid = certificate.get('department_code')
337            facid = certificate.get('faculty_code')
338            if facid not in f_ids:
339                msg = 'Faculty %(faculty_code)s for %(code)s %(title)s not found' % certificate
340                logger.info(msg)
341                no_import_list.append(msg)
342                no_import_list.append(format % certificate + "\n")
343                continue
344            if not deps.has_key(depid):
345                msg = 'Department %(department_code)s for %(code)s %(title)s not found' % certificate
346                logger.info(msg)
347                no_import_list.append(msg)
348                no_import_list.append(format % certificate + "\n")
349                continue
350            dep = deps[depid]
351            cf= dep.certificates
352            code = certificate.get('code')
353            certificate_id = code
354            c = getattr(cf,certificate_id,None)
355            if c is None:
356                logger.info('Creating certificate %(code)s  %(title)s in Department %(department_code)s' % certificate)
357                cf.invokeFactory('Certificate', certificate_id)
358                c = getattr(cf,certificate_id)
359            c.getContent().edit(mapping=certificate)
360            review_state = c.get('review_state')
361            if review_state == "checked" and wf.getInfoFor(c,'review_state',None) != 'checked':
362                self.portal_workflow.doActionFor(c,'approve')
363        if no_import_list:
364            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
365            heading = ','.join(['"%s"' % fn for fn in fields])
366            no_import.write('%s\n' % heading)
367            for line in no_import_list:
368                no_import.write(line)
369        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
370    ###)
371
372    security.declareProtected(ModifyPortalContent,"loadCertificateCoursesFromCSV")###(
373    def loadCertificateCoursesFromCSV(self):
374        """install Certificate Courses from CSV values"""
375        #return
376        logger = logging.getLogger('Academics.AcademicsFolder.loadCertificateCoursesFromCSV')
377        name = 'CertificateCourses'
378        wf = self.portal_workflow
379        no_import_list = []
380        fields = ("code",
381                  "review_state",
382                  "faculty_code",
383                  "department_code",
384                  "certificate_code",
385                  "level",
386                  "semester",
387                  "core_or_elective",
388                  )
389        format = ','.join(['"%%(%s)s"' % fn for fn in fields])
390        try:
391            cert_courses = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
392        except:
393            logger.error('Error reading %s.csv' % name)
394            return
395##        d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
396        c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
397        l = self.portal_catalog({'meta_type': "Certificate"})
398        certs = {}
399        for f in l:
400            ca,ac,fa,depid,co,code = f.relative_path.split('/')
401##            pid = "%(depid)s_%(code)s" % vars()
402            pid = "%(code)s" % vars()
403            certs[pid] = f.getObject()
404        for cert_course in cert_courses:
405            processing = "processing %s" % format
406            logger.info(processing % cert_course)
407##            depid = cert_course.get('department_code')
408            course_code = cert_course.get('code')
409            code = cert_course.get('certificate_code')
410##            pid = "%(depid)s_%(code)s" % vars()
411            pid = "%(code)s" % vars()
412            if not pid in certs.keys():
413                em = 'CertCode %(certificate_code)s for %(code)s not found\n' % cert_course
414                logger.info(em)
415                #no_import_list.append(em)
416                no_import_list.append(format % cert_course + ',"Certificate"\n')
417                continue
418            certificate = certs[pid]
419            certificate_code = certificate.getId()
420            if course_code not in c_ids:
421                em = 'Course %(code)s for %(certificate_code)s Level %(level)s not found in Courses\n' % cert_course
422                logger.info(em)
423                #no_import_list.append(em)
424                no_import_list.append(format % cert_course + ',"Course"\n')
425                continue
426##            if depid not in d_ids:
427##                em = 'Department %(department_code)s for %(certificate_code)s not found\n' % cert_course
428##                logger.info(em)
429##                #no_import_list.append(em)
430##                no_import_list.append(format % cert_course + ',"Department"\n')
431##                continue
432            level = cert_course.get('level')
433            l = getattr(certificate,level,None)
434            if l is None:
435                logger.info('Creating Level %(level)s in certificate %(certificate_code)s' % cert_course)
436                certificate.invokeFactory('StudyLevel', level)
437                l = getattr(certificate, level)
438                l.getContent().edit(mapping={'Title': "Level %s" % level})
439            certificate.orderObjects('id')
440            if hasattr(l,course_code):
441                msg = 'Duplicate %(code)s in Level %(level)s' % cert_course
442                logger.info(msg)
443                #no_import_list.append(msg + "\n")
444                no_import_list.append(format % cert_course + ',"duplicate"\n')
445                continue
446            l.invokeFactory('CertificateCourse',course_code)
447            logger.info('Creating CertificateCourse %(code)s in Certificate %(certificate_code)s StudyLevel %(level)s' % cert_course)
448            cc = getattr(l,course_code)
449            #semester = 'first'
450            #try:
451            #    sem = int(cert_course.get('semester'))
452            #    cert_course['semester'] = ('first','second')[sem - 1]
453            #except:
454            #    pass
455            cert_course['core_or_elective'] = cert_course['core_or_elective'] in ("TRUE","True")
456            cc.getContent().edit(mapping=cert_course)
457            review_state = cc.get('review_state')
458            if review_state == "checked" and wf.getInfoFor(cc,'review_state',None) != 'checked':
459                self.portal_workflow.doActionFor(cc,'approve')
460        if no_import_list:
461            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
462            heading = ','.join(['"%s"' % fn for fn in fields])
463            no_import.write('%s\n' % heading)
464            for line in no_import_list:
465                no_import.write(line)
466        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
467    ###)
468
469
470    security.declareProtected(ModifyPortalContent,"yamlDumpFaculties")###(
471    def yamlDumpFaculties(self):
472        """dump Faculies to Yaml"""
473        #return
474        import yaml
475        logger = logging.getLogger('dumpfaculties')
476        logger.info('Start dumping Faculties')
477        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
478        l = self.portal_catalog({'meta_type': "Faculty"})
479        facs = {}
480        for f in l:
481            facs[f.id] = f.getObject()
482        for fid in facs.keys():
483            faculty = facs.get(fid).aq_self
484            logger.info('dumping %s %s ' % (faculty.id, faculty.title))
485            print yaml.dump(faculty)
486        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
487
488    ###)
489
490
491    def exportLocalRoles(self,portal_type): ###(
492        name = '%sLocalRoles' % portal_type
493        logger = logging.getLogger('Academics.AcademicsFolder.exportLocalRoles')
494        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
495        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
496        objects = [f.getObject() for f in self.portal_catalog({'meta_type': portal_type})]
497        export = []
498        export.append('"code","users"')
499        #import pdb;pdb.set_trace()
500        for obj in objects:
501            lr = {}
502            for (username, roles) in obj.get_local_roles():
503                lr[ 'user:' + username ] = [x for x in roles]
504            for (groupname, roles) in obj.get_local_group_roles():
505                lr[ 'group:' + group ] = [x for x in roles]
506            logger.info('Exporting %s %s ' % (obj.id, lr))
507            export.append('"%s","%s"' % (obj.getId(),lr))
508        open("%s/export/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
509###)
510
511    security.declareProtected(ModifyPortalContent,"exportFacultiesToCSV")###(
512    def exportFacultiesToCSV(self):
513        """export Faculies to CSV"""
514        #return
515        if self.REQUEST.get('localroles'):
516            self.exportLocalRoles('Faculty')
517            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
518        name = 'Faculties'
519        no_import = False
520        logger = logging.getLogger('Academics.AcademicsFolder.exportFacultiesToCSV')
521        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
522        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
523        objects = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
524        export = []
525        export.append('"code","review_state","title","title_prefix","college_code","degree_grade","bank_code"')
526        for obj in objects:
527            logger.info('Exporting %s %s ' % (obj.id, obj.title))
528            obj_d = obj.getContent()
529            di = {}
530            di['code'] = obj_d.code
531            di['title'] = obj_d.title
532            di['title_prefix'] = obj_d.title_prefix
533            di['college_code'] = obj_d.college_code
534            di['degree_grade'] = obj_d.degree_grade
535            di['bank_code'] = obj_d.bank_code
536            di['code'] = di['code'] or obj.id
537            di['review_state'] = self.portal_workflow.getInfoFor(obj,'review_state','no_state')
538            export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(college_code)s","%(degree_grade)s","%(bank_code)s"' % di)
539        open("%s/export/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
540        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
541
542    ###)
543
544    security.declareProtected(ModifyPortalContent,"exportDepartmentsToCSV")###(
545    def exportDepartmentsToCSV(self):
546        """export Faculies to CSV"""
547        #return
548        if self.REQUEST.get('localroles'):
549            self.exportLocalRoles('Department')
550            return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
551        name = 'Departments'
552        no_import = False
553        logger = logging.getLogger('Academics.AcademicsFolder.exportDepartmentsToCSV')
554        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
555        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
556        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
557        export = []
558        export.append('"code","review_state","title","title_prefix","faculty_code"')
559        #import pdb;pdb.set_trace()
560        for faculty in faculties:
561            di = {}
562            di['faculty_code'] = faculty.id
563            for department in faculty.objectValues():
564                department_d = department.getContent()
565                try:
566                    di['code'] =  department.getId()
567                    di['title'] = department_d.title
568                    di['title_prefix'] = department_d.title_prefix
569                    di['review_state'] = self.portal_workflow.getInfoFor(department,'review_state','no_state')
570                    export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(faculty_code)s"' % di)
571                    logger.info('Exporting %s %s ' % (department.id, department.title))
572                except:
573                    logger.info('could not export %s %s ' % (department.id, department.title))
574                    continue
575        open("%s/export/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
576        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
577    ###)
578
579    security.declareProtected(ModifyPortalContent,"exportCoursesToCSV")###(
580    def exportCoursesToCSV(self):
581        """export Courses to CSV"""
582        #return
583        name = 'Courses'
584        no_import = False
585        logger = logging.getLogger('Academics.AcademicsFolder.exportCoursesToCSV')
586        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
587        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
588        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
589        export = []
590        heading = '"code","review_state","title","faculty_code","department_code",'
591        heading += '"credits","org_code","passmark","semester","session"'
592        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
593        dataline += '"%(credits)s","%(org_code)s","%(passmark)s","%(semester)s","%(session)s"'
594        export.append(heading)
595        #import pdb;pdb.set_trace()
596        fields = ("title",
597                  "credits",
598                  "org_code",
599                  "passmark",
600                  "semester",
601                  "session",
602                  )
603        for faculty in faculties:
604            di = {}
605            di['faculty_code'] = faculty.id
606            for department in faculty.objectValues():
607                di['department_code'] = department.id
608                for course in department.courses.objectValues():
609                    di['code'] = course.getId()
610                    course_d = course.getContent()
611                    for f in fields:
612                        di[f] = getattr(course_d,f,None)
613                    di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
614                    export.append(dataline % di)
615                    logger.info('Exporting %s %s ' % (course.id, course.title))
616                    continue
617        open("%s/export/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
618        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
619    ###)
620
621    security.declareProtected(ModifyPortalContent,"exportCertificatesToCSV")###(
622    def exportCertificatesToCSV(self):
623        """export Certificates to CSV"""
624        #return
625        name = 'Certificates'
626        no_import = False
627        logger = logging.getLogger('Academics.AcademicsFolder.exportCertificatesToCSV')
628        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
629        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
630        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
631        export = []
632        heading = '"code","review_state","title","faculty_code","department_code",'
633        heading += '"category","study_mode","end_level","m_prefix","max_elect","max_pass",'
634        heading += '"n_core","nr_years","original_code","probation_credits",'
635        heading += '"promotion_credits","start_level","admin_status","application_category"'
636        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
637        dataline += '"%(category)s","%(study_mode)s","%(end_level)s","%(m_prefix)s","%(max_elect)s","%(max_pass)s",'
638        dataline += '"%(n_core)s","%(nr_years)s","%(original_code)s","%(probation_credits)s",'
639        dataline += '"%(promotion_credits)s","%(start_level)s","%(admin_status)s","%(application_category)s"'
640        export.append(heading)
641        #import pdb;pdb.set_trace()
642        for faculty in faculties:
643            di = {}
644            di['faculty_code'] = faculty.id
645            for department in faculty.objectValues():
646                di['department_code'] = department.id
647                for certificate in department.certificates.objectValues():
648                    certificate_d = certificate.getContent()
649                    di['code'] = certificate.id
650                    #di['code'] = getattr(certificate_d,'code',None)
651                    di['title'] = getattr(certificate_d,'title',None)
652                    di['study_mode'] = getattr(certificate_d,'study_mode',None)
653                    di['category'] = getattr(certificate_d,'category',None)
654                    di['admin_status'] = getattr(certificate_d,'admin_status',None)
655                    di['end_level'] = getattr(certificate_d,'end_level',None)
656                    di['m_prefix'] = getattr(certificate_d,'m_prefix',None)
657                    di['max_elect'] = getattr(certificate_d,'max_elect',None)
658                    di['max_load'] = getattr(certificate_d,'max_load',None)
659                    di['max_pass'] = getattr(certificate_d,'max_pass',None)
660                    di['n_core'] = getattr(certificate_d,'n_core',None)
661                    di['nr_years'] = getattr(certificate_d,'nr_years',None)
662                    di['original_code'] = getattr(certificate_d,'original_code',None)
663                    di['probation_credits'] = getattr(certificate_d,'probation_credits',None)
664                    di['promotion_credits'] = getattr(certificate_d,'promotion_credits',None)
665                    di['start_level'] = getattr(certificate_d,'start_level',None)
666                    di['application_category'] = getattr(certificate_d,'application_category',None)
667                    di['code'] = di['code'] or certificate.id
668                    di['review_state'] = self.portal_workflow.getInfoFor(certificate,'review_state','no_state')
669                    try:
670                        export.append(dataline % di)
671                        logger.info('Exporting %s %s ' % (certificate.id, certificate.title))
672                    except:
673                        logger.info('could not export %s %s ' % (certificate.id, certificate.title))
674                    continue
675        open("%s/export/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
676        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
677    ###)
678
679    security.declareProtected(ModifyPortalContent,"exportCertificateCoursesToCSV")###(
680    def exportCertificateCoursesToCSV(self):
681        """export CertificateCourses to CSV"""
682        #return
683        name = 'CertificateCourses'
684        no_import = False
685        logger = logging.getLogger('Academics.AcademicsFolder.exportCertificateCoursesToCSV')
686        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
687        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
688        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
689        export = []
690        heading = '"code","review_state","faculty_code","department_code",'
691        heading += '"certificate_code","level","core_or_elective"'
692        dataline = '"%(code)s","%(review_state)s","%(faculty_code)s","%(department_code)s",'
693        dataline += '"%(certificate_code)s","%(level)s","%(core_or_elective)s"'
694        export.append(heading)
695        semesters = ['first','second']
696        for faculty in faculties:
697            di = {}
698            di['faculty_code'] = faculty.id
699            for department in faculty.objectValues():
700                di['department_code'] = department.id
701                for certificate in department.certificates.objectValues():
702                    di['certificate_code'] = certificate.id
703                    logger.info('Exporting %s/%s/%s' % (faculty.id,department.id,certificate.id))
704                    for level in certificate.objectValues():
705                        di['level'] = level.id
706                        for course in level.objectValues():
707                            di['code'] = course.getId()
708                            course_d = course.getContent()
709                            di['core_or_elective'] = getattr(course_d,'core_or_elective',None)
710                            di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
711                            try:
712                                export.append(dataline % di)
713                            except:
714                                logger.info('Could not export %s %s' % (certificate.id, di['code']))
715                                continue
716        open("%s/export/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
717        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
718    ###)
719
720
721InitializeClass(AcademicsFolder)
722
723def addAcademicsFolder(container, id, REQUEST=None, **kw):
724    """Add a AcademicsFolder."""
725    ob = AcademicsFolder(id, **kw)
726    return CPSBase_adder(container, ob, REQUEST=REQUEST)
727
728###)
729
730class Certificate(CPSDocument): ###(
731    """
732    WAeUP Certificate
733    """
734    meta_type = 'Certificate'
735    portal_type = meta_type
736    security = ClassSecurityInfo()
737
738    def __init__(self, id, **kw):
739        CPSDocument.__init__(self, id, **kw)
740
741##    security.declareProtected(View,"Title")
742##    def Title(self):
743##        """compose title"""
744##        return "Certificate of %s" % (self.title)
745
746InitializeClass(Certificate)
747
748def addCertificate(container, id, REQUEST=None, **kw):
749    """Add a Certificate."""
750    ob = Certificate(id, **kw)
751    return CPSBase_adder(container, ob, REQUEST=REQUEST)
752
753###)
754
755class StudyLevel(CPSDocument): ###(
756    """
757    WAeUP StudyLevel containing the courses and students
758    """
759    meta_type = 'StudyLevel'
760    portal_type = meta_type
761    security = ClassSecurityInfo()
762
763    security.declareProtected(View,"Title")
764    def Title(self):
765        """compose title"""
766        return self.portal_vocabularies.levels.get(self.aq_parent.getId())
767        # try:
768        #     #return "Level %s" % self.aq_parent.getId()
769        # except:
770        #     return "no Title for %s" % self.getId()
771
772
773InitializeClass(StudyLevel)
774
775def addStudyLevel(container, id, REQUEST=None, **kw):
776    """Add a StudyLevel."""
777    ob = StudyLevel(id, **kw)
778    return CPSBase_adder(container, ob, REQUEST=REQUEST)
779
780###)
781
782class CertificateCourse(CPSDocument): ###(
783    """
784    WAeUP CertificateCourse
785    """
786    meta_type = 'CertificateCourse'
787    portal_type = meta_type
788    security = ClassSecurityInfo()
789
790    def getCourseEntry(self,cid):
791        res = self.courses_catalog({'code': cid})
792        if res:
793            return res[-1]
794        else:
795            return None
796
797    security.declareProtected(View,"Title")
798    def Title(self):
799        """compose title"""
800        #import pdb;pdb.set_trace()
801        ce = self.getCourseEntry(self.aq_parent.getId())
802        #print self.id, self.aq_parent.id
803        if ce:
804            return "%s" % ce.title
805        return "No such course"
806
807    security.declareProtected(View,"credits")
808    def credits(self):
809        """credits from course"""
810        ce = self.getCourseEntry(self.id)
811        if ce:
812            return "%s" % ce.credits
813        return "0"
814
815    security.declareProtected(View,"passmark")
816    def passmark(self):
817        """passmark from course"""
818        ce = self.getCourseEntry(self.id)
819        if ce is not None and hasattr(ce,"passmark"):
820            return ce.passmark
821
822
823    security.declareProtected(View,"coursepath")
824    def coursepath(self):
825        """coursepath from course"""
826        ce = self.getCourseEntry(self.id)
827        if ce:
828            return ce.getPath()
829        return "?"
830
831
832InitializeClass(CertificateCourse)
833
834def addCertificateCourse(container, id, REQUEST=None, **kw):
835    """Add a CertificateCourse."""
836    ob = CertificateCourse(id, **kw)
837    return CPSBase_adder(container, ob, REQUEST=REQUEST)
838###)
839
840class Faculty(CPSDocument): ###(
841    """
842    WAeUP Faculty containing Departments
843    """
844    meta_type = 'Faculty'
845    portal_type = meta_type
846    security = ClassSecurityInfo()
847
848##    def __init__(self, id, **kw):
849##        CPSDocument.__init__(self, id, **kw)
850
851    security.declareProtected(View,"Title")
852    def Title(self):
853        """compose title"""
854        return "%s" % (self.title)
855
856
857    security.declareProtected(View,"LongTitle")
858    def LongTitle(self):
859        """compose long_title"""
860        prefix = getattr(self,'title_prefix',None)
861        if prefix is None:
862            prefix = getattr(self,'institution_type','faculty')
863            self.getContent().edit(mapping = {'title_prefix': prefix})
864        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Faculty of")
865        return "%s %s" % (itype,self.title)
866
867InitializeClass(Faculty)
868
869def addFaculty(container, id, REQUEST=None, **kw):
870    """Add a Faculty."""
871    ob = Faculty(id, **kw)
872    return CPSBase_adder(container, ob, REQUEST=REQUEST)
873
874###)
875
876class Department(CPSDocument): ###(
877    """
878    WAeUP Department containing the courses and students
879    """
880    meta_type = 'Department'
881    portal_type = meta_type
882    security = ClassSecurityInfo()
883
884    security.declareProtected(View,"LongTitle")
885    def LongTitle(self):
886        """compose long_title"""
887        prefix = getattr(self,'title_prefix',None)
888        if prefix is None:
889            prefix = getattr(self,'institution_type','department')
890            self.getContent().edit(mapping = {'title_prefix': prefix})
891        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Department of")
892        return "%s %s" % (itype,self.title)
893
894InitializeClass(Department)
895
896def addDepartment(container, id, REQUEST=None, **kw):
897    """Add a Department."""
898    object = Department(id, **kw)
899    id = object.getId()
900    container._setObject(id, object)
901##    dep = getattr(container,id).getEditableContent()   #getContent()
902##    dep.invokeFactory('CoursesFolder','Courses')
903##    o = getattr(dep,'Courses')
904##    dict = {'Title': 'Courses'}
905##    o.getContent().edit(mapping=dict)
906##    dep.invokeFactory('CertificatesFolder','Certificates')
907##    o = getattr(dep,'Certificates')
908##    dict = {'Title': 'Certificates'}
909##    o.geetContent().edit(mapping=dict)
910    if REQUEST is not None:
911        url = container.absolute_url()
912        REQUEST.RESPONSE.redirect('%s/manage_main' % url)
913
914###)
915
916class Course(CPSDocument): ###(
917    """
918    WAeUP Course
919    """
920    meta_type = 'Course'
921    portal_type = meta_type
922    security = ClassSecurityInfo()
923
924    security.declareProtected(View,"Title")
925    def Title(self):
926        """compose title"""
927        return self.title
928
929InitializeClass(Course)
930
931def addCourse(container, id, REQUEST=None, **kw):
932    """Add a Course."""
933    ob = Course(id, **kw)
934    return CPSBase_adder(container, ob, REQUEST=REQUEST)
935###)
936
937
Note: See TracBrowser for help on using the repository browser.