source: WAeUP_SRP/trunk/WAeUPTool.py @ 1727

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

changes in WAeUPTool undone

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