source: WAeUP_SRP/trunk/WAeUPTool.py @ 1466

Last change on this file since 1466 was 1462, checked in by joachim, 18 years ago

fix

  • Property svn:keywords set to Id
File size: 18.7 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 1462 2007-02-21 18:00:57Z 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    def generatePassword(self,s=None): ###(
77        import random
78        r = random
79        ##if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
80        if s is None:
81            s = 'abcdefghklmnpqrstuvwxy23456789'
82        pw = ''
83        while len(pw) < 6:
84            pw += r.choice(s)
85        return pw
86    ###)
87
88    security.declareProtected(ModifyPortalContent,'getCredential') ###(
89    def getCredential(self,student_id):
90        "return a student password"
91        student_entry = getattr(self.portal_directories.students,student_id,None)
92        if student_entry is None:
93            return None
94        return getattr(student_entry,"password","not set")
95    ###)
96
97    security.declarePublic('checkPassword') ###(
98    def checkPassword(self,password):
99        "return a student password"
100        student_entry = getattr(self.portal_directories.students,student_id,None)
101        if student_entry is None:
102            return False
103        return getattr(student_entry,"password","not set") == password
104    ###)
105
106    security.declareProtected(ModifyPortalContent,'doCommit') ###(
107    def doCommit(self,logger=None):
108        "commit some transactions"
109        transaction.commit()
110    ###)
111
112    security.declarePublic('loadStudentFoto') ###(
113    def loadStudentFoto(self,student):
114        "return a student passport picture"
115        app_doc = student.application.getContent()
116        clear = student.clearance
117        clear_doc = clear.getContent()
118        matric_no = clear_doc.matric_no.upper()
119        picture1 ="%s/import/pictures_returning/%s.jpg" % (i_home,matric_no)
120        picture2 ="%s/import/pictures_returning/%s.JPG" % (i_home,matric_no)
121        #import pdb;pdb.set_trace()
122        if os.path.exists(picture1):
123            file = open(picture1)
124        elif os.path.exists(picture2):
125            file = open(picture2)
126        else:
127            return "passport picture not found %s" % picture1
128
129        outfile = file.read()
130        app_doc.manage_addFile('passport',
131                               file=outfile,
132                               title="%s.jpg" % matric_no)
133        return "successfully loaded passport picture"
134    ###)
135
136    security.declareProtected(ModifyPortalContent,'createOne') ###(
137    def createOne(self,students_folder,student_brain,letter,commit=False):
138        sid = self.waeup_tool.generateStudentId(letter)
139        students_folder.invokeFactory('Student', sid)
140        student = getattr(students_folder,sid)
141        self.portal_workflow.doActionFor(student,'return')
142        student.manage_setLocalRoles(sid, ['Owner',])
143        matric_no = student_brain.matric_no
144        jamb_reg_no = student_brain.Entryregno
145        self.students_catalog.addRecord(id = sid,
146                                           matric_no = matric_no,
147                                           jamb_reg_no = jamb_reg_no,
148                                           sex = student_brain.Sex == "F",
149                                           name = "%s %s %s" % (student_brain.Firstname,
150                                                                student_brain.Middlename,
151                                                                student_brain.Lastname)
152                                        )
153        if commit:
154            transaction.commit()
155        return sid,jamb_reg_no
156    ###)
157
158    security.declareProtected(ModifyPortalContent,'createStudent') ###(
159    def createStudent(self,dict):
160        students_folder = self.portal_url.getPortalObject().campus.students
161        sid = self.waeup_tool.generateStudentId('?')
162        students_folder.invokeFactory('Student', sid)
163        student_obj = getattr(students_folder,sid)
164        password = self.generatePassword()
165        self.makeStudentMember(sid,password)
166        status,entry_mode = dict.get('entry_mode').split('_')
167        wfaction = 'return'
168        if status == "NEW":
169            wfaction = 'admit'
170        matric_no = dict.get('matric_no')
171        email = dict.get('email')
172        level = dict.get('level')
173        jamb_reg_no = dict.get('jamb_reg_no')
174        study_course = dict.get('study_course')
175        self.portal_workflow.doActionFor(student_obj,wfaction)
176        student_obj.manage_setLocalRoles(sid, ['Owner',])
177        student_obj.invokeFactory('StudentApplication','application')
178        application = student_obj.application
179        self.portal_workflow.doActionFor(application,'open',dest_container=application)
180        da = {'Title': 'Application Data'}
181        student_obj.invokeFactory('StudentPersonal','personal')
182        da['entry_mode'] = entry_mode
183        personal = student_obj.personal
184        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
185        dp = {'Title': 'Personal Data'}
186        student_obj.invokeFactory('StudentClearance','clearance')
187        clearance = student_obj.clearance
188        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
189        dc = {'Title': 'Clearance/Eligibility Record'}
190        dc['matric_no'] = matric_no
191        da['app_email'] = dp['email'] = email
192        da['jamb_reg_no'] = jamb_reg_no
193        dp['firstname'] = dict.get('firstname')
194        dp['middlename'] = dict.get('middlename')
195        dp['lastname'] = dict.get('lastname')
196        da['jamb_lastname'] = "%(firstname)s %(middlename)s %(lastname)s" % dict
197        sex = dict.get('sex')
198        if sex:
199            da['jamb_sex'] = 'F'
200        else:
201            da['jamb_sex'] = 'M'
202        dp['sex'] = sex
203        application.getContent().edit(mapping=da)
204        self.portal_workflow.doActionFor(application,'close',dest_container=application)
205        personal.getContent().edit(mapping=dp)
206        clearance.getContent().edit(mapping=dc)
207        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
208        catd = {}
209        catd['id'] = sid
210        catd['entry_mode']= entry_mode
211        catd['email'] = email
212        catd['jamb_reg_no'] = jamb_reg_no
213        catd['matric_no'] = matric_no
214        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
215        catd['sex'] = dp['sex']
216        catd['level'] = level
217        certificate_brain = self.getCertificateBrain(study_course)
218        if certificate_brain:
219            cpath = certificate_brain.getPath().split('/')
220            catd['faculty'] = cpath[-4]
221            catd['department'] = cpath[-3]
222            catd['course'] = study_course
223        self.students_catalog.addRecord(**catd)
224        #
225        # Study Course
226        #
227        student_obj.invokeFactory('StudentStudyCourse','study_course')
228        sc = student_obj.study_course
229        self.portal_workflow.doActionFor(sc,'open',dest_container=sc)
230        dsc = {}
231        dsc['study_course'] = study_course
232        dsc['current_level'] = level
233        sc.getContent().edit(mapping=dsc)
234
235        return sid,password
236    ###)
237
238    security.declarePublic('getCertificateBrain') ###(
239    def getCertificateBrain(self,cert_id):
240        "do it"
241        res = ZCatalog.searchResults(self.portal_catalog,
242                                {'portal_type':"Certificate",
243                                      'id': cert_id})
244        if res:
245            return res[0]
246        return None
247    ###)
248
249    security.declarePublic('findStudentByMatricelNo') ###(
250    def findStudentByMatricelNo(self,matric_no):
251        "do it"
252        res = ZCatalog.searchResults(self.portal_catalog,
253                                {'portal_type':"StudentClearance",
254                                 'SearchableText': matric_no})
255        if res:
256            return res[0]
257        return None
258    ###)
259
260    security.declarePublic('makeStudentMember') ###(
261    def makeStudentMember(self,sid,password='uNsEt'):
262        """make the student a member"""
263        membership = self.portal_membership
264        membership.addMember(sid,
265                             password ,
266                             roles=('Member',
267                                     'Student',
268                                     ),
269                             domains='',
270                             properties = {'memberareaCreationFlag': False,
271                                           'homeless': True},)
272        member = membership.getMemberById(sid)
273        self.portal_registration.afterAdd(member, sid, password, None)
274        #self.manage_setLocalRoles(sid, ['Owner',])
275    ###)
276
277    security.declarePublic('makeStudentData') ###(
278    def makeStudentData(self,student_id,email=None,phone_nr=None):
279        "create Datastructure for a returning Student"
280        #import pdb;pdb.set_trace()
281        logger = logging.getLogger('Student.CreateData')
282        students_folder = self.portal_url.getPortalObject().campus.students
283        res = self.students_catalog(id=student_id)
284        if res:
285            st = res[0]
286        res = self.returning_import(matric_no = st.matric_no)
287        if res:
288            student = res[0]
289        logger.info('"%s", "creating Datastructure"' % student_id)
290        s_results = self.results_import(matric_no = st.matric_no)
291        lnr = self.getLevelFromResultsCosCode(s_results)
292        level = "%d00" % lnr
293        verdict,elegible = self.getVerdict(s_results[0].Verdict)
294        if elegible:
295            level = "%d00" % (lnr + 1)
296##        level = s_results[0].Level
297##        for result in s_results:
298##            if level != result.Level:
299##                logger.info('"%s", "Levels differ","%s != %s"' % (student_id,level,result.Level))
300        #student should not be allowed to perform this transition
301        #wftool = self.portal_workflow
302        #wftool.doActionFor(student,'return')
303        certcode_org = student.Coursemajorcode
304        certcode = makeCertificateCode(certcode_org)
305        certificate_brain = self.getCertificateBrain(certcode)
306        if not certificate_brain:
307            em = 'Certificate %s org-code %s not found\n' % (certcode, certcode_org)
308            logger.info(em)
309        matric_no = student.matric_no
310        sid = student_id
311        student_obj = getattr(students_folder,sid)
312        student_obj.invokeFactory('StudentApplication','application')
313        application = student_obj.application
314        self.portal_workflow.doActionFor(application,'open',dest_container=application)
315        da = {'Title': 'Application Data'}
316        student_obj.invokeFactory('StudentPersonal','personal')
317        da['jamb_reg_no'] = student.Entryregno
318        em = self.getEntryMode(student.Entryregno)
319##        em = student.Mode_of_Entry
320##        if em in ('DIRECT', 'DIRECT ENTRY',):
321##            em = 'DE'
322##        elif em in ('U.M.E', 'UNE',):
323##            em = 'UME'
324##        elif not em:
325##            em = "unknown"
326        da['entry_mode'] = em
327        personal = student_obj.personal
328        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
329        dp = {'Title': 'Personal Data'}
330        student_obj.invokeFactory('StudentClearance','clearance')
331        clearance = student_obj.clearance
332        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
333        dc = {'Title': 'Clearance/Eligibility Record'}
334        dc['matric_no'] = matric_no
335        state = student.State
336        lga = student.LGA
337        if state and lga:
338            lga =  state + ' / ' + lga
339        else:
340            lga = "None"
341        da['jamb_lga'] = dc['lga'] = lga
342        da['app_email'] = dp['email'] = email
343        da['app_mobile'] = dp['phone'] = phone_nr
344        dp['firstname'] = student.Firstname
345        dp['middlename'] = student.Middlename
346        dp['lastname'] = student.Lastname
347        da['jamb_lastname'] = "%s %s %s" % (student.Firstname,student.Middlename,student.Lastname)
348        da['jamb_sex'] = student.Sex
349        dp['sex'] = student.Sex == 'F'
350        dp['perm_address'] = student.Permanent_Address
351        application.getContent().edit(mapping=da)
352        self.portal_workflow.doActionFor(application,'close',dest_container=application)
353        personal.getContent().edit(mapping=dp)
354        clearance.getContent().edit(mapping=dc)
355        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
356        catd = {}
357        catd['id'] = sid
358        catd['entry_mode']= da['entry_mode']
359        catd['matric_no'] = matric_no
360        catd['jamb_reg_no'] = da['jamb_reg_no']
361        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
362        catd['sex'] = dp['sex']
363        catd['level'] = level
364        catd['verdict'] = verdict
365        if certificate_brain:
366            cpath = certificate_brain.getPath().split('/')
367            catd['faculty'] = cpath[-4]
368            catd['department'] = cpath[-3]
369            catd['course'] = certcode
370        self.students_catalog.modifyRecord(**catd)
371        #
372        # Study Course
373        #
374        student_obj.invokeFactory('StudentStudyCourse','study_course')
375        studycourse = student_obj.study_course
376        self.portal_workflow.doActionFor(studycourse,'open',dest_container=studycourse)
377        dsc = {}
378        dsc['study_course'] = certcode
379        dsc['current_level'] = level
380        dsc['current_verdict'] = verdict
381        studycourse.getContent().edit(mapping=dsc)
382        #
383        # Level
384        #
385##        l = getattr(studycourse,level,None)
386##        if l is None:
387##            studycourse.invokeFactory('StudentStudyLevel', level)
388##            l = getattr(studycourse, level)
389##            self.portal_workflow.doActionFor(l,'open',dest_container=l)
390##            l.getContent().edit(mapping={'Title': "Level %s" % level})
391###)
392
393    security.declarePublic('makeStudentLevel') ###(
394    def makeStudentLevel(self,student_id):
395        "create the StudyLevel for a returning Student"
396        #import pdb;pdb.set_trace()
397        logger = logging.getLogger('Student.CreateLevel')
398        students_folder = self.portal_url.getPortalObject().campus.students
399        res = self.students_catalog(id=student_id)
400        if res:
401            st = res[0]
402        course = st.course
403        matric_no = st.matric_no
404        level = st.level
405        res = self.results_import(matric_no = matric_no)
406        if res:
407            results = res
408        logger.info('"%s", "creating Level", "%s"' % (student_id,level))
409        #
410        # Level
411        #
412        student_obj = getattr(self.portal_url.getPortalObject().campus.students,student_id)
413        studycourse = getattr(student_obj,"study_course",None)
414        self.portal_workflow.doActionFor(studycourse,'close_for_edit',dest_container=studycourse)
415        l = getattr(studycourse,level,None)
416        if l is None:
417            studycourse.invokeFactory('StudentStudyLevel', level)
418            l = getattr(studycourse, level)
419            self.portal_workflow.doActionFor(l,'open',dest_container=l)
420            l.getContent().edit(mapping={'Title': "Level %s" % level})
421        ###)
422
423    security.declarePublic('getAccommodationInfo') ###(
424    def getAccommodationInfo(self,bed):
425        """return Accommodation Info"""
426        info = {}
427        hall,block,room,letter = bed.split('_')
428        res = ZCatalog.searchResults(self.portal_catalog,portal_type="AccoHall",id=hall)
429        if res and len(res) == 1:
430            hall_brain = res[0]
431            hall_doc = hall_brain.getObject().getContent()
432        else:
433            return info
434        info['hall_title'] = hall_brain.Title
435        info['maintenance_code'] = hall_doc.maintenance_code
436        res = ZCatalog.searchResults(self.portal_catalog,portal_type="ScratchCardBatch")
437        batch_doc = None
438        for brain in res:
439            if brain.id.startswith(info['maintenance_code']):
440                batch_doc = brain.getObject().getContent()
441                break
442        if batch_doc is None:
443            info['maintenance_fee'] = None
444        else:
445            info['maintenance_fee'] = batch_doc.cost
446        return info
447    ###)
448
449    security.declareProtected(ModifyPortalContent,'deleteAllCourses') ###(
450    def deleteAllCourses(self,department="All"):
451        ''' delete the courses'''
452        pm = self.portal_membership
453        member = pm.getAuthenticatedMember()
454
455        if str(member) not in ("henrik","joachim"):
456            return "not possible"
457        if department == "All":
458            res = self.portal_catalog({'meta_type': 'Department'})
459        if len(res) < 1:
460            return "No Departments found"
461
462        deleted = []
463        for dep in res:
464            cf = dep.getObject().courses
465            if cf:
466                cf.manage_delObjects(ids=cf.objectIds())
467                deleted.append("deleted Courses in %s" % dep.getId)
468        return "\r".join(deleted)
469    ###)
470
471
472InitializeClass(WAeUPTool)
Note: See TracBrowser for help on using the repository browser.