source: WAeUP_SRP/trunk/Academics.py @ 547

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

fixed #14 + #15'

  • Property svn:keywords set to Id
File size: 39.4 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
35class AcademicsFolder(CPSDocument): ###(
36    """
37    WAeUP AcademicsFolder containing StudyCourses
38    """
39    meta_type = 'AcademicsFolder'
40    portal_type = meta_type
41    security = ClassSecurityInfo()
42    use_catalog_for_folder_contents = True
43
44    security.declareProtected(View,"Title")
45    def Title(self):
46        """compose title"""
47        return "Academic Section"
48
49    security.declareProtected(ModifyPortalContent,"loadFacultiesFromCSV")###(
50    def loadFacultiesFromCSV(self):
51        """install Universityspecific Faculies from CSV values"""
52        #return
53        name = 'faculty'
54        no_import = False
55        logger = logging.getLogger('%s_import' % name)
56        logger.info('Start loading from %s.csv' % name)
57        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
58        try:
59            faculties = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
60        except:
61            logger.error('Error reading %s.csv' % name)
62            return
63        l = self.portal_catalog({'meta_type': "Faculty"})
64        facs = {}
65        for f in l:
66            facs[f.id] = f.getObject()
67        for faculty in faculties:
68            logger.info('processing %(Session)s %(FacultyCode)s %(Description)s %(CollegeCode)s %(FacultyKey)s %(Status)s %(degree_grade)s %(Bankcode)s' % faculty)
69            fid = faculty['FacultyCode']
70            f = facs.get(fid,None)
71            if f is None:
72                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
73                logger.info('Creating Faculty with ID %(FacultyCode)s %(Description)s' % faculty)
74                academics.invokeFactory('Faculty', fid)
75                f = getattr(self,fid)
76                d = {'Title': faculty['Description']}
77            else:
78                d = {}
79            d['bank_code'] = faculty.get("Bankcode")
80            d["degree_grade"] = faculty.get("degree_grade")
81            d['institution_type'] = 'faculty'
82            d['Description'] = ''
83            d['college_code'] = faculty.get('CollegeCode')
84            f.getContent().edit(mapping=d)
85        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
86    ###)
87
88    security.declareProtected(ModifyPortalContent,"yamlDumpFaculties")###(
89    def yamlDumpFaculties(self):
90        """dump Faculies to Yaml"""
91        #return
92        import yaml
93        logger = logging.getLogger('dumpfaculties')
94        logger.info('Start dumping Faculties')
95        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
96        l = self.portal_catalog({'meta_type': "Faculty"})
97        facs = {}
98        for f in l:
99            facs[f.id] = f.getObject()
100        for fid in facs.keys():
101            faculty = facs.get(fid).aq_self
102            logger.info('dumping %s %s ' % (faculty.id, faculty.title))
103            print yaml.dump(faculty)
104        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
105
106    ###)
107
108    security.declareProtected(ModifyPortalContent,"loadDepartmentsFromCSV")###(
109    def loadDepartmentsFromCSV(self):
110        """install Universityspecific Faculies from CSV values"""
111        #return
112        name = 'departments'
113        no_import = False
114        logger = logging.getLogger('loaddepartments')
115        try:
116            deps = csv.DictReader(open("%s/import/departments.csv" % i_home,"rb"))
117        except:
118            logger.error('Error reading departments.csv')
119            return
120        l = self.portal_catalog({'meta_type': "Faculty"})
121        facs = {}
122        for f in l:
123            facs[f.id] = f.getObject()
124        for dep in deps:
125            logger.info('Processing %(Session)s %(DeptCode)s %(Description)s %(FacultyCode)s' % dep)
126            fid = dep['FacultyCode']
127            f = facs.get(fid,None)
128            if f is None:
129                logger.info( "No Faculty with ID: %s" % fid)
130                if not no_import:
131                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
132                    no_import.write('"Session","DeptCode","Description","FacultyCode"\n')
133                no_import.write( "No Faculty with ID: %s\n" % fid)
134                no_import.write('"%(Session)s","%(DeptCode)s","%(Description)s","%(FacultyCode)s"\n' % dep)
135            else:
136                did = dep.get('DeptCode')
137                d = getattr(f,did,None)
138                if d is None or d.portal_type == "Faculty":
139                    logger.info('Creating Department %(DeptCode)s = %(Description)s' % dep)
140                    f.invokeFactory('Department', did)
141                    d = getattr(f,did)
142                    dict = {'Title': dep['Description']}
143                    d.getContent().edit(mapping=dict)
144                    d.invokeFactory('CoursesFolder','courses')
145                    courses = getattr(d,'courses')
146                    dict = {'Title': 'Courses'}
147                    courses.getContent().edit(mapping=dict)
148                    d.invokeFactory('CertificatesFolder','certificates')
149                    certificates = getattr(d,'certificates')
150                    dict = {'Title': 'Certificates'}
151                    certificates.getContent().edit(mapping=dict)
152        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
153    ###)
154
155    security.declareProtected(ModifyPortalContent,"loadCoursesFromCSV")###(
156    def loadCoursesFromCSV(self):
157        """install Universityspecific Courses from CSV values"""
158        #return
159        name = 'courses'
160        no_import = False
161        logger = logging.getLogger('loadcourses')
162        try:
163            courses = csv.DictReader(open("%s/import/courses.csv" % i_home,"rb"))
164        except:
165            logger.error('Error reading courses.csv')
166            return
167        l = self.portal_catalog({'meta_type': "Faculty"})
168        facs = {}
169        for f in l:
170            facs[f.id] = f.getObject()
171        dl = self.portal_catalog({'meta_type': "Department"})
172        deps = {}
173        for d in dl:
174            deps[d.id] = d.getObject()
175        cl = self.portal_catalog({'meta_type': "Course"})
176        course_list = [ c.id for c in cl]
177        for course in courses:
178            logger.info('Processing %(CourseCode)s %(Description)s %(Credits)s %(Dept)s %(Semester)s %(Session)s %(PassMark)s %(Category)s %(AdmStatus)s' % course)
179##            if course.get("FORMERCODE").endswith('BITS'):
180##                continue
181            depid = course.get('Dept').upper()
182            if depid in deps.keys():
183                dept= deps.get(depid)
184    ##        elif depid in facs.keys():
185    ##            dept= facs.get(depid)
186            else:
187                logger.info("Dep %(Dept)s for Course %(CourseCode)s not found" % course)
188                if not no_import:
189                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
190                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","Category","AdmStatus"\n')
191                no_import.write("Dep %(Dept)s for Course %(CourseCode)s not found\n" % course)
192                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(Category)s","%(AdmStatus)s"\n' % course)
193                continue
194            course_id = ''.join(re.split('\W+',course.get('CourseCode')))
195            if len(course_id) == 3:
196                course_id = "%s000" % course_id
197            elif len(course_id) > 10:
198                logger.info("invalid course_code %(CourseCode)s" % course)
199                if not no_import:
200                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
201                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","Category","AdmStatus"\n')
202                no_import.write("invalid course_code %(CourseCode)s\n" % course)
203                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(Category)s","%(AdmStatus)s"\n' % course)
204                continue
205            courses = dept.courses
206            c = getattr(courses,course_id,None)
207            if c is None:
208                logger.info('Creating Course %(CourseCode)s  %(Description)s in Department %(Dept)s' % course)
209                courses.invokeFactory('Course', course_id)
210                c = getattr(courses,course_id)
211            dict = {'Title': course['Description']}
212            dict['code'] = course_id
213            dict['org_code'] = course.get('CourseCode')
214            dict['credits'] = course.get('Credits')
215            dict['semester'] = course.get('Semester')
216            dict['session'] = course.get('Session')
217            dict['category'] = course.get('Category')
218            dict['adm_status'] = course.get('AdmStatus')
219            dict['former_code'] = course.get('FORMERCODE')
220            pm = course.get('PassMark')
221            if pm.find(',') > -1:
222                pm.replace(',','.')
223            elif pm == "":
224                pm = "0.0"
225            try:
226                dict['passmark'] = int(float(pm))
227            except:
228                dict['passmark'] = 0
229            c.getContent().edit(mapping=dict)
230        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
231    ###)
232
233    security.declareProtected(ModifyPortalContent,"loadCertificatesFromCSV")###(
234
235    def loadCertificatesFromCSV(self):
236        """install Universityspecific Certificates from CSV values"""
237        #return
238        name = 'certificates'
239        no_import = False
240        logger = logging.getLogger('loadcertificates')
241        try:
242            certificates = csv.DictReader(open("%s/import/certificates.csv" % i_home,"rb"))
243        except:
244            logger.error('Error reading certificates.csv')
245            return
246        f_ids = [f.id for f in self.portal_catalog({'meta_type': "Faculty"})]
247        #d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
248        dl = self.portal_catalog({'meta_type': "Department"})
249        deps = {}
250        for d in dl:
251            deps[d.id] = d.getObject()
252        for certificate in certificates:
253            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)
254            depid = certificate.get('Dept')
255            facid = certificate.get('Faculty')
256            if facid not in f_ids:
257                logger.info('Faculty %(Faculty)s for %(CertCode)s %(Description)s not found' % certificate)
258                if not no_import:
259                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
260                    no_import.write('"CertCode","Description","Faculty","MaxPass","MaxLoad","session","PromotionCredits","Probationcredits","StartLevel","endLevel","Nyears","Ncore","MaxElect","MPREFIX","Dept","Admstatus","category"\n')
261                no_import.write('Faculty %(Faculty)s for %(CertCode)s %(Description)s not found\n' % certificate)
262                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)
263                continue
264            if not deps.has_key(depid):
265                logger.info('Department %(Dept)s for %(CertCode)s %(Description)s not found' % certificate)
266                if not no_import:
267                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
268                    no_import.write('"CertCode","Description","Faculty","MaxPass","MaxLoad","session","PromotionCredits","Probationcredits","StartLevel","endLevel","Nyears","Ncore","MaxElect","MPREFIX","Dept","Admstatus","category"\n')
269                no_import.write('Department %(Dept)s for %(CertCode)s %(Description)s not found\n' % certificate)
270                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)
271                continue
272            #certificate_id = "%(category)s_%(Admstatus)s_%(Dept)s" % certificate
273            dep = deps[depid]
274            certificates = dep.certificates
275            code = makeCertificateCode(certificate.get('CertCode'))
276            certificate_id = code
277            c = getattr(certificates,certificate_id,None)
278            if c is None:
279                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
280                logger.info('Creating certificate %(CertCode)s  %(Description)s in Department %(Dept)s' % certificate)
281                certificates.invokeFactory('Certificate', certificate_id)
282                c = getattr(certificates,certificate_id)
283                dict = {'Title': certificate['Description']}
284                dict['code'] = code
285                dict['faculty'] = certificate.get('Faculty')
286                dict['department'] = certificate.get('Dept')
287                dict['max_pass'] = certificate.get('MaxPass')
288                dict['max_load'] = certificate.get('MaxLoad')
289                dict['admin_status'] = certificate.get('Admstatus')
290                dict['category'] = certificate.get('category')
291                dict['m_prefix'] = certificate.get('MPREFIX')
292                dict['nr_years'] = int(certificate.get('Nyears'))
293                nc = certificate.get('Ncore','1')
294                try:
295                    dict['n_core'] = int(nc)
296                except:
297                    dict['n_core'] = 1
298                dict['start_level'] = certificate.get('StartLevel')
299                dict['end_level'] = certificate.get('endLevel')
300                dict['promotion_credits'] = certificate.get('PromotionCredits')
301                dict['probation_credits'] = certificate.get('ProbationCredits')
302            else:
303                dict = {}
304            dict['original_code'] = certificate.get('CertCode')
305            print
306            c.getContent().edit(mapping=dict)
307        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
308    ###)
309
310    security.declareProtected(ModifyPortalContent,"loadCertificateCoursesFromCSV")###(
311    def loadCertificateCoursesFromCSV(self):
312        """install Certificate Courses from CSV values"""
313        #return
314        logger = logging.getLogger('loadcertificatecourses')
315        name = 'certificate_courses'
316        no_import = False
317        try:
318            cert_courses = csv.DictReader(open("%s/import/course_level_courses.csv" % i_home,"rb"))
319        except:
320            logger.error('Error reading course_level_courses.csv')
321            return
322        d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
323        c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
324        l = self.portal_catalog({'meta_type': "Certificate"})
325        certs = {}
326        for f in l:
327            certs[f.id] = f.getObject()
328        for cert_course in cert_courses:
329            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)
330            depid = cert_course.get('Dept')
331            course_code = cert_course.get('CosCode')
332            code = cert_course.get('CertCode')
333            code = code.replace('.','')
334            code = code.replace('(','')
335            code = code.replace(')','')
336            code = code.replace('/','')
337            code = code.replace(' ','')
338            code = code.replace('_','')
339##            if cert_course.get('Session') != '2002/2003':
340##                continue
341##            certificate = self.portal_catalog({'meta_type': "Certificate",
342##                                               'SearchableText': code})
343##            if not certificate:
344            if not code in certs.keys():
345                #print code
346                em = 'CertCode %(CertCode)s for %(CosCode)s not found\n' % cert_course
347                logger.info(em)
348                if not no_import:
349                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
350                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
351                no_import.write(em)
352                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)
353                continue
354            certificate = certs[code]
355            certificate_code = certificate.getId()
356            if course_code not in c_ids:
357                em = 'CorseCode %(CosCode)s for %(CertCode)s not found in Courses\n' % cert_course
358                logger.info(em)
359                if not no_import:
360                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
361                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
362                no_import.write(em)
363                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)
364                continue
365            if depid not in d_ids:
366                em = 'Department %(Dept)s for %(CertCode)s not found\n' % cert_course
367                logger.info(em)
368                if not no_import:
369                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
370                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
371                no_import.write(em)
372                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)
373                continue
374            level = cert_course.get('Level')
375            l = getattr(certificate,level,None)
376            if l is None:
377                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
378                logger.info('Creating Level %(Level)s in certificate %(CertCode)s' % cert_course)
379                certificate.invokeFactory('StudyLevel', level)
380                l = getattr(certificate, level)
381                l.getContent().edit(mapping={'Title': "Level %s" % level})
382                l.invokeFactory('Semester','first')
383                l.invokeFactory('Semester','second')
384            certificate.orderObjects('id')
385            first_s = getattr(l,'first')
386            first_s.getContent().edit(mapping={'Title': 'First Semester'})
387            second_s = getattr(l,'second')
388            second_s.getContent().edit(mapping={'Title': 'Second Semester'})
389            if cert_course.get('Semester') == '1':
390                semester = first_s
391            else:
392                semester = second_s
393            if hasattr(semester,course_code):
394                logger.info('Duplicate %(CosCode)s in Level %(Level)s' % cert_course)
395                if not no_import:
396                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
397                    no_import.write('"CosCode","CertCode","Session","Level","Core","Elective","Mandatory","AdmStatus","Dept","Semester"\n')
398##                no_import.write('Duplicate %(CosCode)s in Level %(Level)s' % cert_course)
399##                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)
400                continue
401            semester.invokeFactory('CertificateCourse',course_code)
402            cc = getattr(semester,course_code)
403            dict = {}
404            dict['code'] = cert_course.get('CosCode')
405            dict['certificate_code'] = code
406            dict['certificate_code_org'] = cert_course.get('CertCode')
407            dict['department'] = cert_course.get('Dept')
408            dict['admin_status'] = cert_course.get('Admstatus')
409            dict['session'] = cert_course.get('Session')
410            if cert_course.get('Core') != '':
411                dict['core_or_elective'] = True
412            else:
413                dict['core_or_elective'] = False
414            dict['level'] = cert_course.get('Level')
415            cc.getContent().edit(mapping=dict)
416        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
417    ###)
418
419    security.declareProtected(ModifyPortalContent,"exportFacultiesToCSV")###(
420    def exportFacultiesToCSV(self):
421        """export Faculies to CSV"""
422        #return
423        name = 'Faculty'
424        no_import = False
425        logger = logging.getLogger('%s_export' % name)
426        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
427        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
428        objects = [f.getObject() for f in self.portal_catalog({'meta_type': name})]
429        export = []
430        export.append('"code","review_state","title","title_prefix","college_code","degree_grade","bank_code"')
431        for obj in objects:
432            logger.info('exporting %s %s ' % (obj.id, obj.title))
433            obj_d = obj.getContent()
434            di = {}
435            di['code'] = obj_d.code
436            di['title'] = obj_d.title
437            di['title_prefix'] = obj_d.title_prefix
438            di['college_code'] = obj_d.college_code
439            di['degree_grade'] = obj_d.degree_grade
440            di['bank_code'] = obj_d.bank_code
441            di['code'] = di['code'] or obj.id
442            di['review_state'] = self.portal_workflow.getInfoFor(obj,'review_state','no_state')
443            export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(college_code)s","%(degree_grade)s","%(bank_code)s"' % di)
444        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
445        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
446
447    ###)
448
449    security.declareProtected(ModifyPortalContent,"exportDepartmentsToCSV")###(
450    def exportDepartmentsToCSV(self):
451        """export Faculies to CSV"""
452        #return
453        import copy
454        name = 'Department'
455        no_import = False
456        logger = logging.getLogger('%s_export' % name)
457        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
458        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
459        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
460        export = []
461        export.append('"code","review_state","title","title_prefix","faculty_code"')
462        #import pdb;pdb.set_trace()
463        for faculty in faculties:
464            di = {}
465            di['faculty_code'] = faculty.id
466            for department in faculty.objectValues():
467                department_d = department.getContent()
468                try:
469                    di['code'] = department_d.code
470                    di['title'] = department_d.title
471                    di['title_prefix'] = department_d.title_prefix
472                    di['code'] = di['code'] or department.id
473                    di['review_state'] = self.portal_workflow.getInfoFor(department,'review_state','no_state')
474                    export.append('"%(code)s","%(review_state)s","%(title)s","%(title_prefix)s","%(faculty_code)s"' % di)
475                    logger.info('exporting %s %s ' % (department.id, department.title))
476                except:
477                    logger.info('could not export %s %s ' % (department.id, department.title))
478                    continue
479        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
480        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
481    ###)
482
483    security.declareProtected(ModifyPortalContent,"exportCoursesToCSV")###(
484    def exportCoursesToCSV(self):
485        """export Courses to CSV"""
486        #return
487        name = 'Course'
488        no_import = False
489        logger = logging.getLogger('%s_export' % name)
490        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
491        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
492        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
493        export = []
494        heading = '"code","review_state","title","faculty_code","department_code",'
495        heading += '"credits","org_code","passmark","semester","session"'
496        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
497        dataline += '"%(credits)s","%(org_code)s","%(passmark)s","%(semester)s","%(session)s"'
498        export.append(heading)
499        #import pdb;pdb.set_trace()
500        for faculty in faculties:
501            di = {}
502            di['faculty_code'] = faculty.id
503            for department in faculty.objectValues():
504                di['department_code'] = department.id
505                for course in department.courses.objectValues():
506                    course_d = course.getContent()
507                    try:
508                        di['code'] = course_d.code
509                        di['title'] = course_d.title
510                        di['category'] = course_d.category
511                        di['adm_status'] = course_d.adm_status
512                        di['credits'] = course_d.credits
513                        di['former_code'] = course_d.former_code
514                        di['org_code'] = course_d.org_code
515                        di['passmark'] = course_d.passmark
516                        di['semester'] = course_d.semester
517                        di['session'] = course_d.session
518                        di['code'] = di['code'] or course.id
519                        di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
520                        export.append(dataline % di)
521                        logger.info('exporting %s %s ' % (course.id, course.title))
522                    except:
523                        logger.info('could not export %s %s ' % (course.id, course.title))
524                    continue
525        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
526        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
527    ###)
528
529    security.declareProtected(ModifyPortalContent,"exportCertificatesToCSV")###(
530    def exportCertificatesToCSV(self):
531        """export Certificates to CSV"""
532        #return
533        name = 'Certificate'
534        no_import = False
535        logger = logging.getLogger('%s_export' % name)
536        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
537        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
538        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
539        export = []
540        heading = '"code","review_state","title","faculty_code","department_code",'
541        heading += '"category","end_level","m_prefix","max_elect","max_pass",'
542        heading += '"n_core","nr_years","original_code","probation_credits",'
543        heading += '"promotion_credits","start_level","admin_status"'
544        dataline = '"%(code)s","%(review_state)s","%(title)s","%(faculty_code)s","%(department_code)s",'
545        dataline += '"%(category)s","%(end_level)s","%(m_prefix)s","%(max_elect)s","%(max_pass)s",'
546        dataline += '"%(n_core)s","%(nr_years)s","%(original_code)s","%(probation_credits)s",'
547        dataline += '"%(promotion_credits)s","%(start_level)s","%(admin_status)s"'
548        export.append(heading)
549        #import pdb;pdb.set_trace()
550        for faculty in faculties:
551            di = {}
552            di['faculty_code'] = faculty.id
553            for department in faculty.objectValues():
554                di['department_code'] = department.id
555                for certificate in department.certificates.objectValues():
556                    certificate_d = certificate.getContent()
557                    di['code'] = getattr(certificate_d,'code',None)
558                    di['title'] = getattr(certificate_d,'title',None)
559                    di['category'] = getattr(certificate_d,'category',None)
560                    di['admin_status'] = getattr(certificate_d,'admin_status',None)
561                    di['end_level'] = getattr(certificate_d,'end_level',None)
562                    di['m_prefix'] = getattr(certificate_d,'m_prefix',None)
563                    di['max_elect'] = getattr(certificate_d,'max_elect',None)
564                    di['max_load'] = getattr(certificate_d,'max_load',None)
565                    di['max_pass'] = getattr(certificate_d,'max_pass',None)
566                    di['n_core'] = getattr(certificate_d,'n_core',None)
567                    di['nr_years'] = getattr(certificate_d,'nr_years',None)
568                    di['original_code'] = getattr(certificate_d,'original_code',None)
569                    di['probation_credits'] = getattr(certificate_d,'probation_credits',None)
570                    di['promotion_credits'] = getattr(certificate_d,'promotion_credits',None)
571                    di['start_level'] = getattr(certificate_d,'start_level',None)
572                    di['code'] = di['code'] or certificate.id
573                    di['review_state'] = self.portal_workflow.getInfoFor(certificate,'review_state','no_state')
574                    try:
575                        export.append(dataline % di)
576                        logger.info('exporting %s %s ' % (certificate.id, certificate.title))
577                    except:
578                        logger.info('could not export %s %s ' % (certificate.id, certificate.title))
579                    continue
580        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
581        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
582    ###)
583
584    security.declareProtected(ModifyPortalContent,"exportCertificateCoursesToCSV")###(
585    def exportCertificateCoursesToCSV(self):
586        """export CertificateCourses to CSV"""
587        #return
588        name = 'CertificateCourse'
589        no_import = False
590        logger = logging.getLogger('%s_export' % name)
591        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
592        logger.info('Start exporting %(name)s to %(name)s_%(current)s.csv' % vars())
593        faculties = [f.getObject() for f in self.portal_catalog({'meta_type': 'Faculty'})]
594        export = []
595        heading = '"code","review_state","faculty_code","department_code",'
596        heading += '"certificate_code","level","semester","core_or_elective"'
597        dataline = '"%(code)s","%(review_state)s","%(faculty_code)s","%(department_code)s",'
598        dataline += '"%(certificate_code)s","%(level)s","%(semester)s","%(core_or_elective)s"'
599        export.append(heading)
600        #import pdb;pdb.set_trace()
601        semesters = ['first','second']
602        for faculty in faculties:
603            di = {}
604            di['faculty_code'] = faculty.id
605            for department in faculty.objectValues():
606                di['department_code'] = department.id
607                for certificate in department.certificates.objectValues():
608                    di['certificate_code'] = certificate.id
609                    for level in certificate.objectValues():
610                        di['level'] = level.id
611                        for sem in semesters:
612                            semester = getattr(level,sem,None)
613                            if semester is not None:
614                                di['semester'] = semesters.index(sem) + 1
615                                for course in semester.objectValues():
616                                    course_d = course.getContent()
617                                    di['code'] = course_d.get('code',None)
618                                    di['core_or_elective'] = getattr(course_d,'core_or_elective',None)
619                                    di['code'] = di['code'] or course.id
620                                    di['review_state'] = self.portal_workflow.getInfoFor(course,'review_state','no_state')
621                                    try:
622                                        export.append(dataline % di)
623                                        logger.info('exporting %s %s ' % (certificate.id, certificate.title))
624                                    except:
625                                        logger.info('could not export %s %s ' % (certificate.id, certificate.title))
626                                        continue
627        open("%s/import/%s-%s.csv" % (i_home,name,current),"w+").write('\n'.join(export))
628        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
629    ###)
630
631
632InitializeClass(AcademicsFolder)
633
634def addAcademicsFolder(container, id, REQUEST=None, **kw):
635    """Add a AcademicsFolder."""
636    ob = AcademicsFolder(id, **kw)
637    return CPSBase_adder(container, ob, REQUEST=REQUEST)
638
639###)
640
641class Certificate(CPSDocument): ###(
642    """
643    WAeUP Certificate
644    """
645    meta_type = 'Certificate'
646    portal_type = meta_type
647    security = ClassSecurityInfo()
648
649    def __init__(self, id, **kw):
650        CPSDocument.__init__(self, id, **kw)
651
652##    security.declareProtected(View,"Title")
653##    def Title(self):
654##        """compose title"""
655##        return "Certificate of %s" % (self.title)
656
657InitializeClass(Certificate)
658
659def addCertificate(container, id, REQUEST=None, **kw):
660    """Add a Certificate."""
661    ob = Certificate(id, **kw)
662    return CPSBase_adder(container, ob, REQUEST=REQUEST)
663
664###)
665
666class StudyLevel(CPSDocument): ###(
667    """
668    WAeUP StudyLevel containing the courses and students
669    """
670    meta_type = 'StudyLevel'
671    portal_type = meta_type
672    security = ClassSecurityInfo()
673
674    security.declareProtected(View,"Title")
675    def Title(self):
676        """compose title"""
677        try:
678            return "Level %s" % self.aq_parent.getId()
679        except:
680            return "no Title for %s" % self.getId()
681
682
683InitializeClass(StudyLevel)
684
685def addStudyLevel(container, id, REQUEST=None, **kw):
686    """Add a StudyLevel."""
687    ob = StudyLevel(id, **kw)
688    return CPSBase_adder(container, ob, REQUEST=REQUEST)
689
690###)
691
692class CertificateCourse(CPSDocument): ###(
693    """
694    WAeUP CertificateCourse
695    """
696    meta_type = 'CertificateCourse'
697    portal_type = meta_type
698    security = ClassSecurityInfo()
699
700    def getCourseEntry(self,cid):
701        res = self.portal_catalog({'meta_type': "Course",
702                                           'id': cid})
703        if res:
704            return res[-1]
705        else:
706            return None
707
708    security.declareProtected(View,"Title")
709    def Title(self):
710        """compose title"""
711        ce = self.getCourseEntry(self.id.upper())
712        #print self.id, self.aq_parent.id
713        if ce:
714            return "%s" % ce.Title
715        return "No such course"
716
717    security.declareProtected(View,"credits")
718    def credits(self):
719        """credits from course"""
720        ce = self.getCourseEntry(self.id)
721        if ce:
722            return "%s" % ce.credits
723        return "0"
724
725    security.declareProtected(View,"passmark")
726    def passmark(self):
727        """passmark from course"""
728        ce = self.getCourseEntry(self.id)
729        if ce is not None and hasattr(ce,"passmark"):
730            return ce.passmark
731
732
733    security.declareProtected(View,"coursepath")
734    def coursepath(self):
735        """coursepath from course"""
736        ce = self.getCourseEntry(self.id)
737        if ce:
738            return ce.getPath()
739        return "?"
740
741
742InitializeClass(CertificateCourse)
743
744def addCertificateCourse(container, id, REQUEST=None, **kw):
745    """Add a CertificateCourse."""
746    ob = CertificateCourse(id, **kw)
747    return CPSBase_adder(container, ob, REQUEST=REQUEST)
748###)
749
750class Faculty(CPSDocument): ###(
751    """
752    WAeUP Faculty containing Departments
753    """
754    meta_type = 'Faculty'
755    portal_type = meta_type
756    security = ClassSecurityInfo()
757
758##    def __init__(self, id, **kw):
759##        CPSDocument.__init__(self, id, **kw)
760
761    security.declareProtected(View,"Title")
762    def Title(self):
763        """compose title"""
764        return "%s" % (self.title)
765
766
767    security.declareProtected(View,"LongTitle")
768    def LongTitle(self):
769        """compose long_title"""
770        prefix = getattr(self,'title_prefix',None)
771        if prefix is None:
772            prefix = getattr(self,'institution_type','faculty')
773            self.getContent().edit(mapping = {'title_prefix': prefix})
774        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Faculty of")
775        return "%s %s" % (itype,self.title)
776
777InitializeClass(Faculty)
778
779def addFaculty(container, id, REQUEST=None, **kw):
780    """Add a Faculty."""
781    ob = Faculty(id, **kw)
782    return CPSBase_adder(container, ob, REQUEST=REQUEST)
783
784###)
785
786class Department(CPSDocument): ###(
787    """
788    WAeUP Department containing the courses and students
789    """
790    meta_type = 'Department'
791    portal_type = meta_type
792    security = ClassSecurityInfo()
793
794    security.declareProtected(View,"LongTitle")
795    def LongTitle(self):
796        """compose long_title"""
797        prefix = getattr(self,'title_prefix',None)
798        if prefix is None:
799            prefix = getattr(self,'institution_type','department')
800            self.getContent().edit(mapping = {'title_prefix': prefix})
801        itype = self.portal_vocabularies.institution_types_voc.get(prefix,default="Department of")
802        return "%s %s" % (itype,self.title)
803
804InitializeClass(Department)
805
806def addDepartment(container, id, REQUEST=None, **kw):
807    """Add a Department."""
808    object = Department(id, **kw)
809    id = object.getId()
810    container._setObject(id, object)
811##    dep = getattr(container,id).getEditableContent()   #getContent()
812##    dep.invokeFactory('CoursesFolder','Courses')
813##    o = getattr(dep,'Courses')
814##    dict = {'Title': 'Courses'}
815##    o.getContent().edit(mapping=dict)
816##    dep.invokeFactory('CertificatesFolder','Certificates')
817##    o = getattr(dep,'Certificates')
818##    dict = {'Title': 'Certificates'}
819##    o.geetContent().edit(mapping=dict)
820    if REQUEST is not None:
821        url = container.absolute_url()
822        REQUEST.RESPONSE.redirect('%s/manage_main' % url)
823
824###)
825
826class Course(CPSDocument): ###(
827    """
828    WAeUP Course
829    """
830    meta_type = 'Course'
831    portal_type = meta_type
832    security = ClassSecurityInfo()
833
834    security.declareProtected(View,"Title")
835    def Title(self):
836        """compose title"""
837        return self.title
838
839InitializeClass(Course)
840
841def addCourse(container, id, REQUEST=None, **kw):
842    """Add a Course."""
843    ob = Course(id, **kw)
844    return CPSBase_adder(container, ob, REQUEST=REQUEST)
845###)
846
847
Note: See TracBrowser for help on using the repository browser.