source: WAeUP_SRP/trunk/Academics.py @ 280

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

=renamed skins/waeup_faculty to academics

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