source: WAeUP_SRP/trunk/Students.py @ 397

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

empty MatricelNo? no caught.

  • Property svn:keywords set to Id
File size: 20.4 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 396 2006-08-20 15:39:15Z joachim $
3from Globals import InitializeClass
4from AccessControl import ClassSecurityInfo
5from AccessControl.SecurityManagement import newSecurityManager
6
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
21
22class StudentsFolder(CPSDocument): ###(
23    """
24    WAeUP container for the various WAeUP containers data
25    """
26    meta_type = 'StudentsFolder'
27    portal_type = meta_type
28    security = ClassSecurityInfo()
29
30    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsFromCSV")###(
31    def loadFullTimeStudentsFromCSV(self):
32        """load Fulltime Studentdata from CSV values"""
33        #return
34        name = 'short_full_time'
35        no_import = False
36        if not no_import:
37            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
38            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')
39        logger = logging.getLogger('%s_import' % name)
40        logger.info('Start loading from %s.csv' % name)
41        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
42        try:
43            students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
44        except:
45            logger.error('Error reading %s.csv' % name)
46            return
47        l = self.portal_catalog({'meta_type': "Student"})
48        studs = {}
49        for s in l:
50            studs[s.id] = s.getObject()
51        l = self.portal_catalog({'meta_type': "Certificate"})
52        certs = {}
53        students_added = []
54        for c in l:
55            certs[c.id] = c.getObject()
56        for student in students:
57            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)
58            sid = student.get('MatricNo')
59            if sid == "":
60                em = 'Empty MatricNo\n'
61                logger.info(em)
62                no_import.write(em)
63                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)
64                continue
65            certcode = makeCertificateCode(student.get('CourseMajor'))
66            if sid in students_added:
67                em = 'Student with ID %(MatricNo)s %(fullname)s already exists in this import\n' % student
68                logger.info(em)
69                no_import.write(em)
70                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)
71                continue
72            s = studs.get(sid,None)
73            if certcode not in certs.keys():
74                em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
75                logger.info(em)
76                no_import.write(em)
77                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)
78                continue
79            level = student.get('StudentLevel')
80            try:
81                int(level)
82            except:
83                em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
84                logger.info(em)
85                no_import.write(em)
86                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)
87                continue
88            if s is None:
89                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
90                logger.info('Creating Student with ID %(MatricNo)s %(fullname)s' % student)
91                students_folder.invokeFactory('Student', sid)
92                s = getattr(self,sid)
93                students_added.append(sid)
94                s.invokeFactory('StudentPersonal','personal')
95                sp = s.personal
96                d = {'Title': 'Personal Data'}
97                d['matricel_no'] = student.get('MatricNo')
98                d['entry_reg_no'] = student.get('EntryRegNo')
99                d['fullname'] = student.get('fullname')
100                d['firstname'] = student.get('FirstName')
101                d['middlename'] = student.get('MiddleName')
102                d['lastname'] = student.get('Lastname')
103                d['former_surname'] = student.get('FormerSurname')
104                d['sex'] = student.get('Sex') == 'F'
105                d['nationality'] = student.get('Nationality')
106                d['state'] = student.get('State')
107                d['lga'] = student.get('LGA')
108                d['street'] = student.get('PermanentAddress')
109                d['city'] = student.get('PermanentAddressCity')
110                d['campus_address'] = student.get('CampusAddress')
111                d['phone'] = student.get('PhoneNumber')
112                d['email'] = student.get('Emailaddress')
113                sp.getContent().edit(mapping=d)
114                #
115                # Study Course
116                #
117                s.invokeFactory('StudentStudyCourse','study_course')
118                sc = s.study_course
119                d = {}
120                d['matricel_no'] = student.get('MatricNo')
121                d['entry_reg_no'] = student.get('EntryRegNo')
122                d['faculty'] = student.get('Faculty')
123                d['department'] = student.get('Dept')
124                d['course_major'] = certcode
125                css = student.get('CurrentSession') or '2004-2005'
126                cs = int(css.split('-')[0]) - 2000
127                cl = int(student.get('StudentLevel'))/100
128                d['entry_session'] = "200%s" % (cs - cl)
129                sc.getContent().edit(mapping=d)
130                #
131                # Level
132                #
133                l = getattr(sc,level,None)
134                if l is None:
135                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
136                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
137                    sc.invokeFactory('StudyLevel', level)
138                    l = getattr(sc, level)
139                    certificate = certs[certcode]
140                    cert_level = getattr(certificate,level,None)
141                    if cert_level is None:
142                        logger.info('Level %(level)s not in %(certcode)s' % vars())
143                    l.getContent().edit(mapping={'Title': "Level %s" % level})
144                    l.invokeFactory('Semester','first')
145                    l.invokeFactory('Semester','second')
146                    first_s = getattr(l,'first')
147                    first_s.getContent().edit(mapping={'Title': 'First Semester'})
148                    second_s = getattr(l,'second')
149                    second_s.getContent().edit(mapping={'Title': 'Second Semester'})
150            else:
151                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
152                logger.info(em)
153                no_import.write(em)
154                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)
155        return self.students.academics_contents()
156    ###)
157
158    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV")
159    def loadFullTimeStudentsResultsFromCSV(self):
160        """load Fulltime Studentdata from CSV values"""
161        #return
162        name = 'short_full_time_results_2004_2005.csv'
163        no_import = False
164        if not no_import:
165            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
166            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
167        logger = logging.getLogger('%s_import' % name)
168        logger.info('Start loading from %s.csv' % name)
169        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
170        try:
171            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
172        except:
173            logger.error('Error reading %s.csv' % name)
174            return
175        l = self.portal_catalog({'meta_type': "Student"})
176        students = {}
177        for s in l:
178            students[s.id] = s.getObject()
179        courses = self.portal_catalog({'meta_type': "Course"})
180        for result in results:
181            sid = result.get('Matnumber')
182            if sid not in students.keys():               
183                em = 'Student with ID %(Matnumber)s not found\n' % student
184                logger.info(em)
185                no_import.write(em)
186                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' % student)
187                continue
188            if student.get('CosCode') not in courses:
189                em = 'Course with ID %(CosCode)s not found\n' % student
190                logger.info(em)
191                no_import.write(em)
192                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' % student)
193                continue
194            level = student.get('Level')
195            try:
196                int(level)
197            except:
198                em = 'Result for Student with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % student
199                logger.info(em)
200                no_import.write(em)
201                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' % student)
202                continue
203            sf = students.get(sid)
204            sc = getattr(sf,'study_course')
205            l = getattr(sc,level,None)
206            if l is None:
207                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
208                logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
209                sc.invokeFactory('StudyLevel', level)
210                l = getattr(sc, level)
211                l.getContent().edit(mapping={'Title': "Level %s" % level})
212                l.invokeFactory('Semester','first')
213                l.invokeFactory('Semester','second')
214                first_s = getattr(l,'first')
215                first_s.getContent().edit(mapping={'Title': 'First Semester'})
216                second_s = getattr(l,'second')
217                second_s.getContent().edit(mapping={'Title': 'Second Semester'})
218            snr = student.get('Semester')
219            semester = getattr(l,'first')
220            if snr == "1":
221                semester = getattr(l,'second')
222           
223               
224               
225
226    security.declareProtected(View,"Title")
227    def Title(self):
228        """compose title"""
229        return "Student Section"
230
231InitializeClass(StudentsFolder)
232
233def addStudentsFolder(container, id, REQUEST=None, **kw):
234    """Add a Student."""
235    ob = StudentsFolder(id, **kw)
236    return CPSBase_adder(container, ob, REQUEST=REQUEST)
237###)
238
239class Student(CPSDocument): ###(
240    """
241    WAeUP Student container for the various student data
242    """
243    meta_type = 'Student'
244    portal_type = meta_type
245    security = ClassSecurityInfo()
246
247    security.declareProtected(View,"Title")
248    def Title(self):
249        """compose title"""
250        reg_nr = self.getId()[1:]
251        data = getattr(self,'personal',None)
252        if data is None:
253            data = getattr(self,'jamb',None)
254        if data:
255            content = data.getContent()
256            return "%s %s" % (content.firstname,content.lastname)
257        return self.title
258
259    def Description(self):
260        """compose description"""
261        data = getattr(self,'PERSONAL',None)
262        if data is None:
263            return "none"
264        if data:
265            content = data.getContent()
266            return "%s" % (content.description)
267        return self.description
268
269    security.declareProtected(View,"setScratchCardData")
270    def setScratchCardData(self,ident,ds):
271        """set this data """
272        dict = {'%s_sc_pin' % ident : ds.get('sc_pin'),
273                '%s_sc_id' % ident : ds.get('sc_id'),
274                '%s_sc_value' % ident : ds.get('sc_value'),
275                '%s_date' % ident : ds.get('sc_date'),
276                }
277
278        old_user = self.portal_membership.getAuthenticatedMember()
279        if self.portal_membership.isAnonymousUser():
280            tmp_user = CPSUnrestrictedUser('s%(jamb_id)s' % ds, '',
281                                       ['StudentManager'], '')
282            tmp_user = tmp_user.__of__(self.acl_users)
283            newSecurityManager(None, tmp_user)
284        #print str(dict)
285        self.edit(mapping=dict)
286        newSecurityManager(None, old_user)
287
288    security.declareProtected(View,"memberIsOwner")
289    def memberIsOwner(self):
290        """is the current user the owner"""
291        member = self.portal_membership.getAuthenticatedMember()
292        #print member, self.getId(),self.aq_parent.getId()
293        if self.aq_parent.getId() == str(member):
294            return True
295        return False
296
297    security.declareProtected(View,"accommodationIsBooked")
298    def accommodationIsBooked(self):
299        """is the accommodation booked"""
300        if self.accommodation_sc_pin != '':
301            return True
302        return False
303
304    security.declareProtected(View,"accommodationIsPayed")
305    def accommodationIsPayed(self):
306        """is the accommodation payed"""
307        if self.hostel_fee_sc_pin != '':
308            return True
309        return False
310
311    security.declareProtected(View,"isRegisteredForCurrentLevel")
312    def isRegisteredForCurrentLevel(self):
313        """is the student registered for the current level"""
314        for l in  self.aq_parent.objectValues():
315            if l.portal_type == 'StudyLevel':
316                return True
317        return False
318
319InitializeClass(Student)
320
321def addStudent(container, id, REQUEST=None, **kw):
322    """Add a Student."""
323    ob = Student(id, **kw)
324    return CPSBase_adder(container, ob, REQUEST=REQUEST)
325
326###)
327
328class StudentPersonal(CPSDocument): ###(
329    """
330    WAeUP Student container for the various student data
331    """
332    meta_type = 'StudentPersonal'
333    portal_type = meta_type
334    security = ClassSecurityInfo()
335
336    security.declareProtected(View,"Title")
337    def Title(self):
338        """compose title"""
339        content = self.getContent()
340        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
341        return "Personal Data"
342
343
344InitializeClass(StudentPersonal)
345
346def addStudentPersonal(container, id, REQUEST=None, **kw):
347    """Add a Students personal data."""
348    ob = StudentPersonal(id, **kw)
349    return CPSBase_adder(container, ob, REQUEST=REQUEST)
350
351###)
352
353class StudentStudyCourse(CPSDocument): ###(
354    """
355    WAeUP Student container for the various student data
356    """
357    meta_type = 'StudentStudyCourse'
358    portal_type = meta_type
359    security = ClassSecurityInfo()
360
361    security.declareProtected(View,"Title")
362    def Title(self):
363        """compose title"""
364        content = self.getContent()
365        return "Course Major"
366
367
368InitializeClass(StudentStudyCourse)
369
370def addStudentStudyCourse(container, id, REQUEST=None, **kw):
371    """Add a Students personal data."""
372    ob = StudentStudyCourse(id, **kw)
373    return CPSBase_adder(container, ob, REQUEST=REQUEST)
374
375###)
376
377class StudentEligibility(CPSDocument): ###(
378    """
379    WAeUP Student container for the various student data
380    """
381    meta_type = 'StudentEligibility'
382    portal_type = meta_type
383    security = ClassSecurityInfo()
384
385    security.declareProtected(View,"Title")
386    def Title(self):
387        """compose title"""
388        return "Eligibility Data"
389
390
391InitializeClass(StudentEligibility)
392
393def addStudentEligibility(container, id, REQUEST=None, **kw):
394    """Add a Students eligibility data."""
395    ob = StudentEligibility(id, **kw)
396    return CPSBase_adder(container, ob, REQUEST=REQUEST)
397
398###)
399
400class StudentDocuments(CPSDocument): ###(
401    """
402    WAeUP Student container for the various student data
403    """
404    meta_type = 'StudentDocuments'
405    portal_type = meta_type
406    security = ClassSecurityInfo()
407
408    security.declareProtected(View,"Title")
409    def Title(self):
410        """compose title"""
411        content = self.getContent()
412        return "Scanned Documents"
413
414
415InitializeClass(StudentDocuments)
416
417def addStudentDocuments(container, id, REQUEST=None, **kw):
418    """Add a Students documents"""
419    ob = StudentDocuments(id, **kw)
420    return CPSBase_adder(container, ob, REQUEST=REQUEST)
421
422###)
423
424class Jamb(CPSDocument): ###(
425    """
426    WAeUP Jamb containing the courses and students
427    """
428    meta_type = 'Jamb'
429    portal_type = meta_type
430    security = ClassSecurityInfo()
431
432    security.declareProtected(View,"Title")
433    def Title(self):
434        """compose title"""
435        content = self.getContent()
436        return "JAMB Data for %s %s" % (content.firstname,content.lastname)
437
438    security.declareProtected(View,"setOwnership")
439    def setOwnership(self,member_id):
440        """set ownership"""
441        pm = getattr(self,'portal_membership')
442        member = pm.getMemberById(member_id)
443        self.changeOwnership(member)
444
445InitializeClass(Jamb)
446
447def addJamb(container, id, REQUEST=None, **kw):
448    """Add a Jamb."""
449    ob = Jamb(id, **kw)
450    return CPSBase_adder(container, ob, REQUEST=REQUEST)
451
452###)
453
454class StudyLevel(CPSDocument): ###(
455    """
456    WAeUP StudyLevel containing the courses and students
457    """
458    meta_type = 'StudyLevel'
459    portal_type = meta_type
460    security = ClassSecurityInfo()
461
462InitializeClass(StudyLevel)
463
464def addStudyLevel(container, id, REQUEST=None, **kw):
465    """Add a StudyLevel."""
466    ob = StudyLevel(id, **kw)
467    return CPSBase_adder(container, ob, REQUEST=REQUEST)
468
469###)
470
471class Semester(CPSDocument): ###(
472    """
473    WAeUP Semester containing the courses and students
474    """
475    meta_type = 'Semester'
476    portal_type = meta_type
477    security = ClassSecurityInfo()
478
479InitializeClass(Semester)
480
481def addSemester(container, id, REQUEST=None, **kw):
482    """Add a Semester."""
483    ob = Semester(id, **kw)
484    return CPSBase_adder(container, ob, REQUEST=REQUEST)
485
486###)
487
Note: See TracBrowser for help on using the repository browser.