source: WAeUP_SRP/trunk/Students.py @ 441

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

create empty student_admission object during import

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