source: WAeUP_SRP/trunk/Academics.py @ 287

Last change on this file since 287 was 287, checked in by joachim, 19 years ago

=added cps_portlets and experimental theme

  • Property svn:keywords set to Id
File size: 22.9 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 csv,re
20import logging
21import Globals
22p_home = Globals.package_home(globals())
23i_home = Globals.INSTANCE_HOME
24
25class AcademicsFolder(CPSDocument): ###(
26    """
27    WAeUP AcademicsFolder containing StudyCourses
28    """
29    meta_type = 'AcademicsFolder'
30    portal_type = meta_type
31    security = ClassSecurityInfo()
32
33##    security.declareProtected(View,"Title")
34##    def Title(self):
35##        """compose title"""
36##        return "AcademicsFolder of %s" % (self.title)
37
38    security.declareProtected(View,"loadFacultiesFromCSV")###(
39    def loadFacultiesFromCSV(self):
40        """install Universityspecific Faculies from CSV values"""
41        #return
42        name = 'faculty'
43        no_import = False
44        logger = logging.getLogger('%s_import' % name)
45        logger.info('Start loading from %s.csv' % name)
46        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
47        try:
48            faculties = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
49        except:
50            logger.error('Error reading %s.csv' % name)
51            return
52        l = self.portal_catalog({'meta_type': "Faculty"})
53        facs = {}
54        for f in l:
55            facs[f.id] = f.getObject()
56        for faculty in faculties:
57            logger.info('processing %(Session)s %(FacultyCode)s %(Description)s %(CollegeCode)s %(FacultyKey)s %(Status)s %(degree_grade)s %(Bankcode)s' % faculty)
58            fid = faculty['FacultyCode']
59            f = facs.get(fid,None)
60            if f is None:
61                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
62                logger.info('Creating Faculty with ID %(FacultyCode)s %(Description)s' % faculty)
63                academics.invokeFactory('Faculty', fid)
64                f = getattr(self,fid)
65                d = {'Title': faculty['Description']}
66                f.getContent().edit(mapping=d)
67            else:
68                if not no_import:
69                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
70                    no_import.write('"Session","FacultyCode","Description","CollegeCode","FacultyKey","Status","degree_grade","Bankcode"\n')
71                logger.info('Faculty with ID %(FacultyCode)s %(Description)s already exists' % faculty)
72                no_import.write('"%(Session)s","%(FacultyCode)s","%(Description)s","%(CollegeCode)s","%(FacultyKey)s","%(Status)s","%(degree_grade)s","%(Bankcode)s"\n' % faculty)
73    ###)
74
75    security.declareProtected(ModifyPortalContent,"yamlDumpFaculties")###(
76    def yamlDumpFaculties(self):
77        """dump Faculies to Yaml"""
78        #return
79        import yaml
80        logger = logging.getLogger('dumpfaculties')
81        logger.info('Start dumping Faculties')
82        academics = self.portal_catalog({'meta_type': 'AcademicsFolder'})[-1].getObject()
83        l = self.portal_catalog({'meta_type': "Faculty"})
84        facs = {}
85        for f in l:
86            facs[f.id] = f.getObject()
87        for fid in facs.keys():
88            faculty = facs.get(fid).aq_self
89            logger.info('dumping %s %s ' % (faculty.id, faculty.title))
90            print yaml.dump(faculty)
91           
92    ###)
93
94    security.declareProtected(ModifyPortalContent,"loadDepartmentsFromCSV")###(
95    def loadDepartmentsFromCSV(self):
96        """install Universityspecific Faculies from CSV values"""
97        #return
98        name = 'departments'
99        no_import = False
100        logger = logging.getLogger('loaddepartments')
101        try:
102            deps = csv.DictReader(open("%s/import/departments.csv" % i_home,"rb"))
103        except:
104            logger.error('Error reading departments.csv')
105            return
106        l = self.portal_catalog({'meta_type': "Faculty"})
107        facs = {}
108        for f in l:
109            facs[f.id] = f.getObject()
110        for dep in deps:
111            logger.info('Processing %(Session)s %(DeptCode)s %(Description)s %(FacultyCode)s' % dep)
112            fid = dep['FacultyCode']
113            f = facs.get(fid,None)
114            if f is None:
115                logger.info( "No Faculty with ID: %s" % fid)
116                if not no_import:
117                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
118                    no_import.write('"Session","DeptCode","Description","FacultyCode"\n')
119                no_import.write( "No Faculty with ID: %s\n" % fid)
120                no_import.write('"%(Session)s","%(DeptCode)s","%(Description)s","%(FacultyCode)s"\n' % dep)
121            else:
122                did = dep.get('DeptCode')
123                d = getattr(f,did,None)
124                if d is None or d.portal_type == "Faculty":
125                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
126                    logger.info('Creating Department %(DeptCode)s = %(Description)s' % dep)
127                    f.invokeFactory('Department', did)
128                    d = getattr(f,did)
129                dict = {'Title': dep['Description']}
130                d.getContent().edit(mapping=dict)
131    ###)
132   
133    security.declareProtected(ModifyPortalContent,"loadCoursesFromCSV")###(
134    def loadCoursesFromCSV(self):
135        """install Universityspecific Courses from CSV values"""
136        #return
137        name = 'courses'
138        no_import = False
139        logger = logging.getLogger('loadcourses')
140        try:
141            courses = csv.DictReader(open("%s/import/courses.csv" % i_home,"rb"))
142        except:
143            logger.error('Error reading courses.csv')
144            return
145        l = self.portal_catalog({'meta_type': "Faculty"})
146        facs = {}
147        for f in l:
148            facs[f.id] = f.getObject()
149        dl = self.portal_catalog({'meta_type': "Department"})
150        deps = {}
151        for d in dl:
152            deps[d.id] = d.getObject()
153        cl = self.portal_catalog({'meta_type': "Course"})
154        course_list = [ c.id for c in cl]
155        for course in courses:
156            logger.info('Processing %(CourseCode)s %(Description)s %(Credits)s %(Dept)s %(Semester)s %(Session)s %(PassMark)s %(CourseKey)s %(Category)s %(AdmStatus)s' % course)
157##            if course.get("FORMERCODE").endswith('BITS'):
158##                continue
159            depid = course.get('Dept').upper()
160            if depid in deps.keys():
161                dept= deps.get(depid)
162    ##        elif depid in facs.keys():
163    ##            dept= facs.get(depid)
164            else:
165                logger.info("Dep %(Dept)s for Course %(CourseCode)s not found" % course)
166                if not no_import:
167                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
168                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","CourseKey","Category","AdmStatus"\n')
169                no_import.write("Dep %(Dept)s for Course %(CourseCode)s not found\n" % course)
170                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(CourseKey)s","%(Category)s","%(AdmStatus)s"\n' % course)
171                continue
172            course_id = ''.join(re.split('\W+',course.get('CourseCode')))
173            if len(course_id) == 3:
174                course_id = "%s000" % course_id
175            elif course_id.startswith('CHEM'):
176                tid = course_id.replace('CHEM','CHE')
177                logger.info("invalid course_code %(course_id)s renaming to %(tid)s" % vars())
178                course_id = tid
179##            elif course_id.startswith('DAIC'):
180##                tid = course_id.replace('DAIC','DAC')
181##                logger.info("invalid course_code %(course_id)s renaming to %(tid)s" % vars())
182##                course_id = tid
183##            elif course_id.startswith('DAIM'):
184##                tid = course_id.replace('DAIM','DAM')
185##                logger.info("invalid course_code %(course_id)s renaming to %(tid)s" % vars())
186##                course_id = tid
187            elif len(course_id) != 6:
188                logger.info("invalid course_code %(CourseCode)s" % course)
189                if not no_import:
190                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
191                    no_import.write('"CourseCode","Description","Credits","Dept","Semester","Session","PassMark","CourseKey","Category","AdmStatus"')
192                no_import.write("invalid course_code %(CourseCode)s\n" % course)
193                no_import.write('"%(CourseCode)s","%(Description)s","%(Credits)s","%(Dept)s","%(Semester)s","%(Session)s","%(PassMark)s","%(CourseKey)s","%(Category)s","%(AdmStatus)s"\n' % course)
194                continue
195            c = getattr(dept,course_id,None)
196            if c is None:
197                logger.info('Creating Course %(CourseCode)s  %(Description)s in Department %(Dept)s' % course)
198                dept.invokeFactory('Course', course_id)
199                c = getattr(dept,course_id)
200            dict = {'Title': course['Description']}
201            dict['code'] = course_id
202            dict['org_code'] = course.get('CourseCode')
203            dict['credits'] = course.get('Credits')
204            dict['semester'] = course.get('Semester')
205            dict['session'] = course.get('Session')
206            dict['category'] = course.get('Category')
207            pm = course.get('PassMark')
208            if pm.find(',') > -1:
209                pm.replace(',','.')
210            elif pm == "":
211                pm = "0.0"
212            try:
213                dict['passmark'] = int(float(pm))
214            except:
215                dict['passmark'] = 0
216            c.getContent().edit(mapping=dict)
217    ###)
218
219    security.declareProtected(ModifyPortalContent,"loadCertificatesFromCSV")###(
220    def loadCertificatesFromCSV(self):
221        """install Universityspecific Certificates from CSV values"""
222        #return
223        name = 'certificates'
224        no_import = False
225        logger = logging.getLogger('loadcertificates')
226        try:
227            certificates = csv.DictReader(open("%s/import/certificates.csv" % i_home,"rb"))
228        except:
229            logger.error('Error reading certificates.csv')
230            return
231        f_ids = [f.id for f in self.portal_catalog({'meta_type': "Faculty"})]
232        #d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
233        dl = self.portal_catalog({'meta_type': "Department"})
234        deps = {}
235        for d in dl:
236            deps[d.id] = d.getObject()
237        for certificate in certificates:
238            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)
239            depid = certificate.get('Dept')
240            facid = certificate.get('Faculty')
241            if facid not in f_ids:
242                logger.info('Faculty %(Faculty)s for %(CertCode)s %(Description)s not found' % certificate)
243                if not no_import:
244                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
245                    no_import.write('"CertCode","Description","Faculty","MaxPass","MaxLoad","session","PromotionCredits","Probationcredits","StartLevel","endLevel","Nyears","Ncore","MaxElect","MPREFIX","Dept","Admstatus","category"\n')
246                no_import.write('Faculty %(Faculty)s for %(CertCode)s %(Description)s not found\n' % certificate)
247                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)
248                continue
249            if not deps.has_key(depid):
250                logger.info('Department %(Dept)s for %(CertCode)s %(Description)s not found' % certificate)
251                if not no_import:
252                    no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
253                    no_import.write('"CertCode","Description","Faculty","MaxPass","MaxLoad","session","PromotionCredits","Probationcredits","StartLevel","endLevel","Nyears","Ncore","MaxElect","MPREFIX","Dept","Admstatus","category"\n')
254                no_import.write('Department %(Dept)s for %(CertCode)s %(Description)s not found\n' % certificate)
255                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)
256                continue
257            certificate_id = "%(category)s_%(Admstatus)s_%(Dept)s" % certificate
258            dep = deps[depid]
259            c = getattr(dep,certificate_id,None)
260            if c is None:
261                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
262                logger.info('Creating certificate %(CertCode)s  %(Description)s in Department %(Dept)s' % certificate)
263                dep.invokeFactory('Certificate', certificate_id)
264                c = getattr(dep,certificate_id)
265            dict = {'Title': certificate['Description']}
266            code = certificate.get('CertCode')
267            code = code.replace('.','')
268            code = code.replace('(','')
269            code = code.replace(')','')
270            code = code.replace('/','')
271            code = code.replace(' ','')
272            code = code.replace('_','')
273            dict['code'] = code
274            dict['faculty'] = certificate.get('Faculty')
275            dict['department'] = certificate.get('Dept')
276            dict['max_pass'] = certificate.get('MaxPass')
277            dict['max_load'] = certificate.get('MaxLoad')
278            dict['admin_status'] = certificate.get('Admstatus')
279            dict['category'] = certificate.get('category')
280            dict['m_prefix'] = certificate.get('MPREFIX')
281            dict['nr_years'] = int(certificate.get('Nyears'))
282            nc = certificate.get('Ncore','1')
283            try:
284                dict['n_core'] = int(nc)
285            except:
286                dict['n_core'] = 1
287            dict['start_level'] = certificate.get('StartLevel')
288            dict['end_level'] = certificate.get('endLevel')
289            dict['promotion_credits'] = certificate.get('PromotionCredits')
290            dict['probation_credits'] = certificate.get('ProbationCredits')
291            c.getContent().edit(mapping=dict)
292    ###)
293
294    security.declareProtected(ModifyPortalContent,"loadCertificateCoursesFromCSV")###(
295    def loadCertificateCoursesFromCSV(self):
296        """install Certificate Courses from CSV values"""
297        #return
298        logger = logging.getLogger('loadcertificatecourses')
299        try:
300            cert_courses = csv.DictReader(open("%s/import/course_level_courses.csv" % i_home,"rb"))
301        except:
302            logger.error('Error reading course_level_courses.csv')
303            return
304        d_ids = [d.id for d in self.portal_catalog({'meta_type': "Department"})]
305        for cert_course in cert_courses:
306            logger.info('Processing %(CosCode)s %(CertCode)s %(CoreKey)s %(Session)s %(Level)s %(Core)s %(Elective)s %(Mandatory)s %(AdmStatus)s %(Dept)s %(Semester)s' % cert_course)
307            depid = cert_course.get('Dept')
308            code = cert_course.get('CertCode')
309            code = code.replace('.','')
310            code = code.replace('(','')
311            code = code.replace(')','')
312            code = code.replace('/','')
313            code = code.replace(' ','')
314            code = code.replace('_','')
315            if cert_course.get('Session') != '2002/2003':
316                continue
317            certificate = self.portal_catalog({'meta_type': "Certificate",
318                                               'SearchableText': code})
319            if not certificate:
320                print code
321                logger.info('CertCode %(CertCode)s for %(CosCode)s not found' % cert_course)
322                continue
323            certificate = certificate[-1].getObject()
324            certificate_code = certificate.getId()
325            if depid not in d_ids:
326                logger.info('Department %(Dept)s for %(CertCode)s not found' % cert_course)
327                continue
328            course_code = cert_course.get('CosCode')
329            level = cert_course.get('Level')
330            l = getattr(certificate,level,None)
331            if l is None:
332                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
333                logger.info('Creating Level %(Level)s in certificate %(CertCode)s' % cert_course)
334                certificate.invokeFactory('StudyLevel', level)
335                l = getattr(certificate, level)
336                l.invokeFactory('Semester','first')
337                l.invokeFactory('Semester','second')
338            first_s = getattr(l,'first')
339            second_s = getattr(l,'second')
340            if cert_course.get('Semester') == '1':
341                semester = first_s
342            else:
343                semester = second_s
344            if hasattr(semester,course_code):
345                logger.info('Duplicate %(CosCode)s in Level %(Level)s' % cert_course)
346                continue
347               
348            semester.invokeFactory('CertificateCourse',course_code)
349            cc = getattr(semester,course_code)
350            dict = {}
351            dict['code'] = cert_course.get('CosCode')
352            dict['certificate_code'] = code
353            dict['certificate_code_org'] = cert_course.get('CertCode')
354            dict['department'] = cert_course.get('Dept')
355            dict['admin_status'] = cert_course.get('Admstatus')
356            dict['session'] = cert_course.get('Session')
357            if cert_course.get('Core') != '':
358                dict['core_or_elective'] = True
359            else:
360                dict['core_or_elective'] = False
361            dict['level'] = cert_course.get('Level')
362            cc.getContent().edit(mapping=dict)
363    ###)
364
365InitializeClass(AcademicsFolder)
366
367def addAcademicsFolder(container, id, REQUEST=None, **kw):
368    """Add a AcademicsFolder."""
369    ob = AcademicsFolder(id, **kw)
370    return CPSBase_adder(container, ob, REQUEST=REQUEST)
371
372###)
373
374class Certificate(CPSDocument): ###(
375    """
376    WAeUP Certificate
377    """
378    meta_type = 'Certificate'
379    portal_type = meta_type
380    security = ClassSecurityInfo()
381   
382    def __init__(self, id, **kw):
383        CPSDocument.__init__(self, id, **kw)
384
385##    security.declareProtected(View,"Title")
386##    def Title(self):
387##        """compose title"""
388##        return "Certificate of %s" % (self.title)
389
390InitializeClass(Certificate)
391
392def addCertificate(container, id, REQUEST=None, **kw):
393    """Add a Certificate."""
394    ob = Certificate(id, **kw)
395    return CPSBase_adder(container, ob, REQUEST=REQUEST)
396
397###)
398
399class CertificateCourse(CPSDocument): ###(
400    """
401    WAeUP CertificateCourse 
402    """
403    meta_type = 'CertificateCourse'
404    portal_type = meta_type
405    security = ClassSecurityInfo()
406   
407    def getCourseEntry(self,cid):
408        res = self.portal_catalog({'meta_type': "Course",
409                                           'id': cid})
410        if res:
411            return res[-1] 
412        else:
413            return None
414       
415    security.declareProtected(View,"Title")
416    def Title(self):
417        """compose title"""
418        ce = self.getCourseEntry(self.id)
419        if ce:
420            return "%s" % ce.Title
421        return "No such course"
422
423    security.declareProtected(View,"credits")
424    def credits(self):
425        """credits from course"""
426        ce = self.getCourseEntry(self.id)
427        if ce:
428            return "%s" % ce.credits
429        return "0"
430   
431    security.declareProtected(View,"passmark")
432    def passmark(self):
433        """passmark from course"""
434        ce = self.getCourseEntry(self.id)
435        if ce:
436            return "%s" % ce.passmark.split(',')[0]
437        return "0"
438
439    security.declareProtected(View,"coursepath")
440    def coursepath(self):
441        """coursepath from course"""
442        ce = self.getCourseEntry(self.id)
443        if ce:
444            return ce.getPath()
445        return "?"
446   
447
448InitializeClass(CertificateCourse)
449
450def addCertificateCourse(container, id, REQUEST=None, **kw):
451    """Add a CertificateCourse."""
452    ob = CertificateCourse(id, **kw)
453    return CPSBase_adder(container, ob, REQUEST=REQUEST)
454###)
455
456class Faculty(CPSDocument): ###(
457    """
458    WAeUP Faculty containing Departments
459    """
460    meta_type = 'Faculty'
461    portal_type = meta_type
462    security = ClassSecurityInfo()
463   
464##    def __init__(self, id, **kw):
465##        CPSDocument.__init__(self, id, **kw)
466
467    security.declareProtected(View,"Title")
468    def Title(self):
469        """compose title"""
470        return "%s" % (self.title)
471
472InitializeClass(Faculty)
473
474def addFaculty(container, id, REQUEST=None, **kw):
475    """Add a Faculty."""
476    ob = Faculty(id, **kw)
477    return CPSBase_adder(container, ob, REQUEST=REQUEST)
478
479###)
480
481class Department(CPSDocument): ###(
482    """
483    WAeUP Department containing the courses and students
484    """
485    meta_type = 'Department'
486    portal_type = meta_type
487    security = ClassSecurityInfo()
488
489##    security.declareProtected(View,"Title")
490##    def Title(self):
491##        """compose title"""
492##        reg_nr = self.getId()[1:]
493##        return "Department of %s" % (self.title)
494
495InitializeClass(Department)
496
497def addDepartment(container, id, REQUEST=None, **kw):
498    """Add a Department."""
499    ob = Department(id, **kw)
500    return CPSBase_adder(container, ob, REQUEST=REQUEST)
501###)
502
503class Course(CPSDocument): ###(
504    """
505    WAeUP Course 
506    """
507    meta_type = 'Course'
508    portal_type = meta_type
509    security = ClassSecurityInfo()
510
511    security.declareProtected(View,"Title")
512    def Title(self):
513        """compose title"""
514        return self.title
515   
516InitializeClass(Course)
517
518def addCourse(container, id, REQUEST=None, **kw):
519    """Add a Course."""
520    ob = Course(id, **kw)
521    return CPSBase_adder(container, ob, REQUEST=REQUEST)
522###)
523
524class CourseTicket(CPSDocument): ###(
525    """
526    WAeUP CourseTicket 
527    """
528    meta_type = 'CourseTicket'
529    portal_type = meta_type
530    security = ClassSecurityInfo()
531   
532InitializeClass(CourseTicket)
533
534def addCourseTicket(container, id, REQUEST=None, **kw):
535    """Add a CourseTicket."""
536    ob = CourseTicket(id, **kw)
537    return CPSBase_adder(container, ob, REQUEST=REQUEST)
538###)
539
Note: See TracBrowser for help on using the repository browser.