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
Line 
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 $
20"""The WAeUP Tool Box.
21"""
22
23from AccessControl import ClassSecurityInfo
24from Acquisition import aq_inner
25from Acquisition import aq_parent
26from Globals import DTMLFile
27from Globals import InitializeClass
28from OFS.SimpleItem import SimpleItem
29
30from Products.CMFCore.ActionProviderBase import ActionProviderBase
31from Products.CMFCore.permissions import View
32from Products.ZCatalog.ZCatalog import ZCatalog
33from Products.CMFCore.permissions import ModifyPortalContent
34from Products.CMFCore.utils import UniqueObject
35from Products.CMFCore.URLTool import URLTool
36from Students import makeCertificateCode
37from Globals import package_home,INSTANCE_HOME
38p_home = package_home(globals())
39i_home = INSTANCE_HOME
40import logging,os
41import transaction
42
43
44
45
46class WAeUPTool(UniqueObject, SimpleItem, ActionProviderBase):
47    """WAeUP tool"""
48
49    id = 'waeup_tool'
50    meta_type = 'WAeUP Tool'
51    _actions = ()
52
53    security = ClassSecurityInfo()
54    security.declareObjectProtected(View)
55
56    manage_options = ( ActionProviderBase.manage_options
57                     + SimpleItem.manage_options
58                     )
59
60
61    def generateStudentId(self,letter): ###(
62        import random
63        r = random
64        ##if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
65        if letter == '?':
66            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
67        sid = "%c%d" % (letter,r.randint(99999,1000000))
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):
72            sid = "%c%d" % (letter,r.randint(99999,1000000))
73        return sid
74    ###)
75
76    security.declareProtected(ModifyPortalContent,'getCredential') ###(
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
82        return getattr(student_entry,"password","not set")
83    ###)
84
85    security.declareProtected(ModifyPortalContent,'doCommit') ###(
86    def doCommit(self,logger=None):
87        "commit some transactions"
88        transaction.commit()
89    ###)
90
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()
98        picture1 ="%s/import/pictures_returning/%s.jpg" % (i_home,matric_no)
99        picture2 ="%s/import/pictures_returning/%s.JPG" % (i_home,matric_no)
100        #import pdb;pdb.set_trace()
101        if os.path.exists(picture1):
102            file = open(picture1)
103        elif os.path.exists(picture2):
104            file = open(picture2)
105        else:
106            return "passport picture not found %s" % picture1
107
108        outfile = file.read()
109        app_doc.manage_addFile('passport',
110                               file=outfile,
111                               title="%s.jpg" % matric_no)
112        return "successfully loaded passport picture"
113    ###)
114
115    security.declareProtected(ModifyPortalContent,'createOne') ###(
116    def createOne(self,students_folder,student_brain,letter,commit=False):
117        sid = self.waeup_tool.generateStudentId(letter)
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
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    ###)
147
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)
173        #self.manage_setLocalRoles(sid, ['Owner',])
174    ###)
175
176    security.declarePublic('makeStudentData') ###(
177    def makeStudentData(self,student_id,email=None,phone_nr=None):
178        "create Datastructure for a returning Student"
179        import pdb;pdb.set_trace()
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:
187            student = res[0]
188        logger.info('"%s", "creating Datastructure"' % student_id)
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))
199        #student should not be allowed to perform this transition
200        #wftool = self.portal_workflow
201        #wftool.doActionFor(student,'return')
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)
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)
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
235        self.portal_workflow.doActionFor(application,'open',dest_container=application)
236        da = {'Title': 'Application Data'}
237        student_obj.invokeFactory('StudentPersonal','personal')
238        da['jamb_reg_no'] = student.Entryregno
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
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
252        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
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"
261        da['jamb_lga'] = dc['lga'] = lga
262        da['app_email'] = dp['email'] = email
263        da['app_mobile'] = dp['phone'] = phone_nr
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
268        dp['sex'] = student.Sex == 'F'
269        dp['perm_address'] = student.Permanent_Address
270        application.getContent().edit(mapping=da)
271        self.portal_workflow.doActionFor(application,'close',dest_container=application)
272        personal.getContent().edit(mapping=dp)
273        clearance.getContent().edit(mapping=dc)
274        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
275        catd = {}
276        catd['id'] = sid
277        catd['entry_mode']= da['entry_mode']
278        catd['matric_no'] = matric_no
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
283        catd['verdict'] = verdict
284        if certificate_brain:
285            cpath = certificate_brain.getPath().split('/')
286            catd['faculty'] = cpath[-4]
287            catd['department'] = cpath[-3]
288            catd['course'] = certcode
289        self.students_catalog.modifyRecord(**catd)
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
298        dsc['current_level'] = level
299        dsc['current_verdict'] = verdict
300        studycourse.getContent().edit(mapping=dsc)
301        #
302        # Level
303        #
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})
310###)
311
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
342    security.declarePublic('getAccommodationInfo') ###(
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
366    ###)
367
368    security.declareProtected(ModifyPortalContent,'deleteAllCourses') ###(
369    def deleteAllCourses(self,department="All"):
370        ''' delete the courses'''
371        pm = self.portal_membership
372        member = pm.getAuthenticatedMember()
373
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"
380
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)
388    ###)
389
390
391InitializeClass(WAeUPTool)
Note: See TracBrowser for help on using the repository browser.