source: WAeUP_SRP/trunk/WAeUPTool.py @ 1405

Last change on this file since 1405 was 1404, checked in by joachim, 18 years ago

fix makeStudentData in WAeUPTool

  • Property svn:keywords set to Id
File size: 15.3 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 1404 2007-02-10 17:02:32Z 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
40import logging,os
[1170]41import transaction
[197]42
[1151]43
[1171]44
45
[828]46class WAeUPTool(UniqueObject, SimpleItem, ActionProviderBase):
[197]47    """WAeUP tool"""
48
[828]49    id = 'waeup_tool'
[197]50    meta_type = 'WAeUP Tool'
[828]51    _actions = ()
[197]52
53    security = ClassSecurityInfo()
[828]54    security.declareObjectProtected(View)
[197]55
[828]56    manage_options = ( ActionProviderBase.manage_options
57                     + SimpleItem.manage_options
58                     )
59
[1174]60
[1151]61    def generateStudentId(self,letter): ###(
62        import random
63        r = random
[1194]64        ##if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
65        if letter == '?':
[1151]66            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
67        sid = "%c%d" % (letter,r.randint(99999,1000000))
[1194]68##        students = self.portal_url.getPortalObject().campus.students
69##        while hasattr(students, sid):
70##            sid = "%c%d" % (letter,r.randint(99999,1000000))
71        while self.students_catalog(id = sid):
[1151]72            sid = "%c%d" % (letter,r.randint(99999,1000000))
73        return sid
74    ###)
[828]75
[1261]76    security.declareProtected(ModifyPortalContent,'getCredential') ###(
[1250]77    def getCredential(self,student_id):
78        "return a student password"
79        student_entry = getattr(self.portal_directories.students,student_id,None)
80        if student_entry is None:
81            return None
[1263]82        return getattr(student_entry,"password","not set")
[1261]83    ###)
[1250]84
[1401]85    security.declareProtected(ModifyPortalContent,'doCommit') ###(
86    def doCommit(self,logger=None):
87        "commit some transactions"
88        transaction.commit()
89    ###)
90
[1285]91    security.declarePublic('loadStudentFoto') ###(
92    def loadStudentFoto(self,student):
93        "return a student passport picture"
94        app_doc = student.application.getContent()
95        clear = student.clearance
96        clear_doc = clear.getContent()
97        matric_no = clear_doc.matric_no.upper()
[1286]98        picture1 ="%s/import/pictures_returning/%s.jpg" % (i_home,matric_no)
99        picture2 ="%s/import/pictures_returning/%s.JPG" % (i_home,matric_no)
[1285]100        #import pdb;pdb.set_trace()
[1286]101        if os.path.exists(picture1):
102            file = open(picture1)
103        elif os.path.exists(picture2):
[1287]104            file = open(picture2)
[1286]105        else:
[1287]106            return "passport picture not found %s" % picture1
[1286]107
[1285]108        outfile = file.read()
109        app_doc.manage_addFile('passport',
110                               file=outfile,
111                               title="%s.jpg" % matric_no)
[1286]112        return "successfully loaded passport picture"
[1285]113    ###)
114
[1170]115    security.declareProtected(ModifyPortalContent,'createOne') ###(
[1194]116    def createOne(self,students_folder,student_brain,letter,commit=False):
117        sid = self.waeup_tool.generateStudentId(letter)
[1170]118        students_folder.invokeFactory('Student', sid)
119        student = getattr(students_folder,sid)
120        self.portal_workflow.doActionFor(student,'return')
121        student.manage_setLocalRoles(sid, ['Owner',])
122        matric_no = student_brain.matric_no
123        jamb_reg_no = student_brain.Entryregno
124        self.students_catalog.addRecord(id = sid,
125                                           matric_no = matric_no,
126                                           jamb_reg_no = jamb_reg_no,
127                                           sex = student_brain.Sex == "F",
128                                           name = "%s %s %s" % (student_brain.Firstname,
129                                                                student_brain.Middlename,
130                                                                student_brain.Lastname)
131                                        )
132        if commit:
133            transaction.commit()
134        return sid,jamb_reg_no
135    ###)
136
[1151]137    security.declarePublic('getCertificateBrain') ###(
138    def getCertificateBrain(self,cert_id):
139        "do it"
140        res = ZCatalog.searchResults(self.portal_catalog,
141                                {'portal_type':"Certificate",
142                                      'id': cert_id})
143        if res:
144            return res[0]
145        return None
146    ###)
[1160]147
[1151]148    security.declarePublic('findStudentByMatricelNo') ###(
149    def findStudentByMatricelNo(self,matric_no):
150        "do it"
151        res = ZCatalog.searchResults(self.portal_catalog,
152                                {'portal_type':"StudentClearance",
153                                 'SearchableText': matric_no})
154        if res:
155            return res[0]
156        return None
157    ###)
158
159    security.declarePublic('makeStudentMember') ###(
160    def makeStudentMember(self,sid,password='uNsEt'):
161        """make the student a member"""
162        membership = self.portal_membership
163        membership.addMember(sid,
164                             password ,
165                             roles=('Member',
166                                     'Student',
167                                     ),
168                             domains='',
169                             properties = {'memberareaCreationFlag': False,
170                                           'homeless': True},)
171        member = membership.getMemberById(sid)
172        self.portal_registration.afterAdd(member, sid, password, None)
[1261]173        #self.manage_setLocalRoles(sid, ['Owner',])
[1151]174    ###)
[1160]175
[1151]176    security.declarePublic('makeStudentData') ###(
[1158]177    def makeStudentData(self,student_id,email=None,phone_nr=None):
[1151]178        "create Datastructure for a returning Student"
[1404]179        import pdb;pdb.set_trace()
[1151]180        logger = logging.getLogger('Student.CreateData')
181        students_folder = self.portal_url.getPortalObject().campus.students
182        res = self.students_catalog(id=student_id)
183        if res:
184            st = res[0]
185        res = self.returning_import(matric_no = st.matric_no)
186        if res:
[1160]187            student = res[0]
[1158]188        logger.info('"%s", "creating Datastructure"' % student_id)
[1401]189        s_results = self.results_import(matric_no = st.matric_no)
190        lnr = self.getLevelFromResultsCosCode(s_results)
191        level = "%d00" % lnr
192        verdict,elegible = self.getVerdict(s_results[0].Verdict)
193        if elegible:
194            level = "%d00" % (lnr + 1)
195##        level = s_results[0].Level
196##        for result in s_results:
197##            if level != result.Level:
198##                logger.info('"%s", "Levels differ","%s != %s"' % (student_id,level,result.Level))
[1171]199        #student should not be allowed to perform this transition
[1174]200        #wftool = self.portal_workflow
201        #wftool.doActionFor(student,'return')
[1151]202        certcode_org = student.Coursemajorcode
203        certcode = makeCertificateCode(certcode_org)
204        certificate_brain = self.getCertificateBrain(certcode)
205        if not certificate_brain:
206            em = 'Certificate %s org-code %s not found\n' % (certcode, certcode_org)
207            logger.info(em)
[1404]208##        validlevel = False
209##        try:
210##            il = int(level) + 100
211##            level = "%s" % il
212##            validlevel = True
213##        except:
214##            em = '"%(matric_no)s","invalid Level","%(Level)s"' % student
215##            logger.info(em)
216##        if not validlevel:
217##            erg = self.results_import(matric_no = student.matric_no)
218##            level = 'xxx'
219##            if erg:
220##                level = erg[0].Level
221##            try:
222##                il = int(level) + 100
223##                level = "%s" % il
224##                em = '"%s","fixed Level from results_import","%s"' % (student.matric_no,erg[0].Level)
225##                logger.info(em)
226##                validlevel = True
227##            except:
228##                em = '"%s","invalid Level in results_import","%s"' % (student.matric_no,erg[0].Level)
229##                logger.info(em)
[1151]230        matric_no = student.matric_no
231        sid = student_id
232        student_obj = getattr(students_folder,sid)
233        student_obj.invokeFactory('StudentApplication','application')
234        application = student_obj.application
[1169]235        self.portal_workflow.doActionFor(application,'open',dest_container=application)
[1151]236        da = {'Title': 'Application Data'}
237        student_obj.invokeFactory('StudentPersonal','personal')
238        da['jamb_reg_no'] = student.Entryregno
[1401]239        em = student.Mode_of_Entry
240        if em in ('DIRECT', 'DIRECT ENTRY',):
241            em = 'DE'
242        elif em in ('U.M.E', 'UNE',):
243            em = 'UME'
244        elif not em:
245            em = "unknown"
246        da['entry_mode'] = em
[1151]247        personal = student_obj.personal
248        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
249        dp = {'Title': 'Personal Data'}
250        student_obj.invokeFactory('StudentClearance','clearance')
251        clearance = student_obj.clearance
[1169]252        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
[1151]253        dc = {'Title': 'Clearance/Eligibility Record'}
254        dc['matric_no'] = matric_no
255        state = student.State
256        lga = student.LGA
257        if state and lga:
258            lga =  state + ' / ' + lga
259        else:
260            lga = "None"
[1174]261        da['jamb_lga'] = dc['lga'] = lga
[1173]262        da['app_email'] = dp['email'] = email
263        da['app_mobile'] = dp['phone'] = phone_nr
[1174]264        da['jamb_firstname'] = dp['firstname'] = student.Firstname
265        da['jamb_middlename'] = dp['middlename'] = student.Middlename
266        da['jamb_lastname'] = dp['lastname'] = student.Lastname
267        da['jamb_sex'] = student.Sex
[1151]268        dp['sex'] = student.Sex == 'F'
269        dp['perm_address'] = student.Permanent_Address
270        application.getContent().edit(mapping=da)
[1169]271        self.portal_workflow.doActionFor(application,'close',dest_container=application)
[1151]272        personal.getContent().edit(mapping=dp)
273        clearance.getContent().edit(mapping=dc)
[1169]274        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
[1158]275        catd = {}
276        catd['id'] = sid
277        catd['entry_mode']= da['entry_mode']
278        catd['matric_no'] = matric_no
[1171]279        catd['jamb_reg_no'] = da['jamb_reg_no']
280        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
281        catd['sex'] = dp['sex']
282        catd['level'] = level
[1401]283        catd['verdict'] = verdict
[1158]284        if certificate_brain:
285            cpath = certificate_brain.getPath().split('/')
[1171]286            catd['faculty'] = cpath[-4]
287            catd['department'] = cpath[-3]
[1158]288            catd['course'] = certcode
289        self.students_catalog.modifyRecord(**catd)
[1151]290        #
291        # Study Course
292        #
293        student_obj.invokeFactory('StudentStudyCourse','study_course')
294        studycourse = student_obj.study_course
295        self.portal_workflow.doActionFor(studycourse,'open',dest_container=studycourse)
296        dsc = {}
297        dsc['study_course'] = certcode
[1401]298        dsc['current_level'] = level
299        dsc['current_verdict'] = verdict
[1151]300        studycourse.getContent().edit(mapping=dsc)
301        #
302        # Level
303        #
[1198]304##        l = getattr(studycourse,level,None)
305##        if l is None:
306##            studycourse.invokeFactory('StudentStudyLevel', level)
307##            l = getattr(studycourse, level)
308##            self.portal_workflow.doActionFor(l,'open',dest_container=l)
309##            l.getContent().edit(mapping={'Title': "Level %s" % level})
[1194]310###)
[1160]311
[1194]312    security.declarePublic('makeStudentLevel') ###(
313    def makeStudentLevel(self,student_id):
314        "create the StudyLevel for a returning Student"
315        #import pdb;pdb.set_trace()
316        logger = logging.getLogger('Student.CreateLevel')
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        course = st.course
322        matric_no = st.matric_no
323        level = st.level
324        res = self.results_import(matric_no = matric_no)
325        if res:
326            results = res
327        logger.info('"%s", "creating Level", "%s"' % (student_id,level))
328        #
329        # Level
330        #
331        student_obj = getattr(self.portal_url.getPortalObject().campus.students,student_id)
332        studycourse = getattr(student_obj,"study_course",None)
333        self.portal_workflow.doActionFor(studycourse,'close_for_edit',dest_container=studycourse)
334        l = getattr(studycourse,level,None)
335        if l is None:
336            studycourse.invokeFactory('StudentStudyLevel', level)
337            l = getattr(studycourse, level)
338            self.portal_workflow.doActionFor(l,'open',dest_container=l)
339            l.getContent().edit(mapping={'Title': "Level %s" % level})
340        ###)
341
[1151]342    security.declarePublic('getAccommodationInfo') ###(
[828]343    def getAccommodationInfo(self,bed):
344        """return Accommodation Info"""
345        info = {}
346        hall,block,room,letter = bed.split('_')
347        res = ZCatalog.searchResults(self.portal_catalog,portal_type="AccoHall",id=hall)
348        if res and len(res) == 1:
349            hall_brain = res[0]
350            hall_doc = hall_brain.getObject().getContent()
351        else:
352            return info
353        info['hall_title'] = hall_brain.Title
354        info['maintenance_code'] = hall_doc.maintenance_code
355        res = ZCatalog.searchResults(self.portal_catalog,portal_type="ScratchCardBatch")
356        batch_doc = None
357        for brain in res:
358            if brain.id.startswith(info['maintenance_code']):
359                batch_doc = brain.getObject().getContent()
360                break
361        if batch_doc is None:
362            info['maintenance_fee'] = None
363        else:
364            info['maintenance_fee'] = batch_doc.cost
365        return info
[1151]366    ###)
[828]367
[1151]368    security.declareProtected(ModifyPortalContent,'deleteAllCourses') ###(
369    def deleteAllCourses(self,department="All"):
370        ''' delete the courses'''
371        pm = self.portal_membership
372        member = pm.getAuthenticatedMember()
[1160]373
[1151]374        if str(member) not in ("henrik","joachim"):
375            return "not possible"
376        if department == "All":
377            res = self.portal_catalog({'meta_type': 'Department'})
378        if len(res) < 1:
379            return "No Departments found"
[1160]380
[1151]381        deleted = []
382        for dep in res:
383            cf = dep.getObject().courses
384            if cf:
385                cf.manage_delObjects(ids=cf.objectIds())
386                deleted.append("deleted Courses in %s" % dep.getId)
387        return "\r".join(deleted)
[1160]388    ###)
[1151]389
[1160]390
[828]391InitializeClass(WAeUPTool)
Note: See TracBrowser for help on using the repository browser.