source: WAeUP_SRP/trunk/Academics.py @ 1138

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

logging messages changed

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