source: WAeUP_SRP/trunk/Students.py @ 1883

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

Rerunning transferStudents always transferred students, who were already transferred, if they had not level object. These students have upto 3 entries in matric_no_history in their clearance object.

  • Property svn:keywords set to Id
File size: 57.2 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Students.py 1880 2007-06-12 05:14:45Z 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
18from Products.AdvancedQuery import Eq, Between, Le,In
19import DateTime
20import logging
21import csv,re,os
22import Globals
23p_home = Globals.package_home(globals())
24i_home = Globals.INSTANCE_HOME
25MAX_TRANS = 1000
26from urllib import urlencode
27
28import DateTime
29#import PIL.Image
30from StringIO import StringIO
31
32def makeCertificateCode(code): ###(
33    code = code.replace('.','')
34    code = code.replace('(','')
35    code = code.replace(')','')
36    code = code.replace('/','')
37    code = code.replace(' ','')
38    code = code.replace('_','')
39    return code
40
41###)
42
43def response_write(response,s):
44    response.setHeader('Content-type','text/html; charset=ISO-8859-15')
45    while s.find('<') > -1:
46        s = s.replace('<','&lt;')
47    while s.find('>') > -1:
48        #from pdb import set_trace;set_trace()
49        s = s.replace('>','&gt;')
50    response.write("%s<br>\n" % s)
51
52def getInt(s): ###(
53    try:
54        return int(s)
55    except:
56        return 0
57
58def getFloat(s):
59    try:
60        return float(s)
61    except:
62        return 0.0
63
64###)
65
66def getStudentByRegNo(self,reg_no): ###(
67    """search student by JAMB Reg No and return StudentFolder"""
68    search = ZCatalog.searchResults(self.portal_catalog_real,{'meta_type': 'StudentApplication',
69                                  'SearchableText': reg_no,
70                                  })
71    if len(search) < 1:
72        return None
73    return search[0].getObject().aq_parent
74
75###)
76
77def checkJambNo(jnr):
78    try:
79        if len(jnr) != 10:
80            return False
81    except:
82        return False
83    try:
84        int(jnr[:8])
85        return True
86    except:
87        return False
88
89class StudentsFolder(CPSDocument): ###(
90    """
91    WAeUP container for the various WAeUP containers data
92    """
93    meta_type = 'StudentsFolder'
94    portal_type = meta_type
95    security = ClassSecurityInfo()
96
97    security.declareProtected(ModifyPortalContent,"loadPumeResultsFromCSV")###(
98    def loadPumeResultsFromCSV(self):
99        """load Fulltime Studentdata from CSV values into pumeresults catalog"""
100        import transaction
101        import random
102##        csv_d = {'jamb_reg_no': "RegNumber", ###(
103##                 'status': "Admission Status",
104##                 'name': "Name",
105##                 'score': "Score",
106##                 'sex': "Sex",
107##                 'faculty': "Faculty",
108##                 'department': "Dept",
109##                 'course': "Course",
110##                 'course_code_org': "Course Code",
111##                 }
112###)
113##        csv_d = {'jamb_reg_no': "JAMBRegno",
114##                'name': "Name",
115##                'score': "Score",
116##                 'sex': "Sex",
117##                 'course': "Course",
118##                 'faculty': "Faculty",
119##                 'department': "Dept",
120##                 'course_code_org': "Course Code",
121##                 'status': "Admission Status",
122##                 'result_type': None,
123##                 }
124
125        csv_d = {'jamb_reg_no': "reg_no",
126                 'name': "fullname",
127                 'score': "pume_score",
128                 'sex': "sex",
129                 'course': "study_course",
130                 'course_code_org': "study_course",
131                 'status': "admission_status",
132                 'result_type': "entry_mode",
133                 }
134
135        csv_fields = [f[1] for f in csv_d.items() if f[1]]
136        tr_count = 0
137        total = 0
138        #name = 'pup_new'
139        #name = 'pup_update'
140        name = 'Admitted'
141        update = name.endswith('update')
142        no_import = []
143        ok_import = []
144        ok_import.append('%s' % ','.join(['"%s"' % fn for fn in csv_d.keys()]))
145        no_import.append('%s' % ','.join(['"%s"' % fn for fn in csv_fields]))
146        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
147        ok_import_name = "%s/import/%s_imported_%s.csv" % (i_home,name,current)
148        #open(ok_import_name,"w").write('\n'.join(no_import))
149        no_import_name = "%s/import/%s_not_imported_%s.csv" % (i_home,name,current)
150        #open(no_import_name,"w").write('\n'.join(no_import))
151        logger = logging.getLogger('Import.%s' % name)
152        starttime = DateTime.now()
153        logger.info('Start loading from %s.csv' % name)
154        try:
155            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
156        except:
157            logger.error('Error reading %s.csv' % name)
158            return
159        pume = self.portal_pumeresults
160        format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
161        import_format = ','.join(['"%%(%s)s"' % fn for fn in csv_d.keys()])
162        eduplicate = '%s,"duplicate"' % format
163        einvalidjamb = '%s,"invalid JambRegNo"' % format
164        added = 'added ,%s' % format
165        #from pdb import set_trace;set_trace()
166        for jamb in result:
167            dict = {}
168            for f,fn in csv_d.items():
169                dict[f] = jamb.get(csv_d[f])
170            dict['result_type'] = 'CEST'
171            jnr = jamb.get(csv_d['jamb_reg_no'])
172            #if not checkJambNo(jnr):
173            #    logger.info(einvalidjamb % jamb)
174            #    dd = {}
175            #    for f,fn in csv_d.items():
176            #        dd[fn] = getattr(data,f)
177            #        no_import.append(eduplicate % dd)
178            #        no_import.append(eduplicate % jamb)
179            #    continue
180            res = pume(jamb_reg_no=jnr)
181            if len(res) > 0:
182                if update:
183                    try:
184                        pume.modifyRecord(**dict)
185                    except ValueError:
186                        logger.info(eduplicate % jamb)
187                        continue
188                    except KeyError:
189                        pume.addRecord(**dict)
190                        logger.info(added % jamb)
191                        continue
192                else:
193                    data = res[0]
194                    if data.name != jamb.get(csv_d['name']):
195                        #set_trace()
196                        logger.info(eduplicate % jamb)
197                        #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
198                        #logger.info(em)
199                        dd = {}
200                        for f,fn in csv_d.items():
201                            dd[fn] = getattr(data,f)
202                        no_import.append(eduplicate % dd)
203                        no_import.append(eduplicate % jamb)
204                    continue
205            try:
206                pume.addRecord(**dict)
207                ok_import.append(import_format % dict)
208            except ValueError:
209                logger.info(eduplicate % jamb)
210                #em = 'Student with REG-NO %(jamb_reg_no)s already exists\n' % dict
211                #logger.info(em)
212                no_import.append(eduplicate % jamb)
213        logger.info('End loading from %s.csv' % name)
214        if len(no_import) > 1:
215            open(no_import_name,"w+").write('\n'.join(no_import))
216        open(ok_import_name,"w+").write('\n'.join(ok_import))
217        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
218    ###)
219
220    security.declareProtected(ModifyPortalContent,"createStudents")###(
221    def createStudents(self):
222        """
223        load addmitted Studentdata from CSV values and create Studentobjects.
224        This is the current method to create new addmitted Students.
225        Before running the eventservice for the students_catalog must be disabled.
226        """
227        import transaction
228        import random
229        #from pdb import set_trace
230        wftool = self.portal_workflow
231        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
232        students_folder = self.portal_url.getPortalObject().campus.students
233        levels =       {'ume_ft':'100',
234                        'de_ft': '200',
235                        'ug_pt': '100',
236                        'de_pt': '200',
237                        'pg_ft': '700',
238                        'pg_pt': '700',
239                        'dp_pt': '100',
240                        'dp_ft': '100',
241                        }
242        csv_d = {'jamb_reg_no': "reg_no",
243                 'entry_mode': 'entry_mode',
244                 'jamb_firstname': "firstname",
245                 'jamb_middlename': "middlename",
246                 'jamb_lastname': "lastname",
247                 'jamb_sex': "sex",
248                 'jamb_state': "state",
249                 'birthday': "date_of_birth",
250                 'app_email': "email",
251                 'study_course': "study_course",
252                 'perm_address': "address",
253                 'admission_status': "admission_status",
254                 }
255        csv_fields = [f[1] for f in csv_d.items()]
256        tr_count = 0
257        total = 0
258        #name = 'pume_results'
259        name = 'Admitted'
260        no_import = []
261        s = ','.join(['"%s"' % fn for fn in csv_fields])
262        no_import.append('"Error",%s' % s)
263        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
264        no_certificate = "no certificate %s" % format
265        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write('\n'.join(no_import))
266        logger = logging.getLogger('Students.StudentsFolder.createStudents')
267        logger.info('Start loading from %s.csv' % name)
268        certs = {}
269        try:
270            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
271        except:
272            logger.error('Error reading %s.csv' % name)
273            return
274        for result in results:
275            if not result.get(csv_d['admission_status']).startswith('Admitted'):
276                continue
277            #result['Error'] = "Processing "
278            #logger.info(format % result)
279            jamb_reg_no = result.get(csv_d['jamb_reg_no'])
280            res = self.students_catalog(jamb_reg_no = jamb_reg_no)
281            if res:
282                em = 'Student with RegNo %s already exists\n' % jamb_reg_no
283                logger.info(em)
284                result['Error'] = "Student exists"
285                no_import.append(format % result)
286                continue
287            cert_id = makeCertificateCode(result.get(csv_d['study_course']))
288            if cert_id not in certs.keys():
289                res = self.portal_catalog(meta_type = "Certificate",id = cert_id)
290                if not res:
291                    em = 'No Certificate with ID %s \n' % cert_id
292                    logger.info(em)
293                    result['Error'] = "No Certificate %s" % cert_id
294                    no_import.append( format % result)
295                    continue
296                cert = res[0]
297                cert_path = cert.getPath().split('/')
298                certificate = certs[cert_id] = {'faculty': cert_path[-4],
299                                     'department': cert_path[-3]}
300            cert_doc = certs[cert_id]
301            catalog_entry = {}
302            catalog_entry['jamb_reg_no'] = jamb_reg_no
303            firstname = result.get(csv_d['jamb_firstname'])
304            middlename = result.get(csv_d['jamb_middlename'])
305            lastname = result.get(csv_d['jamb_lastname'])
306            perm_address = result.get(csv_d['perm_address'])
307            sid = self.generateStudentId('x')
308            students_folder.invokeFactory('Student', sid)
309            catalog_entry['id'] = sid
310            tr_count += 1
311            logger.info('%(total)s+%(tr_count)s: Creating Student with ID %(sid)s reg_no %(jamb_reg_no)s ' % vars())
312            student = getattr(self,sid)
313            student.manage_setLocalRoles(sid, ['Owner',])
314            student.invokeFactory('StudentApplication','application')
315            da = {'Title': 'Application Data'}
316            da["jamb_firstname"] = firstname
317            da["jamb_middlename"] = middlename
318            da["jamb_lastname"] = lastname
319            catalog_entry['entry_session'] = da["entry_session"] = self.getSessionId()[-2:]
320            catalog_entry['sex'] = sex = result.get(csv_d['jamb_sex']).startswith('F')
321            da_fields = ('jamb_reg_no',
322                         'jamb_sex',
323                         'jamb_state',
324                         'entry_mode',
325                         'app_email',
326                         )
327            for f in da_fields:
328                da[f] = result.get(csv_d[f])
329            catalog_entry['email'] = da['app_email']
330            catalog_entry['entry_mode'] = da['entry_mode']
331            app = student.application
332            app_doc = app.getContent()
333            app.getContent().edit(mapping=da)
334            picture ="%s/import/pictures/%s.jpg" % (i_home,jamb_reg_no)
335            app.manage_setLocalRoles(sid, ['Owner',])
336
337            picture_id = da['jamb_reg_no'].replace('/','_')
338            file = None
339            for ext in ('jpg','JPG'):
340                picture ="%s/import/pictures_admitted_latest/%s.%s" % (i_home,picture_id,ext)
341                if os.path.exists(picture):
342                    file = open(picture)
343                    break
344            if file is not None:
345
346                ## file conversion does not work
347                #img = PIL.Image.open(file)
348                #img.thumbnail((150,200),
349                #              resample=PIL.Image.ANTIALIAS)
350                #outfile = StringIO()
351                #img.save(outfile, format=img.format)
352
353                outfile = file.read()
354                app_doc.manage_addFile('passport',
355                                       file=outfile,
356                                       title="%s.jpg" % jamb_reg_no)
357            #wftool.doActionFor(app,'close')
358            dp = {}
359            dp['firstname'] = firstname
360            dp['middlename'] = middlename
361            dp['lastname'] = lastname
362            dp['email'] = da['app_email']
363            dp['sex'] = sex
364            dp['perm_address'] = perm_address
365            catalog_entry['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
366            student.invokeFactory('StudentPersonal','personal')
367            per = student.personal
368            per_doc = per.getContent()
369            per_doc.edit(mapping = dp)
370            per.manage_setLocalRoles(sid, ['Owner',])
371            wftool.doActionFor(student,'pume_pass')
372            wftool.doActionFor(student,'admit')
373            #
374            # Clearance
375            #
376            student.invokeFactory('StudentClearance','clearance')
377            #wftool.doActionFor(student.clearance,'open')
378            clearance = student.clearance
379            dc = {'Title': 'Clearance/Eligibility Record'}
380            clearance = student.clearance
381            date_str = result.get(csv_d['birthday'])
382            try:
383                date = DateTime.DateTime(date_str)
384            except:
385                #import pdb;pdb.set_trace()
386                date = None
387            dc['birthday'] = date
388            clearance.getContent().edit(mapping=dc)
389            clearance.manage_setLocalRoles(sid, ['Owner',])
390            #
391            # Study Course
392            #
393            student.invokeFactory('StudentStudyCourse','study_course')
394            study_course = student.study_course
395            dsc = {}
396            catalog_entry['level'] = dsc['current_level'] = levels.get(da['entry_mode'],'100')
397            #catalog_entry['level'] = dsc['current_level'] = '100'  # Attention: not for DE students
398            catalog_entry['session'] = dsc['current_session'] = da['entry_session']
399            catalog_entry['mode'] = dsc['current_mode'] = da['entry_mode']
400            catalog_entry['course'] = dsc['study_course'] = cert_id
401            catalog_entry['faculty'] = certificate['faculty']
402            catalog_entry['department'] = certificate['department']
403            catalog_entry['verdict'] = dsc['current_verdict'] = 'N/A'
404            catalog_entry['review_state'] = self.portal_workflow.getInfoFor(student,'review_state',None)
405            study_course.getContent().edit(mapping=dsc)
406            #import pdb;pdb.set_trace()
407            self.students_catalog.addRecord(**catalog_entry)
408            if tr_count > 1000:
409                if len(no_import) > 0:
410                    open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
411                             '\n'.join(no_import) + "\n")
412                    no_import = []
413                em = '%d transactions commited\n' % tr_count
414                transaction.commit()
415                logger.info(em)
416                total += tr_count
417                tr_count = 0
418        open("%s/import/%s_not_imported.csv" % (i_home,name),"a").write(
419                                                '\n'.join(no_import))
420        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
421    ###)
422
423    security.declareProtected(ModifyPortalContent,"transferStudents")###(
424    def transferStudents(self,filename):
425        """
426        load Interfaculty transferStudents Studentdata from CSV values.
427        """
428        import transaction
429        import random
430        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
431        pm = self.portal_membership
432        member = pm.getAuthenticatedMember()
433        logger = logging.getLogger('Students.StudentsFolder.transferStudents')
434        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
435        students_folder = self.portal_url.getPortalObject().campus.students
436        csv_fields = ('old_matric_no',
437                      'matric_no',
438                      'study_course',
439                      'current_mode',
440                      'current_level',
441                      )
442        tr_count = 0
443        total = 0
444        total_imported = 0
445        total_not_imported = 0
446        imported = []
447        not_imported = []
448        certs = {}
449        try:
450            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,filename),"rb"))
451        except:
452            logger.error('Error reading %s.csv' % filename)
453            return
454        start = True
455        for result in results:
456            total += 1
457            if start:
458                start = False
459                logger.info('%s starts import from %s.csv' % (member,filename))
460                import_keys = [k for k in result.keys() if not k.startswith('ignore')]
461                diff2schema = set(import_keys).difference(set(csv_fields))
462                if diff2schema:
463                    em = "not ignorable key(s) %s found in heading" % diff2schema
464                    return em
465                s = ','.join(['"%s"' % fn for fn in import_keys])
466                open("%s/import/%s_not_imported%s.csv" % (i_home,filename,current),"a").write(s + ',"Error"'+ '\n')
467                s = '"id",' + s
468                open("%s/import/%s_imported%s.csv" % (i_home,filename,current),"a").write(s + '\n')
469                format = ','.join(['"%%(%s)s"' % fn for fn in import_keys])
470                format_error = format + ',"%(Error)s"'
471                format = '"%(id)s",'+ format
472            old_matric_no = result.get('old_matric_no')
473            res = self.students_catalog(matric_no = old_matric_no)
474            result['id'] = "None"
475            if not res:
476                em = 'Student with matric_no %s not found' % old_matric_no
477                logger.info(em)
478                result['Error'] = "Student does not exist"
479                not_imported.append(format_error % result)
480                total_not_imported += 1
481                continue
482            student_brain = res[0]
483            student_object = getattr(students_folder,student_brain.id)
484            result['id'] = student_brain.id
485            cert_id = makeCertificateCode(result.get('study_course'))
486            if cert_id not in certs.keys():
487                res = self.portal_catalog(meta_type = "Certificate",id = cert_id)
488                if not res:
489                    em = 'No certificate with ID %s \n' % cert_id
490                    logger.info(em)
491                    result['Error'] = "No Certificate %s" % cert_id
492                    not_imported.append( format_error % result)
493                    total_not_imported += 1
494                    continue
495                cert = res[0]
496                cert_path = cert.getPath().split('/')
497                certificate = certs[cert_id] = {'faculty': cert_path[-4],
498                                     'department': cert_path[-3]}
499            cert_doc = certs[cert_id]
500            clearance = getattr(student_object,'clearance',None)
501            if clearance is None:
502                em = 'Student has no clearance object'
503                logger.info(em)
504                result['Error'] = em
505                not_imported.append( format_error % result)
506                total_not_imported += 1
507                continue
508            clearance_doc = clearance.getContent()
509            study_course = student_object.study_course
510            study_course_doc = study_course.getContent()
511            old_study_course = study_course_doc.study_course
512            old_current_level = study_course_doc.current_level
513            current_level = result.get('current_level',None)
514            new_study_course = result.get('study_course',None)
515            try:
516                icl = int(current_level)
517            except:
518                em = 'Invalid new level %s' % current_level
519                logger.info(em)
520                result['Error'] = em
521                not_imported.append( format_error % result)
522                total_not_imported += 1
523                continue
524            if icl == int(old_current_level) and old_study_course == new_study_course:
525                em = 'Already transferred'
526                logger.info(em)
527                result['Error'] = em
528                not_imported.append( format_error % result)
529                total_not_imported += 1
530                continue               
531            if study_course.objectIds():
532                em = 'Already registered level %s for %s, but is supposed to study %s at level %s' % (old_current_level,old_study_course,new_study_course,current_level)
533                logger.info(em)
534                result['Error'] = em
535                not_imported.append( format_error % result)
536                total_not_imported += 1
537                continue
538            #from pdb import set_trace; set_trace()
539            cd = {}
540            matric_no_history = getattr(clearance_doc,'matric_no_history',[])
541            if not matric_no_history:
542                matric_no_history = []
543            matric_no_history.append(old_matric_no)
544            cd['matric_no_history'] = matric_no_history
545            cd['matric_no'] = result.get('matric_no')
546            clearance_doc.edit(mapping = cd)
547            dsc = {}
548            study_course_history = getattr(study_course_doc,'study_course_history',[])
549            if not study_course_history:
550                study_course_history = []
551            study_course_history.append(old_study_course)
552            dsc['study_course_history'] = study_course_history
553            dsc['study_course'] = new_study_course
554            dsc['current_level'] = current_level
555            dsc['current_mode'] = result.get('current_mode')
556            study_course_doc.edit(mapping=dsc)
557            imported.append( format % result)
558            tr_count += 1
559            total_imported += 1
560            if tr_count > 1000:
561                if len(not_imported) > 0:
562                    open("%s/import/%s_not_imported%s.csv" % (i_home,filename,current),"a").write(
563                             '\n'.join(not_imported) + '\n')
564                    not_imported = []
565                if len(imported) > 0:
566                    open("%s/import/%s_imported%s.csv" % (i_home,filename,current),"a").write(
567                             '\n'.join(imported) + '\n')
568                    imported = []
569                em = '%d transactions committed\n' % (tr_count)
570                transaction.commit()
571                regs = []
572                logger.info(em)
573                tr_count = 0
574        if len(imported) > 0:
575            open("%s/import/%s_imported%s.csv" % (i_home,filename,current),"a").write(
576                                                '\n'.join(imported))
577        if len(not_imported) > 0:
578            open("%s/import/%s_not_imported%s.csv" % (i_home,filename,current),"a").write(
579                                                '\n'.join(not_imported))
580        em = "Imported: %d, not imported: %d of total %d" % (total_imported,total_not_imported,total)
581        logger.info(em)
582        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
583    ###)
584
585    security.declareProtected(ModifyPortalContent,"importReturningStudents")###(
586    def importReturningStudents(self):
587        """load Returning Studentdata from CSV values"""
588        import transaction
589        import random
590        #from pdb import set_trace
591        wftool = self.portal_workflow
592        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
593        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
594        students_folder = self.portal_url.getPortalObject().campus.students
595        tr_count = 1
596        total = 0
597        #name = 'pume_results'
598        name = 'Returning'
599        table = self.returning_import
600        no_import = []
601        imported = []
602        logger = logging.getLogger('Students.StudentsFolder.importReturningStudents')
603        try:
604            returning = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
605        except:
606            logger.error('Error reading %s.csv' % name)
607            return
608        l = self.portal_catalog({'meta_type': "Certificate"})
609        certs = {}
610        cert_docs = {}
611        for f in l:
612            certs[f.getId] = f.getObject().getContent()
613        start = True
614        res = table()
615        regs = []
616        if len(res) > 0:
617            regs = [s.matric_no for s in res]
618        #import pdb;pdb.set_trace()
619        for student in returning:
620            if start:
621                start = False
622                logger.info('Start loading from %s.csv' % name)
623                s = ','.join(['"%s"' % fn for fn in student.keys()])
624                imported.append(s)
625                no_import.append('%s,"Error"' % s)
626                format = ','.join(['"%%(%s)s"' % fn for fn in student.keys()])
627                format_error = format + ',"%(Error)s"'
628                no_certificate = "no certificate %s" % format
629            student['matric_no'] = matric_no = student.get('matric_no').upper()
630            student['Mode_of_Entry'] = entry_mode = student.get('Mode of Entry').upper()
631            student['Permanent_Address'] = perm_address = student.get('Permanent Address')
632            if matric_no == '':
633                student['Error'] = "Empty matric_no"
634                no_import.append( format_error % student)
635                continue
636            if matric_no in regs or self.returning_import(matric_no = matric_no):
637                student['Error'] = "Duplicate"
638                no_import.append( format_error % student)
639                continue
640            cert_id = makeCertificateCode(student.get('Coursemajorcode'))
641            if cert_id not in certs.keys():
642                student['Error'] = "No Certificate %s" % cert_id
643                no_import.append( format_error % student)
644                continue
645            try:
646                table.addRecord(**student)
647            except ValueError:
648                student['Error'] = "Duplicate"
649                no_import.append( format_error % student)
650                continue
651            regs.append(student.get('matric_no'))
652            imported.append(format % student)
653            tr_count += 1
654            if tr_count > 1000:
655                if len(no_import) > 0:
656                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
657                             '\n'.join(no_import) + '\n')
658                    no_import = []
659                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
660                                            '\n'.join(no_import) + "\n")
661                imported = []
662                em = '%d transactions commited total %s\n' % (tr_count,total)
663                transaction.commit()
664                regs = []
665                logger.info(em)
666                total += tr_count
667                tr_count = 0
668        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
669                                            '\n'.join(imported))
670        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
671                                                '\n'.join(no_import))
672        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
673    ###)
674
675    security.declareProtected(ModifyPortalContent,"fixAllNames")###(
676    def fixAllNames(self):
677        "fix all students names"
678        import transaction
679        response = self.REQUEST.RESPONSE
680        logger = logging.getLogger('fixAllNames')
681        logger.info('Start')
682        students = self.portal_catalog(portal_type='Student')
683        count = 0
684        total = 0
685        for student in students:
686            scat_res = self.students_catalog(id = student.getId)
687            if not scat_res:
688                self.students_catalog.addRecord(id = student.getId)
689                scat_res = self.students_catalog(id = student.getId)
690            student_entry = scat_res[0]
691            old_new = self.fixName(student,student_entry)
692            count += 1
693            response_write(response,'"%d","%s",%s' % (count + total,student_entry.id,old_new))
694            if count > 2000:
695                transaction.commit()
696                logger.info("%d transactions commited" % count)
697                total += count
698                count = 0
699    ###)
700
701    security.declareProtected(ModifyPortalContent,"fixName")###(
702    def fixName(self,student_brain, student_entry):
703        "fix the name of a student"
704        fix = "first"
705        if student_entry.get('name_fixed',None) == fix:
706            return "Name already fixed"
707        student_id = student_entry.id
708        new_student = student_entry.jamb_reg_no.startswith('6')
709        student_obj = student_brain.getObject()
710        personal = getattr(student_obj,'personal',None)
711        invalid = ''
712        if personal is None:
713            return '"%s","Returning","%s","%s"' % (invalid,student_entry.name,"not logged in")
714        per_doc = personal.getContent()
715        old_first = per_doc.firstname
716        old_middle = per_doc.middlename
717        old_last = per_doc.lastname
718        new_first = ''
719        new_middle = ''
720        new_last = ''
721        if new_student:
722            if not old_first and not old_middle and old_last:
723                new_names = [n.capitalize() for n in old_last.split()]
724                if len(new_names) > 1:
725                    old_first = new_names[0]
726                    old_last = new_names[-1]
727                    old_middle = ' '.join(new_names[1:-1])
728                else:
729                    old_last = new_names[0]
730                    old_first = ''
731                    old_middle = ''
732            if old_first:
733                new_first = old_first
734            if old_middle:
735                new_middle = old_middle
736            if old_last:
737                new_last = old_last
738            if old_first.find('<') != -1 or\
739               old_first.find('>') != -1 or\
740               old_middle.find('<') != -1 or\
741               old_middle.find('>') != -1 or\
742               old_last.find('<') != -1 or\
743               old_last.find('>') != -1:
744                   invalid = "invalid characters"
745        else:
746            new_first = old_first
747            if new_first.strip() == '-':
748                new_first = ''
749            new_middle = old_middle
750            if new_middle.strip() == '-':
751                new_middle = ''
752            new_last = old_last
753            if new_last.strip() == '-':
754                new_last = ''
755        name = "%(new_first)s %(new_middle)s %(new_last)s" % vars()
756        if new_student:
757            text = "New"
758        else:
759            text = "Returning"
760        old_new = '"%s","%s","%s","%s"' % (invalid,text,
761                                           student_entry.name,
762                                           name)
763        if not invalid:
764            self.students_catalog.modifyRecord(id = student_id,
765                                      name_fixed = fix,
766                                      name = name)
767            per_doc.edit(mapping = {'firstname' : new_first,
768                                'middlename' : new_middle,
769                                'lastname' : new_last,
770                                })
771        return old_new
772    ###)
773
774    security.declareProtected(ModifyPortalContent,"updateReturningStudents")###(
775    def updateReturningStudents(self):
776        """load and overwrite Returning Student Data from CSV values"""
777        import transaction
778        import random
779        #from pdb import set_trace
780        wftool = self.portal_workflow
781        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
782        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
783        students_folder = self.portal_url.getPortalObject().campus.students
784        tr_count = 1
785        total = 0
786        #name = 'pume_results'
787        name = 'Returning_update'
788        table = self.returning_import
789        no_import = []
790        imported = []
791        logger = logging.getLogger('Students.StudentsFolder.updateReturningStudents')
792        try:
793            returning = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
794        except:
795            logger.error('Error reading %s.csv' % name)
796            return
797        l = self.portal_catalog({'meta_type': "Certificate"})
798        certs = {}
799        cert_docs = {}
800        for f in l:
801            certs[f.getId] = f.getObject().getContent()
802        start = True
803        res = table()
804        regs = []
805        if len(res) > 0:
806            regs = [s.matric_no for s in res]
807        for student in returning:
808            if start:
809                start = False
810                logger.info('Start loading from %s.csv' % name)
811                s = ','.join(['"%s"' % fn for fn in student.keys()])
812                imported.append(s)
813                no_import.append('%s,"Error"' % s)
814                format = ','.join(['"%%(%s)s"' % fn for fn in student.keys()])
815                format_error = format + ',"%(Error)s"'
816                no_certificate = "no certificate %s" % format
817            matric_no = student.get('matric_no').upper()
818            student['matric_no'] = matric_no
819            if matric_no == '':
820                student['Error'] = "Empty matric_no"
821                no_import.append( format_error % student)
822                continue
823#            if matric_no in regs or self.returning_import(matric_no = matric_no):
824#                student['Error'] = "Duplicate"
825#                no_import.append( format_error % student)
826#                continue
827#            cert_id = makeCertificateCode(student.get('Coursemajorcode'))
828#            if cert_id not in certs.keys():
829#                student['Error'] = "No Certificate %s" % cert_id
830#                no_import.append( format_error % student)
831#                continue
832            try:
833                table.modifyRecord(**student)
834            except KeyError:
835                #import pdb;pdb.set_trace()
836                student['Error'] = "no Student found to update"
837                no_import.append( format_error % student)
838                continue
839            #s = self.students_catalog(matric_no=matric_no)
840            #if s:
841            #    level = "%s" % (int(student.get('Level')) + 100)
842            #    self.students_catalog.modifyRecord(id = s[0].id,
843            #                                           level=level)
844
845            regs.append(student.get('matric_no'))
846            imported.append(format % student)
847            tr_count += 1
848            if tr_count > 1000:
849                if len(no_import) > 0:
850                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
851                             '\n'.join(no_import) + '\n')
852                    no_import = []
853                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
854                                            '\n'.join(no_import) + "\n")
855                imported = []
856                em = '%d transactions commited total %s\n' % (tr_count,total)
857                transaction.commit()
858                regs = []
859                logger.info(em)
860                total += tr_count
861                tr_count = 0
862        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
863                                            '\n'.join(imported))
864        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
865                                                '\n'.join(no_import))
866        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
867    ###)
868
869    security.declareProtected(ModifyPortalContent,"importResults")###(
870    def importResults(self):
871        """load Returning Students Results from CSV"""
872        import transaction
873        import random
874        #from pdb import set_trace
875        wftool = self.portal_workflow
876        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
877        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
878        students_folder = self.portal_url.getPortalObject().campus.students
879        tr_count = 1
880        total = 0
881        #name = 'pume_results'
882        name = 'Results'
883        table = self.results_import
884        no_import = []
885        imported = []
886        logger = logging.getLogger('Students.StudentsFolder.importResults')
887        try:
888            results = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
889        except:
890            logger.error('Error reading %s.csv' % name)
891            return
892        l = self.portal_catalog({'meta_type': "Course"})
893        courses = [f.getId for f in l]
894        start = True
895        res = table()
896        regs = []
897        if len(res) > 0:
898            regs = [s.key for s in res]
899        no_course = []
900        no_course_list = []
901        course_count = 0
902        for result in results:
903            if start:
904                start = False
905                logger.info('Start loading from %s.csv' % name)
906                s = ','.join(['"%s"' % fn for fn in result.keys()])
907                imported.append(s)
908                no_import.append('%s,"Error"' % s)
909                format = ','.join(['"%%(%s)s"' % fn for fn in result.keys()])
910                format_error = format + ',"%(Error)s"'
911                no_certificate = "no certificate %s" % format
912            course_id = result.get('CosCode')
913            if not course_id:
914                course_id = 'N/A'
915                result['CosCode'] = course_id
916            matric_no = result.get('matric_no').upper()
917            result['matric_no'] = matric_no
918            key = matric_no+course_id
919            if matric_no == '':
920                result['Error'] = "Empty matric_no"
921                no_import.append( format_error % result)
922                continue
923            if key in regs or self.results_import(key = key):
924                result['Error'] = "Duplicate"
925                no_import.append( format_error % result)
926                continue
927            if course_id not in courses:
928                if course_id not in no_course:
929                    course_count +=1
930                    no_course.append(course_id)
931                    no_course_list.append('"%s"' % course_id)
932                    #result['Error'] = "No Course"
933                    #logger.info(format_error % result)
934
935            result['key'] = key
936            try:
937                table.addRecord(**result)
938            except ValueError:
939                #import pdb;pdb.set_trace()
940                result['Error'] = "Duplicate"
941                no_import.append( format_error % result)
942                continue
943
944            regs.append(key)
945            imported.append(format % result)
946            tr_count += 1
947            if tr_count > 1000:
948                if len(no_import) > 0:
949                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
950                             '\n'.join(no_import)+'\n')
951                    no_import = []
952                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
953                                            '\n'.join(imported) + '\n')
954                imported = []
955                if no_course_list:
956                    open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
957                                            '\n'.join(no_course_list) + '\n')
958                    no_course_list = []
959                em = '%d transactions commited total %s\n courses not found %s' % (tr_count,total,course_count)
960                transaction.commit()
961                logger.info(em)
962                regs = []
963                total += tr_count
964                tr_count = 0
965        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
966                                            '\n'.join(imported))
967        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
968                                                '\n'.join(no_import))
969        if no_course_list:
970            open("%s/import/%sno_courses%s.csv" % (i_home,name,current),"a").write(
971                                    '\n'.join(no_course_list))
972        em = '%d transactions commited total %s\n courses not found %s' % (tr_count,total,course_count)
973        logger.info(em)
974        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
975    ###)
976
977    security.declareProtected(ModifyPortalContent,"updateStudyCourse")###(
978    def updateStudyCourse(self):
979        """update StudyCourse from CSV values"""
980        import transaction
981        import random
982        from pdb import set_trace
983        wftool = self.portal_workflow
984        #students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
985        students_folder = self.portal_url.getPortalObject().campus.students
986        csv_d = {'jamb_reg_no': "RegNumber",
987                 'jamb_lastname': "Name",
988                 'session': "Session",
989                 'pume_tot_score': "PUME SCORE",
990                 'jamb_score': "JambScore",
991                 'jamb_sex': "Sex",
992                 'jamb_state': "State",
993##                 'jamb_first_cos': "AdminCourse",
994                 'faculty': "AdminFaculty",
995                 'course_code': "AdmitCoscode",
996                 'stud_status':"AdmitStatus",
997                 'department': "AdmitDept",
998                 'jamb_lga': "LGA",
999                 'app_email': "email",
1000                 'app_mobile': "PhoneNumbers",
1001                 }
1002        csv_fields = [f[1] for f in csv_d.items()]
1003        tr_count = 0
1004        total = 0
1005        #name = 'pume_results'
1006        name = 'StudyCourseChange'
1007        no_import = []
1008        s = ','.join(['"%s"' % fn for fn in csv_fields])
1009        no_import.append('"Error",%s' % s)
1010        format = '"%(Error)s",' + ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
1011        no_certificate = "no certificate %s" % format
1012        open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
1013                    '\n'.join(no_import))
1014        logger = logging.getLogger('Students.StudentsFolder.updateStudyCourse')
1015        logger.info('Start loading from %s.csv' % name)
1016        l = self.portal_catalog({'meta_type': "Certificate"})
1017        try:
1018            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
1019        except:
1020            logger.error('Error reading %s.csv' % name)
1021            return
1022        for jamb in result:
1023            jamb['Error'] = "Processing "
1024            logger.info(format % jamb)
1025            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
1026            res = self.portal_catalog({'portal_type': "StudentApplication",
1027                                     'SearchableText': jamb_reg_no })
1028            if not res:
1029                em = 'Student with jamb_reg_no %s does not exists\n' % jamb_reg_no
1030                logger.info(em)
1031                jamb['Error'] = "Student does not exist"
1032                no_import.append(format % jamb)
1033                continue
1034            sid = res[0].getPath().split('/')[-2]
1035            cert_id = makeCertificateCode(jamb.get(csv_d['course_code']))
1036            res = self.portal_catalog(portal_type = "Certificate", id = cert_id)
1037            if not res:
1038                em = 'No Certificate with ID %s \n' % cert_id
1039                logger.info(em)
1040                jamb['Error'] = "No Certificate %s" % cert_id
1041                no_import.append( format % jamb)
1042                continue
1043            cert_brain = res[0]
1044            catalog_entry = {}
1045            student = getattr(self,sid)
1046            #
1047            # Study Course
1048            #
1049            study_course = student.study_course
1050            dsc = {}
1051            cert_pl = cert_brain.getPath().split('/')
1052            catalog_entry['id'] = sid
1053            catalog_entry['faculty'] = cert_pl[-4]
1054            catalog_entry['department'] = cert_pl[-3]
1055            catalog_entry['course'] = cert_id
1056            dsc['study_course'] = cert_id
1057            study_course.getContent().edit(mapping=dsc)
1058            self.students_catalog.modifyRecord(**catalog_entry)
1059            if tr_count > 10:
1060                if len(no_import) > 1:
1061                    open("%s/import/%s_not_imported.csv" % (i_home,name),"w+").write(
1062                             '\n'.join(no_import))
1063                    no_import = []
1064                em = '%d transactions commited\n' % tr_count
1065                transaction.commit()
1066                logger.info(em)
1067                total += tr_count
1068                tr_count = 0
1069            tr_count += 1
1070        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
1071    ###)
1072
1073    security.declareProtected(View,"fixOwnership") ###(
1074    def fixOwnership(self):
1075        """fix Ownership"""
1076        for s in self.portal_catalog(meta_type = 'Student'):
1077            student = s.getObject()
1078            sid = s.getId
1079            import pdb;pdb.set_trace()
1080            student.application.manage_setLocalRoles(sid, ['Owner',])
1081            student.personal.manage_setLocalRoles(sid, ['Owner',])
1082    ###)
1083
1084    security.declareProtected(View,"Title") ###(
1085    def Title(self):
1086        """compose title"""
1087        return "Student Section"
1088    ###)
1089
1090    def generateStudentId(self,letter,students = None): ###(
1091        import random
1092        r = random
1093        if students is None:
1094            students = self.portal_url.getPortalObject().campus.students
1095        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
1096            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
1097        sid = "%c%d" % (letter,r.randint(99999,1000000))
1098        while hasattr(students, sid):
1099            sid = "%c%d" % (letter,r.randint(99999,1000000))
1100        return sid
1101        #return "%c%d" % (r.choice('ABCDEFGHKLMNPQRSTUVWXY'),r.randint(99999,1000000))
1102    ###)
1103
1104InitializeClass(StudentsFolder)
1105
1106def addStudentsFolder(container, id, REQUEST=None, **kw): ###(
1107    """Add a Student."""
1108    ob = StudentsFolder(id, **kw)
1109    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1110    ###)
1111
1112###)
1113
1114class Student(CPSDocument): ###(
1115    """
1116    WAeUP Student container for the various student data
1117    """
1118    meta_type = 'Student'
1119    portal_type = meta_type
1120    security = ClassSecurityInfo()
1121
1122    security.declareProtected(View,"Title")
1123    def Title(self):
1124        """compose title"""
1125        reg_nr = self.getId()[1:]
1126        data = getattr(self,'personal',None)
1127        if data:
1128            content = data.getContent()
1129            return "%s %s %s" % (content.firstname,content.middlename,content.lastname)
1130        data = getattr(self,'application',None)
1131        if data:
1132            content = data.getContent()
1133            return "%s" % (content.jamb_lastname)
1134        return self.title
1135
1136    security.declarePrivate('makeStudentMember') ###(
1137    def makeStudentMember(self,sid,password='uNsEt'):
1138        """make the student a member"""
1139        membership = self.portal_membership
1140        membership.addMember(sid,
1141                             password ,
1142                             roles=('Member',
1143                                     'Student',
1144                                     ),
1145                             domains='',
1146                             properties = {'memberareaCreationFlag': False,
1147                                           'homeless': True},)
1148        member = membership.getMemberById(sid)
1149        self.portal_registration.afterAdd(member, sid, password, None)
1150        self.manage_setLocalRoles(sid, ['Owner',])
1151
1152###)
1153
1154    security.declareProtected(View,'createSubObjects') ###(
1155    def createSubObjects(self):
1156        """make the student a member"""
1157        dp = {'Title': 'Personal Data'}
1158        app_doc = self.application.getContent()
1159        names = app_doc.jamb_lastname.split()
1160        if len(names) == 3:
1161            dp['firstname'] = names[0].capitalize()
1162            dp['middlename'] = names[1].capitalize()
1163            dp['lastname'] = names[2].capitalize()
1164        elif len(names) == 2:
1165            dp['firstname'] = names[0].capitalize()
1166            dp['lastname'] = names[1].capitalize()
1167        else:
1168            dp['lastname'] = app_doc.jamb_lastname
1169        dp['sex'] = app_doc.jamb_sex == 'F'
1170        dp['lga'] = "%s/%s" % (app_doc.jamb_state,app_doc.jamb_lga )
1171        proxy = self.aq_parent
1172        proxy.invokeFactory('StudentPersonal','personal')
1173        per = proxy.personal
1174        per_doc = per.getContent()
1175        per_doc.edit(mapping = dp)
1176        per.manage_setLocalRoles(proxy.getId(), ['Owner',])
1177        #self.portal_workflow.doActionFor(per,'open',dest_container=per)
1178
1179###)
1180
1181InitializeClass(Student)
1182
1183def addStudent(container, id, REQUEST=None, **kw):
1184    """Add a Student."""
1185    ob = Student(id, **kw)
1186    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1187
1188###)
1189
1190class StudentAccommodation(CPSDocument): ###(
1191    """
1192    WAeUP Student container for the various student data
1193    """
1194    meta_type = 'StudentAccommodation'
1195    portal_type = meta_type
1196    security = ClassSecurityInfo()
1197
1198    security.declareProtected(View,"Title")
1199    def Title(self):
1200        """compose title"""
1201        content = self.getContent()
1202        #return "Accommodation Data for %s %s" % (content.firstname,content.lastname)
1203        return "Accommodation Data for Session %s" % content.session
1204
1205
1206InitializeClass(StudentAccommodation)
1207
1208def addStudentAccommodation(container, id, REQUEST=None, **kw):
1209    """Add a Students personal data."""
1210    ob = StudentAccommodation(id, **kw)
1211    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1212
1213###)
1214
1215class StudentPersonal(CPSDocument): ###(
1216    """
1217    WAeUP Student container for the various student data
1218    """
1219    meta_type = 'StudentPersonal'
1220    portal_type = meta_type
1221    security = ClassSecurityInfo()
1222
1223    security.declareProtected(View,"Title")
1224    def Title(self):
1225        """compose title"""
1226        content = self.getContent()
1227        #return "Personal Data for %s %s" % (content.firstname,content.lastname)
1228        return "Personal Data"
1229
1230
1231InitializeClass(StudentPersonal)
1232
1233def addStudentPersonal(container, id, REQUEST=None, **kw):
1234    """Add a Students personal data."""
1235    ob = StudentPersonal(id, **kw)
1236    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1237
1238###)
1239
1240class StudentClearance(CPSDocument): ###(
1241    """
1242    WAeUP Student container for the various student data
1243    """
1244    meta_type = 'StudentClearance'
1245    portal_type = meta_type
1246    security = ClassSecurityInfo()
1247
1248    security.declareProtected(View,"Title")
1249    def Title(self):
1250        """compose title"""
1251        content = self.getContent()
1252        #return "Clearance/Eligibility Record for %s %s" % (content.firstname,content.lastname)
1253        return "Clearance/Eligibility Record"
1254
1255
1256InitializeClass(StudentClearance)
1257
1258def addStudentClearance(container, id, REQUEST=None, **kw):
1259    """Add a Students personal data."""
1260    ob = StudentClearance(id, **kw)
1261    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1262
1263###)
1264
1265class StudentStudyLevel(CPSDocument): ###(
1266    """
1267    WAeUP Student container for the various student data
1268    """
1269    meta_type = 'StudentStudyLevel'
1270    portal_type = meta_type
1271    security = ClassSecurityInfo()
1272
1273    security.declareProtected(View,"Title")
1274    def Title(self):
1275        """compose title"""
1276        return "Level %s" % self.aq_parent.getId()
1277
1278    def create_course_results(self,cert_id,current_level): ###(
1279        "create all courses in a level"
1280        aq_portal = self.portal_catalog.evalAdvancedQuery
1281        res = self.portal_catalog(portal_type="Certificate", id = cert_id)
1282        l = []
1283        import transaction
1284        if res:
1285            cert = res[0]
1286            path = cert.getPath()
1287            query = Eq("path","%s/%s" % (path,current_level)) &\
1288                    Eq('portal_type','CertificateCourse')
1289            courses = aq_portal(query)
1290            #from pdb import set_trace;set_trace()
1291            self_proxy = self.aq_parent
1292            for c in courses:
1293                d = self.getCourseInfo(c.getId)
1294                cr_id = self_proxy.invokeFactory('StudentCourseResult',c.getId)
1295                course_result = getattr(self_proxy,cr_id)
1296                self.portal_workflow.doActionFor(course_result,'open')
1297                d['core_or_elective'] = getattr(c.getObject().getContent(),'core_or_elective')
1298                course_result.getContent().edit(mapping=d)
1299                #transaction.commit()
1300    ###)
1301
1302InitializeClass(StudentStudyLevel)
1303
1304def addStudentStudyLevel(container, id, REQUEST=None, **kw):
1305    """Add a Students personal data."""
1306    ob = StudentStudyLevel(id, **kw)
1307    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1308
1309###)
1310
1311class StudentStudyCourse(CPSDocument): ###(
1312    """
1313    WAeUP Student container for the various student data
1314    """
1315    meta_type = 'StudentStudyCourse'
1316    portal_type = meta_type
1317    security = ClassSecurityInfo()
1318
1319    security.declareProtected(View,"Title")
1320    def Title(self):
1321        """compose title"""
1322        content = self.getContent()
1323        return "Study Course"
1324
1325
1326InitializeClass(StudentStudyCourse)
1327
1328def addStudentStudyCourse(container, id, REQUEST=None, **kw):
1329    """Add a Students personal data."""
1330    ob = StudentStudyCourse(id, **kw)
1331    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1332
1333###)
1334
1335class StudentApplication(CPSDocument): ###(
1336    """
1337    WAeUP Student container for the various student data
1338    """
1339    meta_type = 'StudentApplication'
1340    portal_type = meta_type
1341    security = ClassSecurityInfo()
1342
1343    security.declareProtected(View,"Title")
1344    def Title(self):
1345        """compose title"""
1346        return "Application Data"
1347
1348
1349InitializeClass(StudentApplication)
1350
1351def addStudentApplication(container, id, REQUEST=None, **kw):
1352    """Add a Students eligibility data."""
1353    ob = StudentApplication(id, **kw)
1354    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1355###)
1356
1357class StudentPume(CPSDocument): ###(
1358    """
1359    WAeUP Student container for the various student data
1360    """
1361    meta_type = 'StudentPume'
1362    portal_type = meta_type
1363    security = ClassSecurityInfo()
1364
1365    security.declareProtected(View,"Title")
1366    def Title(self):
1367        """compose title"""
1368        return "PUME Results"
1369
1370
1371InitializeClass(StudentPume)
1372
1373def addStudentPume(container, id, REQUEST=None, **kw):
1374    """Add a Students PUME data."""
1375    ob = StudentPume(id, **kw)
1376    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1377###)
1378
1379##class StudentSemester(CPSDocument): ###(
1380##    """
1381##    WAeUP StudentSemester containing the courses and students
1382##    """
1383##    meta_type = 'StudentSemester'
1384##    portal_type = meta_type
1385##    security = ClassSecurityInfo()
1386##
1387##InitializeClass(StudentSemester)
1388##
1389##def addStudentSemester(container, id, REQUEST=None, **kw):
1390##    """Add a StudentSemester."""
1391##    ob = StudentSemester(id, **kw)
1392##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1393##
1394#####)
1395
1396##class Semester(CPSDocument): ###(
1397##    """
1398##    WAeUP Semester containing the courses and students
1399##    """
1400##    meta_type = 'Semester'
1401##    portal_type = meta_type
1402##    security = ClassSecurityInfo()
1403##
1404##InitializeClass(Semester)
1405##
1406##def addSemester(container, id, REQUEST=None, **kw):
1407##    """Add a Semester."""
1408##    ob = Semester(id, **kw)
1409##    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1410##
1411#####)
1412
1413class StudentCourseResult(CPSDocument): ###(
1414    """
1415    WAeUP StudentCourseResult
1416    """
1417    meta_type = 'StudentCourseResult'
1418    portal_type = meta_type
1419    security = ClassSecurityInfo()
1420
1421    def getCourseEntry(self,cid):
1422        res = self.portal_catalog({'meta_type': "Course",
1423                                           'id': cid})
1424        if res:
1425            return res[-1]
1426        else:
1427            return None
1428
1429    security.declareProtected(View,"Title")
1430    def Title(self):
1431        """compose title"""
1432        cid = self.aq_parent.getId()
1433        ce = self.getCourseEntry(cid)
1434        if ce:
1435            return "%s" % ce.Title
1436        return "No course with id %s" % cid
1437
1438InitializeClass(StudentCourseResult)
1439
1440def addStudentCourseResult(container, id, REQUEST=None, **kw):
1441    """Add a StudentCourseResult."""
1442    ob = StudentCourseResult(id, **kw)
1443    return CPSBase_adder(container, ob, REQUEST=REQUEST)
1444###)
1445
1446# Backward Compatibility StudyLevel
1447
1448from Products.WAeUP_SRP.Academics import StudyLevel
1449
1450from Products.WAeUP_SRP.Academics import addStudyLevel
1451
Note: See TracBrowser for help on using the repository browser.