source: WAeUP_SRP/trunk/Students.py @ 779

Last change on this file since 779 was 775, checked in by Henrik Bettermann, 18 years ago

PUME import results in states pume_passed or pume_failed depending on the total PUME score
in clearance layout all file uploads removed to enable editing (temporary solution)

  • Property svn:keywords set to Id
File size: 38.5 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 775 2006-10-29 14:22:08Z henrik $
3from string import Template
4from Globals import InitializeClass
5from AccessControl import ClassSecurityInfo
6from AccessControl.SecurityManagement import newSecurityManager
7from zExceptions import BadRequest
8from Products.ZCatalog.ZCatalog import ZCatalog
9from Products.CMFCore.utils import UniqueObject, getToolByName
10from Products.CMFCore.permissions import View
11from Products.CMFCore.permissions import ModifyPortalContent
12from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
13#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
14from Products.CPSDocument.CPSDocument import CPSDocument
15from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder
16from Products.CPSCore.CPSMembershipTool import CPSUnrestrictedUser
17from Products.WAeUP_SRP.Academics import makeCertificateCode
18import logging
19import csv,re
20import Globals
21p_home = Globals.package_home(globals())
22i_home = Globals.INSTANCE_HOME
23MAX_TRANS = 1000
24
25def getInt(s):
26    try:
27        return int(s)
28    except:
29        return 0
30
31def getFloat(s):
32    try:
33        return float(s)
34    except:
35        return 0.0
36
37def getStudentByRegNo(self,reg_no): ###(
38    """search student by JAMB Reg No and return StudentFolder"""
39    search = ZCatalog.searchResults(self.portal_catalog,{'meta_type': 'StudentApplication',
40                                  'SearchableText': reg_no,
41                                  })
42    if len(search) < 1:
43        return None
44    return search[0].getObject().aq_parent
45
46###)
47
48class StudentsFolder(CPSDocument): ###(
49    """
50    WAeUP container for the various WAeUP containers data
51    """
52    meta_type = 'StudentsFolder'
53    portal_type = meta_type
54    security = ClassSecurityInfo()
55
56    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsFromCSV")###(
57    def loadFullTimeStudentsFromCSV(self):
58        """load Fulltime Studentdata from CSV values"""
59        import transaction
60        import random
61        tr_count = 0
62        name = 'short_full_time'
63        no_import = False
64        if not no_import:
65            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
66            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')
67        logger = logging.getLogger('%s_import' % name)
68        logger.info('Start loading from %s.csv' % name)
69        pwlist  = []
70        pwlist.append('"student_id","firstname","middlename","lastname","matric_no","jamb_reg_no","access_code"')
71        pwl_template = Template('"$student_id","$firstname","$middlename","$lastname","$matric_no","$jamb_reg_no","$access_code"')
72        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
73        try:
74            students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
75        except:
76            logger.error('Error reading %s.csv' % name)
77            return
78        l = self.portal_catalog({'meta_type': "StudentClearance",})
79        matrics = []
80        for s in l:
81            matrics.append(s.getObject().getContent().matric_no)
82        print matrics
83        l = self.portal_catalog({'meta_type': "Certificate"})
84        certs = {}
85        for c in l:
86            ca,ac,fa,dep_id,co,certcode = c.relative_path.split('/')
87            cid = "%(dep_id)s_%(certcode)s" % vars()
88            certs[cid] = c.getObject()
89        for student in students:
90            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)
91            sid = student.get('MatricNo')
92            if sid == "":
93                em = 'Empty MatricNo\n'
94                logger.info(em)
95                no_import.write(em)
96                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)
97                continue
98            certcode = makeCertificateCode(student.get('CourseMajor'))
99            dep_id = student.get('Dept')
100            fac_id = student.get('Faculty')
101            cid = "%(dep_id)s_%(certcode)s" % vars()
102            if cid not in certs.keys():
103                em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
104                logger.info(em)
105                no_import.write(em)
106                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)
107                continue
108            certificate_doc = certs[cid].getContent()
109            level = student.get('StudentLevel')
110            try:
111                int(level)
112            except:
113                em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
114                logger.info(em)
115                no_import.write(em)
116                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)
117                continue
118            matric_no = student.get('MatricNo')
119            if matric_no not in matrics:
120                matrics.append(matric_no)
121                sid = self.generateStudentId(student.get('Lastname')[0])
122                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
123                students_folder.invokeFactory('Student', sid)
124                logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
125                student_obj = getattr(self,sid)
126                access_code = "%d" % random.randint(1000000000,9999999999)
127                student_obj.getContent().makeStudentMember(sid,access_code,)
128                pwl_dict = {'student_id': sid,'access_code':access_code}
129                student_obj.invokeFactory('StudentApplication','application')
130                application = student_obj.application
131                da = {'Title': 'Application Data'}
132                student_obj.invokeFactory('StudentPersonal','personal')
133                da['jamb_reg_no'] = student.get('EntryRegNo')
134                personal = student_obj.personal
135                dp = {'Title': 'Personal Data'}
136                student_obj.invokeFactory('StudentClearance','clearance')
137                clearance = student_obj.clearance
138                dc = {'Title': 'Clearance Data'}
139                dc['matric_no'] = matric_no
140                state = student.get('State')
141                lga = student.get('LGA')
142                if state and lga:
143                    lga =  state + ' / ' + lga
144                else:
145                    lga = "None"
146                dc['lga'] = lga
147                dc['nationality'] = student.get('Nationality')
148                dc['email'] = student.get('Emailaddress')
149                dp['firstname'] = student.get('FirstName')
150                dp['middlename'] = student.get('MiddleName')
151                dp['lastname'] = student.get('Lastname')
152                dp['former_surname'] = student.get('FormerSurname')
153                dp['sex'] = student.get('Sex') == 'F'
154                dp['perm_address'] = student.get('PermanentAddress')
155                dp['perm_city'] = student.get('PermanentAddressCity')
156                dp['campus_address'] = student.get('CampusAddress')
157                dp['phone'] = student.get('PhoneNumber')
158                application.getContent().edit(mapping=da)
159                personal.getContent().edit(mapping=dp)
160                clearance.getContent().edit(mapping=dc)
161                #
162                # Study Course
163                #
164                student_obj.invokeFactory('StudentStudyCourse','study_course')
165                studycourse = student_obj.study_course
166                dsc = {}
167                from_certificate = ['title',
168                                   'max_elect',
169                                   'max_pass',
170                                   'n_core',
171                                   'nr_years',
172                                   'probation_credits',
173                                   'promotion_credits',
174                                   'start_level',
175                                  ]
176                for f in from_certificate:
177                    dsc[f] = getattr(certificate_doc,f)
178                dsc['faculty'] = fac_id
179                dsc['department'] = dep_id
180                dsc['study_course'] = certcode
181                css = student.get('CurrentSession') or '2004-2005'
182                cs = int(css.split('-')[0]) - 2000
183                cl = int(student.get('StudentLevel') or '100')/100
184                dsc['entry_session'] = "200%s" % (cs - cl)
185                dsc['clr_ac_pin'] = access_code
186                studycourse.getContent().edit(mapping=dsc)
187                #
188                # Level
189                #
190##                l = getattr(studycourse,level,None)
191##                if 0 and l is None:
192##                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
193##                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
194##                    studycourse.invokeFactory('StudentStudyLevel', level)
195##                    l = getattr(studycourse, level)
196##                    certificate = certs[certcode]
197##                    cert_level = getattr(certificate,level,None)
198##                    if cert_level is None:
199##                        logger.info('Level %(level)s not in %(certcode)s' % vars())
200##                    l.getContent().edit(mapping={'Title': "Level %s" % level})
201            else:
202                em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
203                logger.info(em)
204                no_import.write(em)
205                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)
206                continue
207            if tr_count > MAX_TRANS:
208                transaction.commit()
209                em = 'Transaction commited\n' % student
210                logger.info(em)
211                tr_count = 0
212            tr_count += 1
213            pwl_dict.update(dc)
214            pwl_dict.update(da)
215            pwl_dict.update(dp)
216            wftool = self.portal_workflow
217            pwlist.append(pwl_template.substitute(pwl_dict))
218            wftool.doActionFor(student_obj,'clear_and_validate')
219            student_obj.manage_setLocalRoles(sid, ['Owner',])
220            wftool.doActionFor(application,'close')
221            application.manage_setLocalRoles(sid, ['Owner',])
222            wftool.doActionFor(clearance,'close')
223            clearance.manage_setLocalRoles(sid, ['Owner',])
224            wftool.doActionFor(personal,'close')
225            personal.manage_setLocalRoles(sid, ['Owner',])
226            wftool.doActionFor(studycourse,'close_for_edit')
227            studycourse.manage_setLocalRoles(sid, ['Owner',])
228        open("%s/import/pwlist-%s.csv" % (i_home,name),"w+").write('\n'.join(pwlist))
229        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
230    ###)
231
232    security.declareProtected(ModifyPortalContent,"loadPumeResultsFromCSV")###(
233    def loadPumeResultsFromCSV(self):
234        """load Fulltime Studentdata from CSV values"""
235        import transaction
236        import random
237        wftool = self.portal_workflow
238        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
239        csv_d = {'jamb_reg_no': "Matnumber",
240                 'jamb_lastname': "Surname",
241                 'pume_options': "Options",
242                 'session': "Session",
243                 'days': "Days",
244                 'response': "Responce",
245                 'wrong': "Wrong",
246                 'pume_eng_score': "EngScore",
247                 'pume_gen_score': "GenScore",
248                 'pume_tot_score': "Right",
249                 'batch': "Batch",
250                 'serial': "SerialNo",
251                 'jamb_score': "JambScore",
252                 'omitted':"Omitted",
253                 'search_key': "SearchKey",
254                 'jamb_sex': "Sex",
255                 'fac1': "Fac1",
256                 'fac2': "Fac2",
257                 'jamb_first_cos': "CourseofStudy",
258                 'stud_status':"StudStatus",
259                 'registered': "Registered",
260                 'jamb_state': "State",
261                 'eng_fail': "EngFail",
262                 'gen_fail': "GenFail",
263                 'un_ans_eng': "UnAnsEng",
264                 'un_ans_eng': "UnAnsGen",
265                 'total_ans': "TotalUnAns",
266                 'dept': "Dept",
267                 'jamb_second_cos': "Course2",
268                 'jamb_third_cos': "course3",
269                 }
270        csv_fields = [f[1] for f in csv_d.items()]
271        tr_count = 0
272        name = 'pume_results'
273        no_import = []
274        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
275        no_import.append('%s\n' % s)
276        logger = logging.getLogger('%s_import' % name)
277        logger.info('Start loading from %s.csv' % name)
278        try:
279            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
280        except:
281            logger.error('Error reading %s.csv' % name)
282            return
283        for jamb in result:
284            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
285            processing = "processing %s" % format
286            logger.info(processing % jamb)
287            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
288            #import pdb;pdb.set_trace()
289            res = self.portal_catalog({'portal_type': "StudentApplication",
290                                     'jamb_reg_no': jamb_reg_no })
291            if res:
292                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
293                logger.info(em)
294                no_import.append(em)
295                no_import.append(format % jamb)
296                continue
297            jamb_name = jamb.get(csv_d['jamb_lastname'])
298            jamb_name.replace('>','')
299            names = jamb_name.split()
300            letter = names[-1][0].upper()
301            sid = self.generateStudentId(letter)
302            not_created = True
303            while not_created:
304                try:
305                    students_folder.invokeFactory('Student', sid)
306                    not_created = False
307                except BadRequest:
308                    sid = self.generateStudentId(letter)
309            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
310            student = getattr(self,sid)
311            student.manage_setLocalRoles(sid, ['Owner',])
312            student.invokeFactory('StudentClearance','clearance')
313            #wftool.doActionFor(student.clearance,'open')
314            dp = {'Title': 'Clearance Data'}
315            student.clearance.manage_setLocalRoles(sid, ['Owner',])
316            student.invokeFactory('StudentPume','pume')
317            dp = {'Title': 'Pume Data'}
318            student.invokeFactory('StudentApplication','application')
319            da = {'Title': 'Application Data'}
320            da["jamb_lastname"] = jamb_name
321            da_fields = ('jamb_reg_no',
322                         'jamb_sex',
323                         'jamb_state',
324                         'jamb_score',
325                         'jamb_first_cos',
326                         'jamb_sex',
327                         'jamb_state',
328                         'jamb_first_cos',
329                         'jamb_second_cos',
330                         )
331            for f in da_fields:
332                da[f] = jamb.get(csv_d[f])
333            app = student.application
334            app.getContent().edit(mapping=da)
335            app.manage_setLocalRoles(sid, ['Owner',])
336            dp_fields = (
337                         'pume_eng_score',
338                         'pume_gen_score',
339                         'pume_tot_score',
340                         )
341            for f in dp_fields:
342                dp[f] = float(jamb.get(csv_d[f]))
343            pume = student.pume
344            pume.getContent().edit(mapping=dp)
345            wftool.doActionFor(pume,'close',dest_container=app)
346            pume.manage_setLocalRoles(sid, ['Owner',])
347            student.getContent().createSubObjects()
348            if dp['pume_tot_score']>49:
349                wftool.doActionFor(student,'pume_pass',dest_container=student)
350            else:
351                wftool.doActionFor(student,'pume_fail',dest_container=student)
352            if len(no_import) > 1:
353                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
354                     '\n'.join(no_import))
355        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
356    ###)
357
358    security.declareProtected(ModifyPortalContent,"loadFullTimeStudentsResultsFromCSV") ###(
359    def loadFullTimeStudentsResultsFromCSV(self):
360        """load Fulltime Studentdata from CSV values"""
361        #return
362        level_wf_actions = {}
363        level_wf_actions["SUCCESSFUL STUDENT"] = "pass_A"
364        level_wf_actions["STUDENT WITH CARRYOVER COURSES"] = "pass_B"
365        level_wf_actions["STUDENT FOR PROBATION"] = "probate_C"
366        level_wf_actions["STUDENT ON PROBATION/TRANSFER"] = "reject_D"
367        import transaction
368        wftool = self.portal_workflow
369        tr_count = 0
370        name = 'short_full_time_results_2004_2005'
371        no_import = False
372        if not no_import:
373            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
374            no_import.write('"Matnumber","CosCode","Ansbook","CosStuatus","Session","Mat_Cos","Score","CarryLevel","Grade","Weight","Semster","Verdict","Level","id","GPA"\n')
375        logger = logging.getLogger('%s_import' % name)
376        logger.info('Start loading from %s.csv' % name)
377        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
378        try:
379            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
380        except:
381            logger.error('Error reading %s.csv' % name)
382            return
383        l = self.portal_catalog({'meta_type': "Course"})
384        courses = {}
385        for c in l:
386            courses[c.id] = c.getObject()
387        level_changed = False
388        student_changed = False
389        sid = ''
390        #import pdb;pdb.set_trace()
391        for result in results:
392            temp_sid = result.get('Matnumber')
393            if temp_sid != sid:
394                student_changed = True
395                res = self.portal_catalog({'meta_type': "StudentClearance",
396                                         'SearchableText': temp_sid })
397                if not res:
398                    em = 'Student with ID %(Matnumber)s not found\n' % result
399                    logger.info(em)
400                    no_import.write(em)
401                    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)
402                    continue
403                elif len(res) > 1:
404                    em = 'More than one Student with ID %(Matnumber)s found\n' % result
405                    logger.info(em)
406                    no_import.write(em)
407                    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)
408                    continue
409                sid = temp_sid
410                sf = res[0].getObject().aq_parent
411                sc = getattr(sf,'study_course')
412                level = ''
413            else:
414                student_changed = False
415            course = result.get('CosCode')
416            if course not in courses.keys():
417                em = 'Course with ID %(CosCode)s not found\n' % result
418                logger.info(em)
419                no_import.write(em)
420                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)
421                continue
422            course_doc = courses[course].getContent()
423            temp_level = result.get('Level')
424            student_id = sf.getId()
425            result['StudentId'] = student_id
426            if temp_level != level:
427                try:
428                    int(temp_level)
429                except:
430                    em = 'Result with ID %(Matnumber)s Course %(CosCode)s Level is empty\n' % result
431                    logger.info(em)
432                    no_import.write(em)
433                    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)
434                    continue
435                level_changed = True
436                if 'dlev' in vars().keys():
437                    wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
438                level = temp_level
439                l = getattr(sc,level,None)
440                if l is None:
441                    logger.info('Creating Level %(Level)s for %(StudentId)s %(Matnumber)s' % result)
442                    sc.invokeFactory('StudentStudyLevel', level)
443                    l = getattr(sc, level)
444                    l.manage_setLocalRoles(student_id, ['Owner',])
445            else:
446                level_changed = False
447            cr = getattr(l,course,None)
448            if cr is None:
449                logger.info('Creating Course %(CosCode)s for %(StudentId)s %(Matnumber)s in Level %(Level)s' % result)
450                l.invokeFactory('StudentCourseResult',course)
451            cr = getattr(l,course)
452            dcr = {}
453            from_course = ['title',
454                           'credits',
455                           'passmark',
456                           ]
457            for f in from_course:
458                dcr[f] = getattr(course_doc,f)
459            dlev = {}
460            dcr['ansbook'] = result.get('Ansbook')
461            dcr['semester'] = getInt(result.get('Semster'))
462            dcr['status'] = result.get('CosStuatus')
463            dcr['score'] = getInt(result.get('Score'))
464            dlev['session'] = result.get('Session')
465            dcr['carry_level'] = result.get('CarryLevel')
466            dcr['grade'] = result.get('Grade')
467            dcr['weight'] = result.get('Weight')
468            dlev['verdict'] = result.get('Verdict')
469            dcr['import_id'] = result.get('id')
470            gpa = result.get('GPA').replace(',','.')
471            dlev['imported_gpa'] = getFloat(gpa)
472            cr.getContent().edit(mapping = dcr)
473            cr.manage_setLocalRoles(student_id, ['Owner',])
474            l.getContent().edit(mapping = dlev)
475            if tr_count > MAX_TRANS:
476                transaction.commit()
477                tr_count = 0
478            tr_count += 1
479            wftool.doActionFor(cr,'close')
480        wftool.doActionFor(l,level_wf_actions[dlev['verdict']])
481        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
482
483###)
484
485    security.declareProtected(ModifyPortalContent,"loadJAMBFromCSV")###(
486    def loadJAMBFromCSV(self):
487        """load JAMB data from CSV values"""
488        #return
489        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
490        import transaction
491        tr_count = 0
492        name = 'SampleJAMBDataII'
493        wftool = self.portal_workflow
494        no_import = False
495        if not no_import:
496            no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
497            no_import.write('REG-NO,NAME,SEX,STATE,LGA,ENG-SCORE,SUBJ1,SUBJ1-SCORE,SUBJ2,SUBJ2-SCORE,SUBJ3,SUBJ3-SCORE,AGGREGATE,UNIV1,FACULTY1,COURSE1,UNIV2,FACULTY2,COURSE2')
498        logger = logging.getLogger('%s_import' % name)
499        logger.info('Start loading from %s.csv' % name)
500        try:
501            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
502        except:
503            logger.error('Error reading %s.csv' % name)
504            return
505        for jamb in result:
506            logger.info('processing %(REG-NO)s,%(NAME)s,%(SEX)s,%(STATE)s,%(LGA)s,%(ENG-SCORE)s,%(SUBJ1)s,%(SUBJ1-SCORE)s,%(SUBJ2)s,%(SUBJ2-SCORE)s,%(SUBJ3)s,%(SUBJ3-SCORE)s,%(AGGREGATE)s,%(UNIV1)s,%(FACULTY1)s,%(COURSE1)s,%(UNIV2)s,%(FACULTY2)s,%(COURSE2)s\n' % jamb)
507            jamb_reg_no = jamb.get('REG-NO')
508            res = self.portal_catalog({'meta_type': "StudentApplication",
509                                     'jamb_reg_no': jamb_reg_no })
510            if res:
511                em = 'Student with REG-NO %(REG-NO)s already exists\n' % jamb
512                logger.info(em)
513                no_import.write(em)
514                no_import.write('%(REG-NO)s,%(NAME)s,%(SEX)s,%(STATE)s,%(LGA)s,%(ENG-SCORE)s,%(SUBJ1)s,%(SUBJ1-SCORE)s,%(SUBJ2)s,%(SUBJ2-SCORE)s,%(SUBJ3)s,%(SUBJ3-SCORE)s,%(AGGREGATE)s,%(UNIV1)s,%(FACULTY1)s,%(COURSE1)s,%(UNIV2)s,%(FACULTY2)s,%(COURSE2)s\n' % jamb)
515                continue
516            jamb_name = jamb.get("NAME")
517            jamb_name.replace('>','')
518            names = jamb_name.split()
519            letter = names[-1][0].upper()
520            sid = self.generateStudentId(letter)
521            not_created = True
522            while not_created:
523                try:
524                    students_folder.invokeFactory('Student', sid)
525                    not_created = False
526                except BadRequest:
527                    sid = self.generateStudentId(letter)
528            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
529            student = getattr(self,sid)
530            student.manage_setLocalRoles(sid, ['Owner',])
531            student.invokeFactory('StudentApplication','application')
532            da = {'Title': 'Application Data'}
533            da["jamb_reg_no"] = jamb.get("REG-NO")
534            da["jamb_lastname"] = jamb_name
535            da["jamb_sex"] = jamb.get("SEX")
536            da["jamb_state"] = jamb.get("STATE")
537            da["jamb_lga"] = jamb.get("LGA")
538            da["jamb_score"] = jamb.get("AGGREGATE")
539            da["jamb_first_cos"] = jamb.get("COURSE1")
540            da["jamb_second_cos"] = jamb.get("COURSE2")
541            da["jamb_first_uni"] = jamb.get("UNIV1")
542            da["jamb_second_uni"] = jamb.get("UNIV2")
543            app = student.application
544            app_doc = app.getContent()
545            app_doc.edit(mapping=da)
546            #wftool.doActionFor(app,'open',dest_container=app)
547            app.manage_setLocalRoles(sid, ['Owner',])
548            student.getContent().createSubObjects()
549        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
550    ###)
551
552
553    security.declareProtected(View,"fixOwnership")
554    def fixOwnership(self):
555        """fix Ownership"""
556        for s in self.portal_catalog(meta_type = 'Student'):
557            student = s.getObject()
558            sid = s.getId
559            import pdb;pdb.set_trace()
560            student.application.manage_setLocalRoles(sid, ['Owner',])
561            student.personal.manage_setLocalRoles(sid, ['Owner',])
562
563    security.declareProtected(View,"Title")
564    def Title(self):
565        """compose title"""
566        return "Student Section"
567
568    def generateStudentId(self,letter): ###(
569        import random
570        r = random
571        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
572            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
573        students = self.portal_catalog(meta_type = "StudentsFolder")[-1]
574        sid = "%c%d" % (letter,r.randint(99999,1000000))
575        while hasattr(students, sid):
576            sid = "%c%d" % (letter,r.randint(99999,1000000))
577        return sid
578        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
579    ###)
580
581InitializeClass(StudentsFolder)
582
583def addStudentsFolder(container, id, REQUEST=None, **kw):
584    """Add a Student."""
585    ob = StudentsFolder(id, **kw)
586    return CPSBase_adder(container, ob, REQUEST=REQUEST)
587###)
588
589class Student(CPSDocument): ###(
590    """
591    WAeUP Student container for the various student data
592    """
593    meta_type = 'Student'
594    portal_type = meta_type
595    security = ClassSecurityInfo()
596
597    security.declareProtected(View,"Title")
598    def Title(self):
599        """compose title"""
600        reg_nr = self.getId()[1:]
601        data = getattr(self,'personal',None)
602        if data:
603            content = data.getContent()
604            return "%s %s" % (content.firstname,content.lastname)
605        data = getattr(self,'application',None)
606        if data:
607            content = data.getContent()
608            return "%s" % (content.jamb_lastname)
609        return self.title
610
611    security.declarePrivate('makeStudentMember') ###(
612    def makeStudentMember(self,sid,password='uNsEt'):
613        """make the student a member"""
614        membership = self.portal_membership
615        membership.addMember(sid,
616                             password ,
617                             roles=('Member',
618                                     'Student',
619                                     ),
620                             domains='',
621                             properties = {'memberareaCreationFlag': False,},)
622        member = membership.getMemberById(sid)
623        self.portal_registration.afterAdd(member, sid, password, None)
624        self.manage_setLocalRoles(sid, ['Owner',])
625
626###)
627
628    security.declareProtected(View,'createSubObjects') ###(
629    def createSubObjects(self):
630        """make the student a member"""
631        dp = {'Title': 'Personal Data'}
632        app_doc = self.application.getContent()
633        names = app_doc.jamb_lastname.split()
634        if len(names) == 3:
635            dp['firstname'] = names[0].capitalize()
636            dp['middlename'] = names[1].capitalize()
637            dp['lastname'] = names[2].capitalize()
638        elif len(names) == 2:
639            dp['firstname'] = names[0].capitalize()
640            dp['lastname'] = names[1].capitalize()
641        else:
642            dp['lastname'] = app_doc.jamb_lastname
643        dp['sex'] = app_doc.jamb_sex == 'F'
644        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
645        proxy = self.aq_parent
646        proxy.invokeFactory('StudentPersonal','personal')
647        per = proxy.personal
648        per_doc = per.getContent()
649        per_doc.edit(mapping = dp)
650        per.manage_setLocalRoles(self.getId(), ['Owner',])
651        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
652
653###)
654
655InitializeClass(Student)
656
657def addStudent(container, id, REQUEST=None, **kw):
658    """Add a Student."""
659    ob = Student(id, **kw)
660    return CPSBase_adder(container, ob, REQUEST=REQUEST)
661
662###)
663
664class StudentAccommodation(CPSDocument): ###(
665    """
666    WAeUP Student container for the various student data
667    """
668    meta_type = 'StudentAccommodation'
669    portal_type = meta_type
670    security = ClassSecurityInfo()
671
672    security.declareProtected(View,"Title")
673    def Title(self):
674        """compose title"""
675        content = self.getContent()
676        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
677        return "Accommodation Data for Session %s" % content.session
678
679
680InitializeClass(StudentAccommodation)
681
682def addStudentAccommodation(container, id, REQUEST=None, **kw):
683    """Add a Students personal data."""
684    ob = StudentAccommodation(id, **kw)
685    return CPSBase_adder(container, ob, REQUEST=REQUEST)
686
687###)
688
689class StudentPersonal(CPSDocument): ###(
690    """
691    WAeUP Student container for the various student data
692    """
693    meta_type = 'StudentPersonal'
694    portal_type = meta_type
695    security = ClassSecurityInfo()
696
697    security.declareProtected(View,"Title")
698    def Title(self):
699        """compose title"""
700        content = self.getContent()
701        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
702        return "Personal Data"
703
704
705InitializeClass(StudentPersonal)
706
707def addStudentPersonal(container, id, REQUEST=None, **kw):
708    """Add a Students personal data."""
709    ob = StudentPersonal(id, **kw)
710    return CPSBase_adder(container, ob, REQUEST=REQUEST)
711
712###)
713
714class StudentClearance(CPSDocument): ###(
715    """
716    WAeUP Student container for the various student data
717    """
718    meta_type = 'StudentClearance'
719    portal_type = meta_type
720    security = ClassSecurityInfo()
721
722    security.declareProtected(View,"Title")
723    def Title(self):
724        """compose title"""
725        content = self.getContent()
726        #return "Clearance Data for %s %s" % (content.firstname,content.lastname)
727        return "Clearance Data"
728
729
730InitializeClass(StudentClearance)
731
732def addStudentClearance(container, id, REQUEST=None, **kw):
733    """Add a Students personal data."""
734    ob = StudentClearance(id, **kw)
735    return CPSBase_adder(container, ob, REQUEST=REQUEST)
736
737###)
738
739class StudentStudyLevel(CPSDocument): ###(
740    """
741    WAeUP Student container for the various student data
742    """
743    meta_type = 'StudentStudyLevel'
744    portal_type = meta_type
745    security = ClassSecurityInfo()
746
747    security.declareProtected(View,"Title")
748    def Title(self):
749        """compose title"""
750        return "Level %s" % self.aq_parent.getId()
751
752##    security.declarePublic("gpa")
753##    def gpa(self):
754##        """calculate the gpa"""
755##        sum = 0
756##        course_count = 0
757##        for sc in self.objectValues():
758##            result = sc.getContent()
759##            if not result.grade:
760##                continue
761##            res = self.portal_catalog({'meta_type': 'Course',
762##                                          'id': sc.aq_parent.id})
763##            if len(res) != 1:
764##                continue
765##            course = res[0].getObject().getContent()
766##            sum += course.credits * ['F','E','D','C','B','A'].index(result.grade)
767##            course_count += 1
768##        if course_count:
769##            return sum/course_count
770##        return 0.0
771
772InitializeClass(StudentStudyLevel)
773
774def addStudentStudyLevel(container, id, REQUEST=None, **kw):
775    """Add a Students personal data."""
776    ob = StudentStudyLevel(id, **kw)
777    return CPSBase_adder(container, ob, REQUEST=REQUEST)
778
779###)
780
781class StudentStudyCourse(CPSDocument): ###(
782    """
783    WAeUP Student container for the various student data
784    """
785    meta_type = 'StudentStudyCourse'
786    portal_type = meta_type
787    security = ClassSecurityInfo()
788
789    security.declareProtected(View,"Title")
790    def Title(self):
791        """compose title"""
792        content = self.getContent()
793        return "Study Course"
794
795
796InitializeClass(StudentStudyCourse)
797
798def addStudentStudyCourse(container, id, REQUEST=None, **kw):
799    """Add a Students personal data."""
800    ob = StudentStudyCourse(id, **kw)
801    return CPSBase_adder(container, ob, REQUEST=REQUEST)
802
803###)
804
805class StudentApplication(CPSDocument): ###(
806    """
807    WAeUP Student container for the various student data
808    """
809    meta_type = 'StudentApplication'
810    portal_type = meta_type
811    security = ClassSecurityInfo()
812
813    security.declareProtected(View,"Title")
814    def Title(self):
815        """compose title"""
816        return "Application Data"
817
818
819InitializeClass(StudentApplication)
820
821def addStudentApplication(container, id, REQUEST=None, **kw):
822    """Add a Students eligibility data."""
823    ob = StudentApplication(id, **kw)
824    return CPSBase_adder(container, ob, REQUEST=REQUEST)
825###)
826
827
828class StudentPume(CPSDocument): ###(
829    """
830    WAeUP Student container for the various student data
831    """
832    meta_type = 'StudentPume'
833    portal_type = meta_type
834    security = ClassSecurityInfo()
835
836    security.declareProtected(View,"Title")
837    def Title(self):
838        """compose title"""
839        return "PUME Results"
840
841
842InitializeClass(StudentPume)
843
844def addStudentPume(container, id, REQUEST=None, **kw):
845    """Add a Students PUME data."""
846    ob = StudentPume(id, **kw)
847    return CPSBase_adder(container, ob, REQUEST=REQUEST)
848###)
849
850##class StudentSemester(CPSDocument): ###(
851##    """
852##    WAeUP StudentSemester containing the courses and students
853##    """
854##    meta_type = 'StudentSemester'
855##    portal_type = meta_type
856##    security = ClassSecurityInfo()
857##
858##InitializeClass(StudentSemester)
859##
860##def addStudentSemester(container, id, REQUEST=None, **kw):
861##    """Add a StudentSemester."""
862##    ob = StudentSemester(id, **kw)
863##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
864##
865#####)
866
867##class Semester(CPSDocument): ###(
868##    """
869##    WAeUP Semester containing the courses and students
870##    """
871##    meta_type = 'Semester'
872##    portal_type = meta_type
873##    security = ClassSecurityInfo()
874##
875##InitializeClass(Semester)
876##
877##def addSemester(container, id, REQUEST=None, **kw):
878##    """Add a Semester."""
879##    ob = Semester(id, **kw)
880##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
881##
882#####)
883
884class StudentCourseResult(CPSDocument): ###(
885    """
886    WAeUP StudentCourseResult
887    """
888    meta_type = 'StudentCourseResult'
889    portal_type = meta_type
890    security = ClassSecurityInfo()
891
892    def getCourseEntry(self,cid):
893        res = self.portal_catalog({'meta_type': "Course",
894                                           'id': cid})
895        if res:
896            return res[-1]
897        else:
898            return None
899
900    security.declareProtected(View,"Title")
901    def Title(self):
902        """compose title"""
903        cid = self.aq_parent.getId()
904        ce = self.getCourseEntry(cid)
905        if ce:
906            return "%s" % ce.Title
907        return "No course with id %s" % cid
908
909InitializeClass(StudentCourseResult)
910
911def addStudentCourseResult(container, id, REQUEST=None, **kw):
912    """Add a StudentCourseResult."""
913    ob = StudentCourseResult(id, **kw)
914    return CPSBase_adder(container, ob, REQUEST=REQUEST)
915###)
916
917# Backward Compatibility StudyLevel
918
919from Products.WAeUP_SRP.Academics import StudyLevel
920
921from Products.WAeUP_SRP.Academics import addStudyLevel
922
Note: See TracBrowser for help on using the repository browser.