source: WAeUP_SRP/trunk/WAeUPTool.py @ 1417

Last change on this file since 1417 was 1415, checked in by joachim, 18 years ago

added new Function add_student

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