source: WAeUP_SRP/trunk/Students.py @ 447

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

removed old actions from Student.xml

  • Property svn:keywords set to Id
File size: 20.5 KB
RevLine 
[57]1#-*- mode: python; mode: fold -*-
[200]2# $Id: Students.py 446 2006-08-29 17:43:05Z joachim $
[45]3from Globals import InitializeClass
4from AccessControl import ClassSecurityInfo
[164]5from AccessControl.SecurityManagement import newSecurityManager
[429]6from zExceptions import BadRequest
[47]7from Products.CMFCore.utils import UniqueObject, getToolByName
[45]8from Products.CMFCore.permissions import View
9from Products.CMFCore.permissions import ModifyPortalContent
[154]10from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
11#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
12from Products.CPSDocument.CPSDocument import CPSDocument
13from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
[164]14from Products.CPSCore.CPSMembershipTool import CPSUnrestrictedUser
[361]15from Products.WAeUP_SRP.Academics import makeCertificateCode
[362]16import logging
17import csv,re
18import Globals
19p_home = Globals.package_home(globals())
20i_home = Globals.INSTANCE_HOME
[398]21MAX_TRANS = 1000
[154]22
[422]23def generateStudentId():
24    import random
[423]25    r = random
26    return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
[422]27
[361]28class StudentsFolder(CPSDocument): ###(
29    """
30    WAeUP container for the various WAeUP containers data
31    """
[362]32    meta_type = 'StudentsFolder'
[361]33    portal_type = meta_type
34    security = ClassSecurityInfo()
[154]35
[361]36    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsFromCSV")###(
37    def loadFullTimeStudentsFromCSV(self):
38        """load Fulltime Studentdata from CSV values"""
39        #return
[398]40        import transaction
41        tr_count = 0
[361]42        name = 'short_full_time'
43        no_import = False
[395]44        if not no_import:
45            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
46            no_import.write('"MatricNo","EntryRegNo","CurrentSession","StudentLevel","fullname","FirstName","MiddleName","Lastname","FormerSurname","Sex","Nationality","State","LGA","PermanentAddress","PermanentAddressCity","CampusAddress","PhoneNumber","Emailaddress","Mode","CourseMajor","Faculty","Dept"\n')
[361]47        logger = logging.getLogger('%s_import' % name)
48        logger.info('Start loading from %s.csv' % name)
49        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
50        try:
51            students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
52        except:
53            logger.error('Error reading %s.csv' % name)
54            return
[422]55        l = self.portal_catalog({'meta_type': "StudentClearance",})
56        matrics = []
[361]57        for s in l:
[422]58            matrics.append(s.getObject().getContent().matric_no)
[423]59        print matrics
[361]60        l = self.portal_catalog({'meta_type': "Certificate"})
61        certs = {}
62        for c in l:
[362]63            certs[c.id] = c.getObject()
[361]64        for student in students:
[393]65            logger.info('processing "%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
[361]66            sid = student.get('MatricNo')
[396]67            if sid == "":
68                em = 'Empty MatricNo\n'
69                logger.info(em)
70                no_import.write(em)
71                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
72                continue
[361]73            certcode = makeCertificateCode(student.get('CourseMajor'))
74            if certcode not in certs.keys():
[393]75                em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
[361]76                logger.info(em)
[393]77                no_import.write(em)
78                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
[361]79                continue
[395]80            level = student.get('StudentLevel')
[426]81            try:
[395]82                int(level)
83            except:
84                em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
85                logger.info(em)
86                no_import.write(em)
87                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
88                continue
[422]89            matric_no = student.get('MatricNo')
90            if matric_no not in matrics:
91                matrics.append(matric_no)
92                sid = generateStudentId()
[361]93                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
[426]94                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
[429]95                not_created = True
96                while not_created:
97                    try:
98                        students_folder.invokeFactory('Student', sid)
99                        not_created = False
100                    except BadRequest:
101                        sid = generateStudentId()
102                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
[361]103                s = getattr(self,sid)
[441]104                s.invokeFactory('StudentAdmission','admission')
[446]105                da = {'Title': 'Admission Data'}
[361]106                s.invokeFactory('StudentPersonal','personal')
[446]107                da['jamb_reg_no'] = student.get('EntryRegNo')
[362]108                sp = s.personal
[361]109                d = {'Title': 'Personal Data'}
[422]110                s.invokeFactory('StudentClearance','clearance')
[427]111                sc = s.clearance
[422]112                dc = {'Title': 'Clearance Data'}
113                dc['matric_no'] = matric_no
[427]114                lga = student.get('State') + ' / ' + student.get('LGA')               
115                dc['lga'] = lga
[422]116                dc['nationality'] = student.get('Nationality')
117                dc['email'] = student.get('Emailaddress')
[361]118                d['firstname'] = student.get('FirstName')
119                d['middlename'] = student.get('MiddleName')
[362]120                d['lastname'] = student.get('Lastname')
[361]121                d['former_surname'] = student.get('FormerSurname')
[362]122                d['sex'] = student.get('Sex') == 'F'
[422]123                d['perm_address'] = student.get('PermanentAddress')
124                d['perm_city'] = student.get('PermanentAddressCity')
[361]125                d['campus_address'] = student.get('CampusAddress')
126                d['phone'] = student.get('PhoneNumber')
[446]127                s.admission.getContent().edit(mapping=da)
[362]128                sp.getContent().edit(mapping=d)
[422]129                sc.getContent().edit(mapping=dc)
[362]130                #
131                # Study Course
132                #
133                s.invokeFactory('StudentStudyCourse','study_course')
134                sc = s.study_course
135                d = {}
[422]136                #d['matricel_no'] = student.get('MatricNo')
137                #d['entry_reg_no'] = student.get('EntryRegNo')
138                #d['faculty'] = student.get('Faculty')
139                #d['department'] = student.get('Dept')
[362]140                d['course_major'] = certcode
141                css = student.get('CurrentSession') or '2004-2005'
142                cs = int(css.split('-')[0]) - 2000
143                cl = int(student.get('StudentLevel'))/100
144                d['entry_session'] = "200%s" % (cs - cl)
145                sc.getContent().edit(mapping=d)
[364]146                #
147                # Level
148                #
149                l = getattr(sc,level,None)
150                if l is None:
151                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
152                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
153                    sc.invokeFactory('StudyLevel', level)
154                    l = getattr(sc, level)
155                    certificate = certs[certcode]
156                    cert_level = getattr(certificate,level,None)
157                    if cert_level is None:
158                        logger.info('Level %(level)s not in %(certcode)s' % vars())
159                    l.getContent().edit(mapping={'Title': "Level %s" % level})
160                    l.invokeFactory('Semester','first')
161                    l.invokeFactory('Semester','second')
162                    first_s = getattr(l,'first')
163                    first_s.getContent().edit(mapping={'Title': 'First Semester'})
164                    second_s = getattr(l,'second')
165                    second_s.getContent().edit(mapping={'Title': 'Second Semester'})
[361]166            else:
[393]167                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
[361]168                logger.info(em)
[393]169                no_import.write(em)
170                no_import.write('"%(MatricNo)s","%(EntryRegNo)s","%(CurrentSession)s","%(StudentLevel)s","%(fullname)s","%(FirstName)s","%(MiddleName)s","%(Lastname)s","%(FormerSurname)s","%(Sex)s","%(Nationality)s","%(State)s","%(LGA)s","%(PermanentAddress)s","%(PermanentAddressCity)s","%(CampusAddress)s","%(PhoneNumber)s","%(Emailaddress)s","%(Mode)s","%(CourseMajor)s","%(Faculty)s","%(Dept)s"\n' % student)
[398]171            if tr_count > MAX_TRANS:
[422]172                transaction.commit()
173                em = 'Transaction commited\n' % student
[398]174                logger.info(em)
175                tr_count = 0
176            tr_count += 1
[423]177        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
[393]178        return self.students.academics_contents()
[361]179    ###)
[382]180
[398]181    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
[396]182    def loadFullTimeStudentsResultsFromCSV(self):
183        """load Fulltime Studentdata from CSV values"""
184        #return
[398]185        import transaction
186        tr_count = 0
187        name = 'short_full_time_results_2004_2005'
[396]188        no_import = False
189        if not no_import:
190            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
191            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
192        logger = logging.getLogger('%s_import' % name)
193        logger.info('Start loading from %s.csv' % name)
194        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
195        try:
196            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
197        except:
198            logger.error('Error reading %s.csv' % name)
199            return
200        l = self.portal_catalog({'meta_type': "Student"})
201        students = {}
202        for s in l:
203            students[s.id] = s.getObject()
[398]204        l = self.portal_catalog({'meta_type': "Course"})
205        courses = {}
206        for c in l:
207            courses[c.id] = c.getObject()
[396]208        for result in results:
209            sid = result.get('Matnumber')
[426]210            if sid not in students.keys():
[398]211                em = 'Student with ID %(Matnumber)s not found\n' % result
[396]212                logger.info(em)
213                no_import.write(em)
[398]214                no_import.write('"%(Matnumber)s","%(CosCode)s","%(Ansbook)s","%(CosStuatus)s","%(Session)s","%(Mat_Cos)s","%(Score)s","%(CarryLevel)s","%(Grade)s","%(Weight)s","%(Semster)s","%(Verdict)s","%(Level)s","%(id)s","%(GPA)s"\n' % result)
[396]215                continue
[398]216            course = result.get('CosCode')
217            if course not in courses.keys():
218                em = 'Course with ID %(CosCode)s not found\n' % result
[396]219                logger.info(em)
220                no_import.write(em)
[398]221                no_import.write('"%(Matnumber)s","%(CosCode)s","%(Ansbook)s","%(CosStuatus)s","%(Session)s","%(Mat_Cos)s","%(Score)s","%(CarryLevel)s","%(Grade)s","%(Weight)s","%(Semster)s","%(Verdict)s","%(Level)s","%(id)s","%(GPA)s"\n' % result)
[396]222                continue
[398]223            level = result.get('Level')
[426]224            try:
[396]225                int(level)
226            except:
[398]227                em = 'Result for result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
[396]228                logger.info(em)
229                no_import.write(em)
[398]230                no_import.write('"%(Matnumber)s","%(CosCode)s","%(Ansbook)s","%(CosStuatus)s","%(Session)s","%(Mat_Cos)s","%(Score)s","%(CarryLevel)s","%(Grade)s","%(Weight)s","%(Semster)s","%(Verdict)s","%(Level)s","%(id)s","%(GPA)s"\n' % result)
[396]231                continue
232            sf = students.get(sid)
233            sc = getattr(sf,'study_course')
234            l = getattr(sc,level,None)
235            if l is None:
236                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
[398]237                logger.info('Creating Level %(Level)s for %(Matnumber)s' % result)
[396]238                sc.invokeFactory('StudyLevel', level)
239                l = getattr(sc, level)
240                l.getContent().edit(mapping={'Title': "Level %s" % level})
241                l.invokeFactory('Semester','first')
242                l.invokeFactory('Semester','second')
243                first_s = getattr(l,'first')
244                first_s.getContent().edit(mapping={'Title': 'First Semester'})
245                second_s = getattr(l,'second')
246                second_s.getContent().edit(mapping={'Title': 'Second Semester'})
[398]247            snr = result.get('Semester')
[396]248            semester = getattr(l,'first')
[398]249            if snr == "2":
[396]250                semester = getattr(l,'second')
[398]251            logger.info('Creating CourseTicket %(CourseTicket)s in Level %(Level)s for %(Matnumber)s' % result)
252            semester.invokeFactory('CourseTicket',course)
253            ct = getattr(semester,course)
254            d = {}
255            d['ansbook'] = result.get('Ansbook')
256            d['status'] = result.get('CosStuatus')
257            d['score'] = result.get('Score')
258            d['carry_level'] = result.get('CarryLevel')
259            d['grade'] = result.get('Grade')
260            d['weight'] = result.get('Weight')
261            d['verdict'] = result.get('Verdict')
262            d['import_id'] = result.get('id')
263            gpa = result.get('GPA').replace(',','.')
[426]264            d['gpa'] = float(gpa)
[398]265            ct.getContent().edit(mapping = d)
266            if tr_count > MAX_TRANS:
267                transaction.commit()
268                tr_count = 0
269            tr_count += 1
270        return self.students.academics_contents()
[426]271
[398]272###)
[396]273
[426]274
[364]275    security.declareProtected(View,"Title")
276    def Title(self):
277        """compose title"""
[382]278        return "Student Section"
[361]279
280InitializeClass(StudentsFolder)
281
282def addStudentsFolder(container, id, REQUEST=None, **kw):
283    """Add a Student."""
284    ob = StudentsFolder(id, **kw)
285    return CPSBase_adder(container, ob, REQUEST=REQUEST)
286###)
287
[57]288class Student(CPSDocument): ###(
289    """
[154]290    WAeUP Student container for the various student data
[57]291    """
292    meta_type = 'Student'
293    portal_type = meta_type
294    security = ClassSecurityInfo()
[154]295
[152]296    security.declareProtected(View,"Title")
297    def Title(self):
298        """compose title"""
[153]299        reg_nr = self.getId()[1:]
[362]300        data = getattr(self,'personal',None)
[152]301        if data:
302            content = data.getContent()
303            return "%s %s" % (content.firstname,content.lastname)
304        return self.title
[154]305
306
[57]307InitializeClass(Student)
308
309def addStudent(container, id, REQUEST=None, **kw):
310    """Add a Student."""
311    ob = Student(id, **kw)
312    return CPSBase_adder(container, ob, REQUEST=REQUEST)
313
314###)
[91]315
[89]316class StudentPersonal(CPSDocument): ###(
317    """
[154]318    WAeUP Student container for the various student data
[89]319    """
320    meta_type = 'StudentPersonal'
321    portal_type = meta_type
322    security = ClassSecurityInfo()
[152]323
324    security.declareProtected(View,"Title")
325    def Title(self):
326        """compose title"""
327        content = self.getContent()
[364]328        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
329        return "Personal Data"
[152]330
[154]331
[89]332InitializeClass(StudentPersonal)
333
334def addStudentPersonal(container, id, REQUEST=None, **kw):
335    """Add a Students personal data."""
336    ob = StudentPersonal(id, **kw)
337    return CPSBase_adder(container, ob, REQUEST=REQUEST)
338
339###)
340
[423]341class StudentClearance(CPSDocument): ###(
342    """
343    WAeUP Student container for the various student data
344    """
345    meta_type = 'StudentClearance'
346    portal_type = meta_type
347    security = ClassSecurityInfo()
348
349    security.declareProtected(View,"Title")
350    def Title(self):
351        """compose title"""
352        content = self.getContent()
353        #return "Clearance Data for %s %s" % (content.firstname,content.lastname)
354        return "Clearance Data"
355
356
357InitializeClass(StudentClearance)
358
359def addStudentClearance(container, id, REQUEST=None, **kw):
360    """Add a Students personal data."""
361    ob = StudentClearance(id, **kw)
362    return CPSBase_adder(container, ob, REQUEST=REQUEST)
363
364###)
365
[362]366class StudentStudyCourse(CPSDocument): ###(
367    """
368    WAeUP Student container for the various student data
369    """
370    meta_type = 'StudentStudyCourse'
371    portal_type = meta_type
372    security = ClassSecurityInfo()
373
[364]374    security.declareProtected(View,"Title")
375    def Title(self):
376        """compose title"""
377        content = self.getContent()
[382]378        return "Course Major"
[362]379
380
381InitializeClass(StudentStudyCourse)
382
383def addStudentStudyCourse(container, id, REQUEST=None, **kw):
384    """Add a Students personal data."""
385    ob = StudentStudyCourse(id, **kw)
386    return CPSBase_adder(container, ob, REQUEST=REQUEST)
387
388###)
389
[423]390class StudentAdmission(CPSDocument): ###(
[179]391    """
392    WAeUP Student container for the various student data
393    """
[423]394    meta_type = 'StudentAdmission'
[179]395    portal_type = meta_type
396    security = ClassSecurityInfo()
397
[181]398    security.declareProtected(View,"Title")
399    def Title(self):
400        """compose title"""
[423]401        return "Admission Data"
[179]402
[181]403
[423]404InitializeClass(StudentAdmission)
[179]405
[423]406def addStudentAdmission(container, id, REQUEST=None, **kw):
[179]407    """Add a Students eligibility data."""
[423]408    ob = StudentAdmission(id, **kw)
[179]409    return CPSBase_adder(container, ob, REQUEST=REQUEST)
410
411###)
[181]412
[440]413class StudyLevel(CPSDocument): ###(
[166]414    """
[440]415    WAeUP StudyLevel containing the courses and students
[166]416    """
[440]417    meta_type = 'StudyLevel'
[166]418    portal_type = meta_type
419    security = ClassSecurityInfo()
420
421    security.declareProtected(View,"Title")
422    def Title(self):
423        """compose title"""
[440]424        return "Level %s" % self.aq_parent.getId()
425   
[166]426
[440]427InitializeClass(StudyLevel)
[166]428
[440]429def addStudyLevel(container, id, REQUEST=None, **kw):
430    """Add a StudyLevel."""
431    ob = StudyLevel(id, **kw)
[166]432    return CPSBase_adder(container, ob, REQUEST=REQUEST)
433
434###)
435
[440]436class Semester(CPSDocument): ###(
[89]437    """
[440]438    WAeUP Semester containing the courses and students
[89]439    """
[440]440    meta_type = 'Semester'
[89]441    portal_type = meta_type
442    security = ClassSecurityInfo()
[154]443
[440]444InitializeClass(Semester)
[152]445
[440]446def addSemester(container, id, REQUEST=None, **kw):
447    """Add a Semester."""
448    ob = Semester(id, **kw)
[89]449    return CPSBase_adder(container, ob, REQUEST=REQUEST)
450
[139]451###)
452
[440]453class ScratchCardBatchesFolder(CPSDocument): ###(
[139]454    """
[440]455    WAeUP Student container for the various student data
[139]456    """
[440]457    meta_type = 'ScratchCardBatchesFolder'
[139]458    portal_type = meta_type
459    security = ClassSecurityInfo()
[154]460
[440]461    security.declareProtected(View,"Title")
462    def Title(self):
463        """compose title"""
464        return "Pin Batches"
[139]465
[440]466
467InitializeClass(ScratchCardBatchesFolder)
468
469def addScratchCardBatchesFolder(container, id, REQUEST=None, **kw):
470    """Add a Students personal data."""
471    ob = ScratchCardBatchesFolder(id, **kw)
[139]472    return CPSBase_adder(container, ob, REQUEST=REQUEST)
473
474###)
475
[440]476from Products.WAeUP_SRP.WAeUPTables import PinTable
477
478class ScratchCardBatch(CPSDocument): ###(
[139]479    """
[440]480    WAeUP Student container for the various student data
[139]481    """
[440]482    meta_type = 'ScratchCardBatch'
[139]483    portal_type = meta_type
484    security = ClassSecurityInfo()
[154]485
[440]486    security.declareProtected(View,"Title")
487    def Title(self):
488        """compose title"""
489        doc = self.getContent()
490        return "Pin Batch %s BatchNo %d" % (doc.prefix, doc.batch_no)
[139]491
[440]492
493InitializeClass(ScratchCardBatch)
494
495def addScratchCardBatch(container, id, REQUEST=None, **kw):
496    """Add a Students personal data."""
497    ob = ScratchCardBatch(id, **kw)
[139]498    return CPSBase_adder(container, ob, REQUEST=REQUEST)
[200]499
[139]500###)
Note: See TracBrowser for help on using the repository browser.