source: WAeUP_SRP/trunk/WAeUPTool.py @ 1712

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

new import function for createStudents,
catalog fields added

  • Property svn:keywords set to Id
File size: 26.5 KB
RevLine 
[197]1#-*- mode: python; mode: fold -*-
2# (C) Copyright 2005 The WAeUP group  <http://www.waeup.org>
3# Author: Joachim Schmitz (js@aixtraware.de)
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License version 2 as published
7# by the Free Software Foundation.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program; if not, write to the Free Software
16# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
17# 02111-1307, USA.
18#
19# $Id: WAeUPTool.py 1707 2007-04-25 11:58:39Z joachim $
[1174]20"""The WAeUP Tool Box.
[197]21"""
22
23from AccessControl import ClassSecurityInfo
[828]24from Acquisition import aq_inner
25from Acquisition import aq_parent
26from Globals import DTMLFile
27from Globals import InitializeClass
28from OFS.SimpleItem import SimpleItem
[197]29
[828]30from Products.CMFCore.ActionProviderBase import ActionProviderBase
31from Products.CMFCore.permissions import View
32from Products.ZCatalog.ZCatalog import ZCatalog
33from Products.CMFCore.permissions import ModifyPortalContent
[197]34from Products.CMFCore.utils import UniqueObject
[1194]35from Products.CMFCore.URLTool import URLTool
[1151]36from Students import makeCertificateCode
[1285]37from Globals import package_home,INSTANCE_HOME
38p_home = package_home(globals())
39i_home = INSTANCE_HOME
[1620]40import DateTime
41import logging
[1170]42import transaction
[1620]43import csv,re,os
[1707]44from Products.AdvancedQuery import Eq, Between, Le,In
[197]45
[1707]46def getObject(object,name):
47    if object.hasObject(name):
48        return getattr(object,name)
49    return None
50   
[828]51class WAeUPTool(UniqueObject, SimpleItem, ActionProviderBase):
[197]52    """WAeUP tool"""
53
[828]54    id = 'waeup_tool'
[197]55    meta_type = 'WAeUP Tool'
[828]56    _actions = ()
[197]57
58    security = ClassSecurityInfo()
[828]59    security.declareObjectProtected(View)
[197]60
[828]61    manage_options = ( ActionProviderBase.manage_options
62                     + SimpleItem.manage_options
63                     )
64
[1707]65    def rwrite(self,s):
66        response = self.REQUEST.RESPONSE
67        response.setHeader('Content-type','text/html; charset=ISO-8859-15')
68        response.write("%s<br />\r\n" % s)
[1174]69
[1151]70    def generateStudentId(self,letter): ###(
71        import random
72        r = random
[1194]73        ##if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
74        if letter == '?':
[1151]75            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
76        sid = "%c%d" % (letter,r.randint(99999,1000000))
[1194]77##        students = self.portal_url.getPortalObject().campus.students
78##        while hasattr(students, sid):
79##            sid = "%c%d" % (letter,r.randint(99999,1000000))
80        while self.students_catalog(id = sid):
[1151]81            sid = "%c%d" % (letter,r.randint(99999,1000000))
82        return sid
[1460]83    ###)
[1415]84
85    def generatePassword(self,s=None): ###(
86        import random
87        r = random
88        ##if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
89        if s is None:
90            s = 'abcdefghklmnpqrstuvwxy23456789'
91        pw = ''
92        while len(pw) < 6:
93            pw += r.choice(s)
94        return pw
[1151]95    ###)
[828]96
[1261]97    security.declareProtected(ModifyPortalContent,'getCredential') ###(
[1250]98    def getCredential(self,student_id):
99        "return a student password"
100        student_entry = getattr(self.portal_directories.students,student_id,None)
101        if student_entry is None:
102            return None
[1263]103        return getattr(student_entry,"password","not set")
[1261]104    ###)
[1250]105
[1460]106    security.declarePublic('checkPassword') ###(
[1467]107    def checkPassword(self,student_id,password):
[1460]108        "return a student password"
109        student_entry = getattr(self.portal_directories.students,student_id,None)
110        if student_entry is None:
111            return False
112        return getattr(student_entry,"password","not set") == password
113    ###)
114
[1467]115    security.declarePublic('editPassword') ###(
116    def editPassword(self,student_id,password):
117        "edit a student password"
118        student_entry = getattr(self.portal_directories.students,student_id,None)
119        if student_entry is None:
[1571]120            return
[1467]121        setattr(student_entry,'password',password)
122    ###)
123
[1647]124    security.declareProtected(View,'doCommit') ###(
[1401]125    def doCommit(self,logger=None):
126        "commit some transactions"
127        transaction.commit()
128    ###)
129
[1285]130    security.declarePublic('loadStudentFoto') ###(
131    def loadStudentFoto(self,student):
132        "return a student passport picture"
133        app_doc = student.application.getContent()
134        clear = student.clearance
135        clear_doc = clear.getContent()
136        matric_no = clear_doc.matric_no.upper()
[1286]137        picture1 ="%s/import/pictures_returning/%s.jpg" % (i_home,matric_no)
138        picture2 ="%s/import/pictures_returning/%s.JPG" % (i_home,matric_no)
[1285]139        #import pdb;pdb.set_trace()
[1286]140        if os.path.exists(picture1):
141            file = open(picture1)
142        elif os.path.exists(picture2):
[1287]143            file = open(picture2)
[1286]144        else:
[1287]145            return "passport picture not found %s" % picture1
[1286]146
[1285]147        outfile = file.read()
148        app_doc.manage_addFile('passport',
149                               file=outfile,
150                               title="%s.jpg" % matric_no)
[1286]151        return "successfully loaded passport picture"
[1285]152    ###)
153
[1170]154    security.declareProtected(ModifyPortalContent,'createOne') ###(
[1194]155    def createOne(self,students_folder,student_brain,letter,commit=False):
156        sid = self.waeup_tool.generateStudentId(letter)
[1170]157        students_folder.invokeFactory('Student', sid)
158        student = getattr(students_folder,sid)
159        self.portal_workflow.doActionFor(student,'return')
160        student.manage_setLocalRoles(sid, ['Owner',])
161        matric_no = student_brain.matric_no
162        jamb_reg_no = student_brain.Entryregno
163        self.students_catalog.addRecord(id = sid,
164                                           matric_no = matric_no,
165                                           jamb_reg_no = jamb_reg_no,
166                                           sex = student_brain.Sex == "F",
167                                           name = "%s %s %s" % (student_brain.Firstname,
168                                                                student_brain.Middlename,
169                                                                student_brain.Lastname)
170                                        )
171        if commit:
172            transaction.commit()
173        return sid,jamb_reg_no
174    ###)
175
[1415]176    security.declareProtected(ModifyPortalContent,'createStudent') ###(
177    def createStudent(self,dict):
178        students_folder = self.portal_url.getPortalObject().campus.students
179        sid = self.waeup_tool.generateStudentId('?')
180        students_folder.invokeFactory('Student', sid)
181        student_obj = getattr(students_folder,sid)
182        password = self.generatePassword()
183        self.makeStudentMember(sid,password)
184        status,entry_mode = dict.get('entry_mode').split('_')
185        wfaction = 'return'
186        if status == "NEW":
187            wfaction = 'admit'
188        matric_no = dict.get('matric_no')
189        email = dict.get('email')
190        level = dict.get('level')
[1426]191        jamb_reg_no = dict.get('jamb_reg_no')
[1415]192        study_course = dict.get('study_course')
193        self.portal_workflow.doActionFor(student_obj,wfaction)
194        student_obj.manage_setLocalRoles(sid, ['Owner',])
195        student_obj.invokeFactory('StudentApplication','application')
196        application = student_obj.application
197        self.portal_workflow.doActionFor(application,'open',dest_container=application)
198        da = {'Title': 'Application Data'}
199        student_obj.invokeFactory('StudentPersonal','personal')
200        da['entry_mode'] = entry_mode
201        personal = student_obj.personal
202        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
203        dp = {'Title': 'Personal Data'}
204        student_obj.invokeFactory('StudentClearance','clearance')
205        clearance = student_obj.clearance
206        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
207        dc = {'Title': 'Clearance/Eligibility Record'}
208        dc['matric_no'] = matric_no
209        da['app_email'] = dp['email'] = email
[1426]210        da['jamb_reg_no'] = jamb_reg_no
[1415]211        dp['firstname'] = dict.get('firstname')
212        dp['middlename'] = dict.get('middlename')
213        dp['lastname'] = dict.get('lastname')
214        da['jamb_lastname'] = "%(firstname)s %(middlename)s %(lastname)s" % dict
215        sex = dict.get('sex')
216        if sex:
217            da['jamb_sex'] = 'F'
218        else:
219            da['jamb_sex'] = 'M'
220        dp['sex'] = sex
221        application.getContent().edit(mapping=da)
222        self.portal_workflow.doActionFor(application,'close',dest_container=application)
223        personal.getContent().edit(mapping=dp)
224        clearance.getContent().edit(mapping=dc)
225        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
226        catd = {}
227        catd['id'] = sid
228        catd['entry_mode']= entry_mode
229        catd['email'] = email
[1426]230        catd['jamb_reg_no'] = jamb_reg_no
[1415]231        catd['matric_no'] = matric_no
232        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
233        catd['sex'] = dp['sex']
234        catd['level'] = level
235        certificate_brain = self.getCertificateBrain(study_course)
236        if certificate_brain:
237            cpath = certificate_brain.getPath().split('/')
238            catd['faculty'] = cpath[-4]
239            catd['department'] = cpath[-3]
240            catd['course'] = study_course
241        self.students_catalog.addRecord(**catd)
242        #
243        # Study Course
244        #
245        student_obj.invokeFactory('StudentStudyCourse','study_course')
246        sc = student_obj.study_course
247        self.portal_workflow.doActionFor(sc,'open',dest_container=sc)
248        dsc = {}
249        dsc['study_course'] = study_course
250        dsc['current_level'] = level
251        sc.getContent().edit(mapping=dsc)
252
253        return sid,password
254    ###)
255
[1151]256    security.declarePublic('getCertificateBrain') ###(
257    def getCertificateBrain(self,cert_id):
258        "do it"
259        res = ZCatalog.searchResults(self.portal_catalog,
260                                {'portal_type':"Certificate",
261                                      'id': cert_id})
262        if res:
263            return res[0]
264        return None
265    ###)
[1160]266
[1151]267    security.declarePublic('findStudentByMatricelNo') ###(
268    def findStudentByMatricelNo(self,matric_no):
269        "do it"
270        res = ZCatalog.searchResults(self.portal_catalog,
271                                {'portal_type':"StudentClearance",
272                                 'SearchableText': matric_no})
273        if res:
274            return res[0]
275        return None
276    ###)
277
278    security.declarePublic('makeStudentMember') ###(
279    def makeStudentMember(self,sid,password='uNsEt'):
280        """make the student a member"""
281        membership = self.portal_membership
282        membership.addMember(sid,
283                             password ,
284                             roles=('Member',
285                                     'Student',
286                                     ),
287                             domains='',
288                             properties = {'memberareaCreationFlag': False,
289                                           'homeless': True},)
290        member = membership.getMemberById(sid)
291        self.portal_registration.afterAdd(member, sid, password, None)
[1261]292        #self.manage_setLocalRoles(sid, ['Owner',])
[1151]293    ###)
[1160]294
[1151]295    security.declarePublic('makeStudentData') ###(
[1158]296    def makeStudentData(self,student_id,email=None,phone_nr=None):
[1151]297        "create Datastructure for a returning Student"
[1406]298        #import pdb;pdb.set_trace()
[1571]299        logger = logging.getLogger('WAeUPTool.makeStudentData')
[1151]300        students_folder = self.portal_url.getPortalObject().campus.students
301        res = self.students_catalog(id=student_id)
302        if res:
303            st = res[0]
304        res = self.returning_import(matric_no = st.matric_no)
305        if res:
[1160]306            student = res[0]
[1580]307        logger.info('%s creates data structure' % student_id)
[1401]308        s_results = self.results_import(matric_no = st.matric_no)
309        lnr = self.getLevelFromResultsCosCode(s_results)
310        level = "%d00" % lnr
[1695]311        verdict,eligible = self.getVerdict(s_results[0].Verdict)
312        if eligible:
[1401]313            level = "%d00" % (lnr + 1)
314##        level = s_results[0].Level
315##        for result in s_results:
316##            if level != result.Level:
317##                logger.info('"%s", "Levels differ","%s != %s"' % (student_id,level,result.Level))
[1171]318        #student should not be allowed to perform this transition
[1174]319        #wftool = self.portal_workflow
320        #wftool.doActionFor(student,'return')
[1151]321        certcode_org = student.Coursemajorcode
322        certcode = makeCertificateCode(certcode_org)
323        certificate_brain = self.getCertificateBrain(certcode)
324        if not certificate_brain:
325            em = 'Certificate %s org-code %s not found\n' % (certcode, certcode_org)
326            logger.info(em)
327        matric_no = student.matric_no
328        sid = student_id
329        student_obj = getattr(students_folder,sid)
330        student_obj.invokeFactory('StudentApplication','application')
331        application = student_obj.application
[1169]332        self.portal_workflow.doActionFor(application,'open',dest_container=application)
[1151]333        da = {'Title': 'Application Data'}
334        student_obj.invokeFactory('StudentPersonal','personal')
335        da['jamb_reg_no'] = student.Entryregno
[1462]336        em = self.getEntryMode(student.Entryregno)
[1460]337##        em = student.Mode_of_Entry
338##        if em in ('DIRECT', 'DIRECT ENTRY',):
339##            em = 'DE'
340##        elif em in ('U.M.E', 'UNE',):
341##            em = 'UME'
342##        elif not em:
343##            em = "unknown"
[1401]344        da['entry_mode'] = em
[1151]345        personal = student_obj.personal
346        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
347        dp = {'Title': 'Personal Data'}
348        student_obj.invokeFactory('StudentClearance','clearance')
349        clearance = student_obj.clearance
[1169]350        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
[1151]351        dc = {'Title': 'Clearance/Eligibility Record'}
352        dc['matric_no'] = matric_no
353        state = student.State
354        lga = student.LGA
355        if state and lga:
356            lga =  state + ' / ' + lga
357        else:
358            lga = "None"
[1174]359        da['jamb_lga'] = dc['lga'] = lga
[1173]360        da['app_email'] = dp['email'] = email
361        da['app_mobile'] = dp['phone'] = phone_nr
[1411]362        dp['firstname'] = student.Firstname
363        dp['middlename'] = student.Middlename
364        dp['lastname'] = student.Lastname
365        da['jamb_lastname'] = "%s %s %s" % (student.Firstname,student.Middlename,student.Lastname)
[1174]366        da['jamb_sex'] = student.Sex
[1151]367        dp['sex'] = student.Sex == 'F'
368        dp['perm_address'] = student.Permanent_Address
369        application.getContent().edit(mapping=da)
[1169]370        self.portal_workflow.doActionFor(application,'close',dest_container=application)
[1151]371        personal.getContent().edit(mapping=dp)
372        clearance.getContent().edit(mapping=dc)
[1169]373        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
[1158]374        catd = {}
375        catd['id'] = sid
376        catd['entry_mode']= da['entry_mode']
377        catd['matric_no'] = matric_no
[1171]378        catd['jamb_reg_no'] = da['jamb_reg_no']
379        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
380        catd['sex'] = dp['sex']
381        catd['level'] = level
[1401]382        catd['verdict'] = verdict
[1158]383        if certificate_brain:
384            cpath = certificate_brain.getPath().split('/')
[1171]385            catd['faculty'] = cpath[-4]
386            catd['department'] = cpath[-3]
[1158]387            catd['course'] = certcode
388        self.students_catalog.modifyRecord(**catd)
[1151]389        #
390        # Study Course
391        #
392        student_obj.invokeFactory('StudentStudyCourse','study_course')
393        studycourse = student_obj.study_course
394        self.portal_workflow.doActionFor(studycourse,'open',dest_container=studycourse)
395        dsc = {}
396        dsc['study_course'] = certcode
[1401]397        dsc['current_level'] = level
398        dsc['current_verdict'] = verdict
[1151]399        studycourse.getContent().edit(mapping=dsc)
400        #
401        # Level
402        #
[1198]403##        l = getattr(studycourse,level,None)
404##        if l is None:
405##            studycourse.invokeFactory('StudentStudyLevel', level)
406##            l = getattr(studycourse, level)
407##            self.portal_workflow.doActionFor(l,'open',dest_container=l)
408##            l.getContent().edit(mapping={'Title': "Level %s" % level})
[1194]409###)
[1160]410
[1194]411    security.declarePublic('makeStudentLevel') ###(
412    def makeStudentLevel(self,student_id):
413        "create the StudyLevel for a returning Student"
414        #import pdb;pdb.set_trace()
[1571]415        logger = logging.getLogger('WAeUPTool.makeStudentLevel')
[1194]416        students_folder = self.portal_url.getPortalObject().campus.students
417        res = self.students_catalog(id=student_id)
418        if res:
419            st = res[0]
420        course = st.course
421        matric_no = st.matric_no
422        level = st.level
423        res = self.results_import(matric_no = matric_no)
424        if res:
425            results = res
[1571]426        logger.info('%s creating Level %s' % (student_id,level))
[1194]427        #
428        # Level
429        #
430        student_obj = getattr(self.portal_url.getPortalObject().campus.students,student_id)
431        studycourse = getattr(student_obj,"study_course",None)
432        self.portal_workflow.doActionFor(studycourse,'close_for_edit',dest_container=studycourse)
433        l = getattr(studycourse,level,None)
434        if l is None:
435            studycourse.invokeFactory('StudentStudyLevel', level)
436            l = getattr(studycourse, level)
437            self.portal_workflow.doActionFor(l,'open',dest_container=l)
438            l.getContent().edit(mapping={'Title': "Level %s" % level})
439        ###)
440
[1151]441    security.declarePublic('getAccommodationInfo') ###(
[828]442    def getAccommodationInfo(self,bed):
443        """return Accommodation Info"""
444        info = {}
445        hall,block,room,letter = bed.split('_')
446        res = ZCatalog.searchResults(self.portal_catalog,portal_type="AccoHall",id=hall)
447        if res and len(res) == 1:
448            hall_brain = res[0]
449            hall_doc = hall_brain.getObject().getContent()
450        else:
451            return info
452        info['hall_title'] = hall_brain.Title
453        info['maintenance_code'] = hall_doc.maintenance_code
454        res = ZCatalog.searchResults(self.portal_catalog,portal_type="ScratchCardBatch")
455        batch_doc = None
456        for brain in res:
457            if brain.id.startswith(info['maintenance_code']):
458                batch_doc = brain.getObject().getContent()
459                break
460        if batch_doc is None:
461            info['maintenance_fee'] = None
462        else:
463            info['maintenance_fee'] = batch_doc.cost
464        return info
[1151]465    ###)
[828]466
[1151]467    security.declareProtected(ModifyPortalContent,'deleteAllCourses') ###(
468    def deleteAllCourses(self,department="All"):
469        ''' delete the courses'''
470        pm = self.portal_membership
471        member = pm.getAuthenticatedMember()
[1160]472
[1151]473        if str(member) not in ("henrik","joachim"):
474            return "not possible"
475        if department == "All":
476            res = self.portal_catalog({'meta_type': 'Department'})
477        if len(res) < 1:
478            return "No Departments found"
[1160]479
[1151]480        deleted = []
481        for dep in res:
482            cf = dep.getObject().courses
483            if cf:
484                cf.manage_delObjects(ids=cf.objectIds())
485                deleted.append("deleted Courses in %s" % dep.getId)
486        return "\r".join(deleted)
[1160]487    ###)
[1151]488
[1572]489    security.declareProtected(ModifyPortalContent,'getLogfileLines') ###(
490    def getLogfileLines(self,filename="event.log",numlines=20):
491        """Get last NUMLINES lines of logfile FILENAME.
[1160]492
[1572]493        Return last lines' of a file in the instances logfile directory as
494        a list. The number of returned lines equals `numlines' or less. If
495        less than `numlines' lines are available, the whole file ist
496        returned. If the file can not be opened or some other error
497        occurs, empty list is returend.
498        """
499        result = []
500        lines_hit = 0
501
502        # We only handle files in instances' log directory...
503        logpath = os.path.join(i_home, "log")
504        filename = str(os.path.abspath( os.path.join( logpath, filename )))
505        if not filename.startswith( logpath ):
506            # Attempt to access file outside log-dir...
507            return []
508
509        try:
510            fd = file( filename, "rb" )
511        except IOError:
512            return []
513        if not fd:
514            return []
515
516        if os.linesep == None:
517            linesep = '\n'
518        else:
519            linesep = os.linesep
520
521        # Try to find 'numlines' times a lineseparator, searching from end
522        # and moving to the beginning of file...
523        fd.seek( 0, 2) # Move to end of file...
524        while lines_hit < numlines:
525            if fd.read(1) == linesep[-1]: # This moves filedescriptor
526                                          # one step forward...
527                lines_hit += 1
528            try:
529                fd.seek( -2, 1) # Go two bytes back from current pos...
530            except IOError:
531                # We cannot go back two bytes. Maybe the file is too small...
532                break
533        fd.seek(2,1)
534
535        # Read all lines from current position...
536        result = fd.readlines()
537        # Remove line endings...
538        result = [x.strip() for x in result]
539        fd.close()
540        return result
541    ###)
542
[1700]543    security.declareProtected(ModifyPortalContent,"getCallbacksFromLog")###(
[1665]544    def getCallbacksFromLog(self,filename):
545        """fix Online Payment Transactions from Z2.log entries"""
546        import transaction
547        import random
548        from cgi import parse_qs
549        from urlparse import urlparse
550        #from pdb import set_trace
551        wftool = self.portal_workflow
552        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
553        students_folder = self.portal_url.getPortalObject().campus.students
554        s = r'(?P<client_ip>\S+) - (?P<member_id>\S+) \['
555        s += r'(?P<date>.*)\] "(?P<get>.*)" (?P<codes>\d+ \d+) "'
556        s += r'(?P<intersw>.*)" "(?P<agent>.*)"'
557        data = re.compile(s)
558        start = True
559        tr_count = 1
560        total = 0
561        #name = 'pume_results'
562        #name = 'epaymentsuccessful_z2log2'
563        name = filename
564        no_import = []
565        imported = []
566        logger = logging.getLogger('WAeUPTool.getFailedTransactions')
567        try:
568            transactions = open("%s/import/%s" % (i_home,name),"rb").readlines()
569        except:
570            logger.error('Error reading %s' % name)
571            return
572        tas = []
573        for line in transactions:
574            dict = {}
575            items = data.search(line)
576            dict['idict'] = idict = items.groupdict()
577            #print idict
578            #from pdb import set_trace;set_trace()
579            urlparsed = urlparse(idict['get'][4:])
580            #print urlparsed
581            path = urlparsed[2].split('/')
582            dict['student_id'] = student_id = path[8]
583            dict['payment_id'] = payment_id = path[10]
584            dict['qs_dict'] = qs_dict = parse_qs(urlparsed[4])
585            tas.append(dict)
586            tr_count += 1
587        return tas
588    ###)
589
[1620]590    security.declareProtected(ModifyPortalContent,"importOnlinePaymentTransactions")###(
591    def importOnlinePaymentTransactions(self):
592        """load Online Payment Transactions from CSV values"""
593        import transaction
594        import random
595        #from pdb import set_trace
596        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
[1625]597        opt = self.online_payments_import
[1620]598        students_folder = self.portal_url.getPortalObject().campus.students
599        start = True
600        tr_count = 1
601        total = 0
602        #name = 'pume_results'
603        name = 'OnlineTransactions'
604        no_import = []
605        imported = []
606        logger = logging.getLogger('WAeUPTool.importOnlinePaymentTransactions')
607        try:
608            transactions = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
609        except:
610            logger.error('Error reading %s.csv' % name)
611            return
612        for pay_transaction in transactions:
613            if start:
614                start = False
615                logger.info('Start loading from %s.csv' % name)
616                s = ','.join(['"%s"' % fn for fn in pay_transaction.keys()])
617                no_import.append('%s,"Error"' % s)
618                format = ','.join(['"%%(%s)s"' % fn for fn in pay_transaction.keys()])
619                format_error = format + ',"%(Error)s"'
620            data = {}
[1644]621
[1643]622            # format of the first file sent from Tayo
623            #data['datetime'] = date = DateTime.DateTime(pay_transaction['Date'])
624            #data['student_id'] = student_id = pay_transaction['Payer ID']
625            #data['order_id'] = order_id = pay_transaction['Order ID (Tranx Ref)']
626            #data['response_code'] = response_code = pay_transaction['Resp Code']
627            #data['amount'] = amount = pay_transaction['Amount']
[1644]628
[1643]629            # format of the second file sent from Tayo
630            data['datetime'] = date = 0
[1625]631            data['student_id'] = student_id = pay_transaction['Payer ID']
632            data['order_id'] = order_id = pay_transaction['Order ID (Tranx Ref)']
[1644]633            data['response_code'] = response_code = '00'
634            data['amount'] = amount = pay_transaction['Amount']
635
[1620]636            dup = False
637            if response_code == "12":
638                continue
639            try:
640                opt.addRecord(**data)
641            except ValueError:
642                dup = True
643            #from pdb import set_trace;set_trace()
644            if dup:
645                if response_code == "00":
646                    opt.modifyRecord(**data)
647                else:
[1674]648                    pay_transaction['Error'] = "Duplicate order_id"
[1620]649                    no_import.append( format_error % pay_transaction)
[1674]650                    logger.info("duplicate order_id %(order_id)s for %(student_id)s %(response_code)s" % data)
[1620]651                    continue
652            tr_count += 1
653            if tr_count > 1000:
654                if len(no_import) > 0:
655                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
656                             '\n'.join(no_import) + '\n')
657                    no_import = []
[1645]658                em = '%d transactions committed\n' % (tr_count)
[1620]659                transaction.commit()
660                regs = []
661                logger.info(em)
662                total += tr_count
663                tr_count = 0
664        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
665                                                '\n'.join(no_import))
666        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
667    ###)
668
[828]669InitializeClass(WAeUPTool)
Note: See TracBrowser for help on using the repository browser.