Changeset 757 for WAeUP_SRP/trunk


Ignore:
Timestamp:
26 Oct 2006, 19:12:33 (18 years ago)
Author:
joachim
Message:

first Pume results import.
which is actually an extended Jamb import. An Pume Object is not created.

Location:
WAeUP_SRP/trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • WAeUP_SRP/trunk/Students.py

    r746 r757  
    235235        import transaction
    236236        import random
     237        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
     238        csv_d = {'jamb_reg_no': "Matnumber",
     239                 'jamb_lastname': "Surname",
     240                 'pume_options': "Options",
     241                 'session': "Session",
     242                 'days': "Days",
     243                 'response': "Responce",
     244                 'right': "Right",
     245                 'wrong': "Wrong",
     246                 'pume_eng_score': "EngScore",
     247                 'pume_tot_score': "GenScore",
     248                 'batch': "Batch",
     249                 'serial': "SerialNo",
     250                 'jamb_score': "JambScore",
     251                 'omitted':"Omitted",
     252                 'search_key': "SearchKey",
     253                 'jamb_sex': "Sex",
     254                 'fac1': "Fac1",
     255                 'fac2': "Fac2",
     256                 'jamb_first_cos': "CourseofStudy",
     257                 'stud_status':"StudStatus",
     258                 'registered': "Registered",
     259                 'jamb_state': "State",
     260                 'eng_fail': "EngFail",
     261                 'gen_fail': "GenFail",
     262                 'un_ans_eng': "UnAnsEng",
     263                 'un_ans_eng': "UnAnsGen",
     264                 'total_ans': "TotalUnAns",
     265                 'dept': "Dept",
     266                 'jamb_second_cos': "Course2",
     267                 'jamb_third_cos': "course3",
     268                 }
     269        csv_fields = [f[1] for f in csv_d.items()]
    237270        tr_count = 0
    238271        name = 'pume_results'
    239         no_import = False
    240         if not no_import:
    241             no_import = open("%s/import/%s_not_imported.csv" % (i_home,name),"w")
    242             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')
     272        no_import = []
     273        s = ','.join(['"(%s)"' % fn for fn in csv_fields])
     274        no_import.append('%s\n' % s)
    243275        logger = logging.getLogger('%s_import' % name)
    244276        logger.info('Start loading from %s.csv' % name)
    245         pwlist  = []
    246         pwlist.append('"student_id","firstname","middlename","lastname","jamb_reg_no","access_code"')
    247         pwl_template = Template('"$student_id","$firstname","$middlename","$lastname","$jamb_reg_no","$access_code"')
    248         students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
    249277        try:
    250             students = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
     278            result = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
    251279        except:
    252280            logger.error('Error reading %s.csv' % name)
    253281            return
    254         l = self.portal_catalog({'meta_type': "StudentClearance",})
    255         matrics = []
    256         for s in l:
    257             matrics.append(s.getObject().getContent().matric_no)
    258         print matrics
    259         l = self.portal_catalog({'meta_type': "Certificate"})
    260         certs = {}
    261         for c in l:
    262             ca,ac,fa,dep_id,co,certcode = c.relative_path.split('/')
    263             cid = "%(dep_id)s_%(certcode)s" % vars()
    264             certs[cid] = c.getObject()
    265         for student in students:
    266             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)
    267             sid = student.get('MatricNo')
    268             if sid == "":
    269                 em = 'Empty MatricNo\n'
     282        for jamb in result:
     283            format = ','.join(['"%%(%s)s"' % fn for fn in csv_fields])
     284            processing = "processing %s" % format
     285            logger.info(processing % jamb)
     286            jamb_reg_no = jamb.get(csv_d['jamb_reg_no'])
     287            res = self.portal_catalog({'meta_type': "StudentApplication",
     288                                     'jamb_reg_no': jamb_reg_no })
     289            if res:
     290                em = 'Student with REG-NO %s already exists\n' % jamb_reg_no
    270291                logger.info(em)
    271                 no_import.write(em)
    272                 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)
     292                no_import.append(em)
     293                no_import.append(format % jamb)
    273294                continue
    274             certcode = makeCertificateCode(student.get('CourseMajor'))
    275             dep_id = student.get('Dept')
    276             fac_id = student.get('Faculty')
    277             cid = "%(dep_id)s_%(certcode)s" % vars()
    278             if cid not in certs.keys():
    279                 em = 'Certificate with ID %s %s not found\n' % (certcode, student.get('CourseMajor'))
    280                 logger.info(em)
    281                 no_import.write(em)
    282                 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)
    283                 continue
    284             certificate_doc = certs[cid].getContent()
    285             level = student.get('StudentLevel')
    286             try:
    287                 int(level)
    288             except:
    289                 em = 'Student with ID %(MatricNo)s StudentLevel is empty\n' % student
    290                 logger.info(em)
    291                 no_import.write(em)
    292                 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)
    293                 continue
    294             matric_no = student.get('MatricNo')
    295             if matric_no not in matrics:
    296                 matrics.append(matric_no)
    297                 sid = self.generateStudentId(student.get('Lastname')[0])
    298                 #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
    299                 students_folder.invokeFactory('Student', sid)
    300                 logger.info('%(tr_count)s: Creating Student with ID %(sid)s Matric_no %(matric_no)s ' % vars())
    301                 student_obj = getattr(self,sid)
    302                 access_code = "%d" % random.randint(1000000000,9999999999)
    303                 student_obj.getContent().addMember(sid,access_code ,)
    304                 pwl_dict = {'student_id': sid,'access_code':access_code}
    305                 student_obj.invokeFactory('StudentApplication','application')
    306                 application = student_obj.application
    307                 da = {'Title': 'Application Data'}
    308                 student_obj.invokeFactory('StudentPersonal','personal')
    309                 da['jamb_reg_no'] = student.get('EntryRegNo')
    310                 personal = student_obj.personal
    311                 dp = {'Title': 'Personal Data'}
    312                 student_obj.invokeFactory('StudentClearance','clearance')
    313                 clearance = student_obj.clearance
    314                 dc = {'Title': 'Clearance Data'}
    315                 dc['matric_no'] = matric_no
    316                 state = student.get('State')
    317                 lga = student.get('LGA')
    318                 if state and lga:
    319                     lga =  state + ' / ' + lga
    320                 else:
    321                     lga = "None"
    322                 dc['lga'] = lga
    323                 dc['nationality'] = student.get('Nationality')
    324                 dc['email'] = student.get('Emailaddress')
    325                 dp['firstname'] = student.get('FirstName')
    326                 dp['middlename'] = student.get('MiddleName')
    327                 dp['lastname'] = student.get('Lastname')
    328                 dp['former_surname'] = student.get('FormerSurname')
    329                 dp['sex'] = student.get('Sex') == 'F'
    330                 dp['perm_address'] = student.get('PermanentAddress')
    331                 dp['perm_city'] = student.get('PermanentAddressCity')
    332                 dp['campus_address'] = student.get('CampusAddress')
    333                 dp['phone'] = student.get('PhoneNumber')
    334                 application.getContent().edit(mapping=da)
    335                 personal.getContent().edit(mapping=dp)
    336                 clearance.getContent().edit(mapping=dc)
    337                 #
    338                 # Study Course
    339                 #
    340                 student_obj.invokeFactory('StudentStudyCourse','study_course')
    341                 studycourse = student_obj.study_course
    342                 dsc = {}
    343                 from_certificate = ['title',
    344                                    'max_elect',
    345                                    'max_pass',
    346                                    'n_core',
    347                                    'nr_years',
    348                                    'probation_credits',
    349                                    'promotion_credits',
    350                                    'start_level',
    351                                   ]
    352                 for f in from_certificate:
    353                     dsc[f] = getattr(certificate_doc,f)
    354                 dsc['faculty'] = fac_id
    355                 dsc['department'] = dep_id
    356                 dsc['study_course'] = certcode
    357                 css = student.get('CurrentSession') or '2004-2005'
    358                 cs = int(css.split('-')[0]) - 2000
    359                 cl = int(student.get('StudentLevel') or '100')/100
    360                 dsc['entry_session'] = "200%s" % (cs - cl)
    361                 dsc['clr_ac_pin'] = access_code
    362                 studycourse.getContent().edit(mapping=dsc)
    363                 #
    364                 # Level
    365                 #
    366 ##                l = getattr(studycourse,level,None)
    367 ##                if 0 and l is None:
    368 ##                    #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
    369 ##                    logger.info('Creating Level %(StudentLevel)s for %(fullname)s' % student)
    370 ##                    studycourse.invokeFactory('StudentStudyLevel', level)
    371 ##                    l = getattr(studycourse, level)
    372 ##                    certificate = certs[certcode]
    373 ##                    cert_level = getattr(certificate,level,None)
    374 ##                    if cert_level is None:
    375 ##                        logger.info('Level %(level)s not in %(certcode)s' % vars())
    376 ##                    l.getContent().edit(mapping={'Title': "Level %s" % level})
    377             else:
    378                 em = 'Student with ID %(MatricNo)s %(fullname)s already exists\n' % student
    379                 logger.info(em)
    380                 no_import.write(em)
    381                 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)
    382                 continue
    383             if tr_count > MAX_TRANS:
    384                 transaction.commit()
    385                 em = 'Transaction commited\n' % student
    386                 logger.info(em)
    387                 tr_count = 0
    388             tr_count += 1
    389             pwl_dict.update(dc)
    390             pwl_dict.update(da)
    391             pwl_dict.update(dp)
    392             wftool = self.portal_workflow
    393             pwlist.append(pwl_template.substitute(pwl_dict))
    394             wftool.doActionFor(student_obj,'clear_and_validate')
    395             student_obj.manage_setLocalRoles(sid, ['Owner',])
    396             wftool.doActionFor(application,'close')
    397             application.manage_setLocalRoles(sid, ['Owner',])
    398             wftool.doActionFor(clearance,'close')
    399             clearance.manage_setLocalRoles(sid, ['Owner',])
    400             wftool.doActionFor(personal,'close')
    401             personal.manage_setLocalRoles(sid, ['Owner',])
    402             wftool.doActionFor(studycourse,'close_for_edit')
    403             studycourse.manage_setLocalRoles(sid, ['Owner',])
    404         open("%s/import/pwlist-%s.csv" % (i_home,name),"w+").write('\n'.join(pwlist))
     295            jamb_name = jamb.get(csv_d['jamb_lastname'])
     296            jamb_name.replace('>','')
     297            names = jamb_name.split()
     298            letter = names[-1][0].upper()
     299            sid = self.generateStudentId(letter)
     300            not_created = True
     301            while not_created:
     302                try:
     303                    students_folder.invokeFactory('Student', sid)
     304                    not_created = False
     305                except BadRequest:
     306                    sid = self.generateStudentId(letter)
     307            logger.info('%(tr_count)s: Creating Student with ID %(sid)s REG-NO %(jamb_reg_no)s ' % vars())
     308            student = getattr(self,sid)
     309            student.manage_setLocalRoles(sid, ['Owner',])
     310            student.invokeFactory('StudentApplication','application')
     311            da = {'Title': 'Application Data'}
     312            da["jamb_lastname"] = jamb_name
     313            da_fields = ('jamb_reg_no',
     314                         'jamb_sex',
     315                         'jamb_state',
     316                         'jamb_score',
     317                         'jamb_first_cos',
     318                         'jamb_sex',
     319                         'jamb_state',
     320                         'jamb_first_cos',
     321                         'jamb_second_cos',
     322                         'pume_eng_score',
     323                         'pume_tot_score',
     324                         )
     325            for daf in da_fields:
     326                da[daf] = jamb.get(csv_d[daf])
     327            app = student.application
     328            app_doc = app.getContent()
     329            app_doc.edit(mapping=da)
     330            #wftool.doActionFor(app,'open',dest_container=app)
     331            app.manage_setLocalRoles(sid, ['Owner',])
     332            student.getContent().createSubObjects()
     333            if len(no_import) > 1:
     334                open("%s/import/%s_not_imported.csv" % (i_home,name),"w").write(
     335                     '\n'.join(no_import))
    405336        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
    406337    ###)
  • WAeUP_SRP/trunk/profiles/default/actionicons.xml

    r680 r757  
    194194              title="Import JAMB Data" priority="6"
    195195              icon_expr="actionicon_submit.png"/>
     196 <action-icon category="import" action_id="import_jamb_data"
     197              title="Import PUME Results" priority="7"
     198              icon_expr="actionicon_submit.png"/>
    196199 <action-icon category="import"
    197200              action_id="import_fulltime_student_results"
  • WAeUP_SRP/trunk/profiles/default/types/StudentsFolder.xml

    r542 r757  
    6969  <permission value="Modify portal content"/>
    7070 </action>
     71<action title="JAMB Data"
     72    action_id="import_pume_data" category="import"
     73    condition_expr=""
     74    url_expr="string:${object_url}/loadPumeResultsFromCSV"
     75    visible="True">
     76  <permission value="Modify portal content"/>
     77 </action>
    7178</object>
Note: See TracChangeset for help on using the changeset viewer.