source: WAeUP_SRP/trunk/WAeUPTool.py @ 1388

Last change on this file since 1388 was 1319, checked in by joachim, 18 years ago

A profiles/default/vocabularies/student_transfer_types.xml
A profiles/default/layouts/student_transfer.xml
M profiles/default/vocabularies.xml
M profiles/default/layouts.xml
AM skins/waeup_student/request_transfer.py
AM skins/waeup_student/request_transfer_form.pt
for request transfer
M profiles/default/students_catalog.xml
entry_mode index (in zmi)
M Students.py
fixEntryModeForReturning + fixAllEntryModeForReturning
M WAeUPTool.py
makeStudent fixed

  • Property svn:keywords set to Id
File size: 14.4 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 1319 2007-01-18 23:09:04Z 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.declarePublic('loadStudentFoto') ###(
86    def loadStudentFoto(self,student):
87        "return a student passport picture"
88        app_doc = student.application.getContent()
89        clear = student.clearance
90        clear_doc = clear.getContent()
91        matric_no = clear_doc.matric_no.upper()
92        picture1 ="%s/import/pictures_returning/%s.jpg" % (i_home,matric_no)
93        picture2 ="%s/import/pictures_returning/%s.JPG" % (i_home,matric_no)
94        #import pdb;pdb.set_trace()
95        if os.path.exists(picture1):
96            file = open(picture1)
97        elif os.path.exists(picture2):
98            file = open(picture2)
99        else:
100            return "passport picture not found %s" % picture1
101
102        outfile = file.read()
103        app_doc.manage_addFile('passport',
104                               file=outfile,
105                               title="%s.jpg" % matric_no)
106        return "successfully loaded passport picture"
107    ###)
108
109
110    security.declareProtected(ModifyPortalContent,'createOne') ###(
111    def createOne(self,students_folder,student_brain,letter,commit=False):
112        sid = self.waeup_tool.generateStudentId(letter)
113        students_folder.invokeFactory('Student', sid)
114        student = getattr(students_folder,sid)
115        self.portal_workflow.doActionFor(student,'return')
116        student.manage_setLocalRoles(sid, ['Owner',])
117        matric_no = student_brain.matric_no
118        jamb_reg_no = student_brain.Entryregno
119        self.students_catalog.addRecord(id = sid,
120                                           matric_no = matric_no,
121                                           jamb_reg_no = jamb_reg_no,
122                                           sex = student_brain.Sex == "F",
123                                           name = "%s %s %s" % (student_brain.Firstname,
124                                                                student_brain.Middlename,
125                                                                student_brain.Lastname)
126                                        )
127        if commit:
128            transaction.commit()
129        return sid,jamb_reg_no
130    ###)
131
132    security.declarePublic('getCertificateBrain') ###(
133    def getCertificateBrain(self,cert_id):
134        "do it"
135        res = ZCatalog.searchResults(self.portal_catalog,
136                                {'portal_type':"Certificate",
137                                      'id': cert_id})
138        if res:
139            return res[0]
140        return None
141    ###)
142
143    security.declarePublic('findStudentByMatricelNo') ###(
144    def findStudentByMatricelNo(self,matric_no):
145        "do it"
146        res = ZCatalog.searchResults(self.portal_catalog,
147                                {'portal_type':"StudentClearance",
148                                 'SearchableText': matric_no})
149        if res:
150            return res[0]
151        return None
152    ###)
153
154    security.declarePublic('makeStudentMember') ###(
155    def makeStudentMember(self,sid,password='uNsEt'):
156        """make the student a member"""
157        membership = self.portal_membership
158        membership.addMember(sid,
159                             password ,
160                             roles=('Member',
161                                     'Student',
162                                     ),
163                             domains='',
164                             properties = {'memberareaCreationFlag': False,
165                                           'homeless': True},)
166        member = membership.getMemberById(sid)
167        self.portal_registration.afterAdd(member, sid, password, None)
168        #self.manage_setLocalRoles(sid, ['Owner',])
169    ###)
170
171    security.declarePublic('makeStudentData') ###(
172    def makeStudentData(self,student_id,email=None,phone_nr=None):
173        "create Datastructure for a returning Student"
174        #import pdb;pdb.set_trace()
175        logger = logging.getLogger('Student.CreateData')
176        students_folder = self.portal_url.getPortalObject().campus.students
177        res = self.students_catalog(id=student_id)
178        if res:
179            st = res[0]
180        res = self.returning_import(matric_no = st.matric_no)
181        if res:
182            student = res[0]
183        logger.info('"%s", "creating Datastructure"' % student_id)
184        #student should not be allowed to perform this transition
185        #wftool = self.portal_workflow
186        #wftool.doActionFor(student,'return')
187        certcode_org = student.Coursemajorcode
188        certcode = makeCertificateCode(certcode_org)
189        certificate_brain = self.getCertificateBrain(certcode)
190        if not certificate_brain:
191            em = 'Certificate %s org-code %s not found\n' % (certcode, certcode_org)
192            logger.info(em)
193        level = student.Level
194        validlevel = False
195        try:
196            il = int(level) + 100
197            level = "%s" % il
198            validlevel = True
199        except:
200            em = '"%(matric_no)s","invalid Level","%(Level)s"' % student
201            logger.info(em)
202        if not validlevel:
203            erg = self.results_import(matric_no = student.matric_no)
204            level = 'xxx'
205            if erg:
206                level = erg[0].Level
207            try:
208                il = int(level) + 100
209                level = "%s" % il
210                em = '"%s","fixed Level from results_import","%s"' % (student.matric_no,erg[0].Level)
211                logger.info(em)
212                validlevel = True
213            except:
214                em = '"%s","invalid Level in results_import","%s"' % (student.matric_no,erg[0].Level)
215                logger.info(em)
216        matric_no = student.matric_no
217        sid = student_id
218        student_obj = getattr(students_folder,sid)
219        student_obj.invokeFactory('StudentApplication','application')
220        application = student_obj.application
221        self.portal_workflow.doActionFor(application,'open',dest_container=application)
222        da = {'Title': 'Application Data'}
223        student_obj.invokeFactory('StudentPersonal','personal')
224        da['jamb_reg_no'] = student.Entryregno
225        da['entry_mode'] = student.Mode_of_Entry
226        personal = student_obj.personal
227        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
228        dp = {'Title': 'Personal Data'}
229        student_obj.invokeFactory('StudentClearance','clearance')
230        clearance = student_obj.clearance
231        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
232        dc = {'Title': 'Clearance/Eligibility Record'}
233        dc['matric_no'] = matric_no
234        state = student.State
235        lga = student.LGA
236        if state and lga:
237            lga =  state + ' / ' + lga
238        else:
239            lga = "None"
240        da['jamb_lga'] = dc['lga'] = lga
241        da['app_email'] = dp['email'] = email
242        da['app_mobile'] = dp['phone'] = phone_nr
243        da['jamb_firstname'] = dp['firstname'] = student.Firstname
244        da['jamb_middlename'] = dp['middlename'] = student.Middlename
245        da['jamb_lastname'] = dp['lastname'] = student.Lastname
246        da['jamb_sex'] = student.Sex
247        dp['sex'] = student.Sex == 'F'
248        dp['perm_address'] = student.Permanent_Address
249        application.getContent().edit(mapping=da)
250        self.portal_workflow.doActionFor(application,'close',dest_container=application)
251        personal.getContent().edit(mapping=dp)
252        clearance.getContent().edit(mapping=dc)
253        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
254        catd = {}
255        catd['id'] = sid
256        catd['entry_mode']= da['entry_mode']
257        catd['matric_no'] = matric_no
258        catd['jamb_reg_no'] = da['jamb_reg_no']
259        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
260        catd['sex'] = dp['sex']
261        catd['level'] = level
262        if certificate_brain:
263            cpath = certificate_brain.getPath().split('/')
264            catd['faculty'] = cpath[-4]
265            catd['department'] = cpath[-3]
266            catd['course'] = certcode
267        self.students_catalog.modifyRecord(**catd)
268        #
269        # Study Course
270        #
271        student_obj.invokeFactory('StudentStudyCourse','study_course')
272        studycourse = student_obj.study_course
273        self.portal_workflow.doActionFor(studycourse,'open',dest_container=studycourse)
274        dsc = {}
275        dsc['study_course'] = certcode
276        studycourse.getContent().edit(mapping=dsc)
277        #
278        # Level
279        #
280##        l = getattr(studycourse,level,None)
281##        if l is None:
282##            studycourse.invokeFactory('StudentStudyLevel', level)
283##            l = getattr(studycourse, level)
284##            self.portal_workflow.doActionFor(l,'open',dest_container=l)
285##            l.getContent().edit(mapping={'Title': "Level %s" % level})
286###)
287
288    security.declarePublic('makeStudentLevel') ###(
289    def makeStudentLevel(self,student_id):
290        "create the StudyLevel for a returning Student"
291        #import pdb;pdb.set_trace()
292        logger = logging.getLogger('Student.CreateLevel')
293        students_folder = self.portal_url.getPortalObject().campus.students
294        res = self.students_catalog(id=student_id)
295        if res:
296            st = res[0]
297        course = st.course
298        matric_no = st.matric_no
299        level = st.level
300        res = self.results_import(matric_no = matric_no)
301        if res:
302            results = res
303        logger.info('"%s", "creating Level", "%s"' % (student_id,level))
304        #
305        # Level
306        #
307        student_obj = getattr(self.portal_url.getPortalObject().campus.students,student_id)
308        studycourse = getattr(student_obj,"study_course",None)
309        self.portal_workflow.doActionFor(studycourse,'close_for_edit',dest_container=studycourse)
310        l = getattr(studycourse,level,None)
311        if l is None:
312            studycourse.invokeFactory('StudentStudyLevel', level)
313            l = getattr(studycourse, level)
314            self.portal_workflow.doActionFor(l,'open',dest_container=l)
315            l.getContent().edit(mapping={'Title': "Level %s" % level})
316        ###)
317
318    security.declarePublic('getAccommodationInfo') ###(
319    def getAccommodationInfo(self,bed):
320        """return Accommodation Info"""
321        info = {}
322        hall,block,room,letter = bed.split('_')
323        res = ZCatalog.searchResults(self.portal_catalog,portal_type="AccoHall",id=hall)
324        if res and len(res) == 1:
325            hall_brain = res[0]
326            hall_doc = hall_brain.getObject().getContent()
327        else:
328            return info
329        info['hall_title'] = hall_brain.Title
330        info['maintenance_code'] = hall_doc.maintenance_code
331        res = ZCatalog.searchResults(self.portal_catalog,portal_type="ScratchCardBatch")
332        batch_doc = None
333        for brain in res:
334            if brain.id.startswith(info['maintenance_code']):
335                batch_doc = brain.getObject().getContent()
336                break
337        if batch_doc is None:
338            info['maintenance_fee'] = None
339        else:
340            info['maintenance_fee'] = batch_doc.cost
341        return info
342    ###)
343
344    security.declareProtected(ModifyPortalContent,'deleteAllCourses') ###(
345    def deleteAllCourses(self,department="All"):
346        ''' delete the courses'''
347        pm = self.portal_membership
348        member = pm.getAuthenticatedMember()
349
350        if str(member) not in ("henrik","joachim"):
351            return "not possible"
352        if department == "All":
353            res = self.portal_catalog({'meta_type': 'Department'})
354        if len(res) < 1:
355            return "No Departments found"
356
357        deleted = []
358        for dep in res:
359            cf = dep.getObject().courses
360            if cf:
361                cf.manage_delObjects(ids=cf.objectIds())
362                deleted.append("deleted Courses in %s" % dep.getId)
363        return "\r".join(deleted)
364    ###)
365
366
367InitializeClass(WAeUPTool)
Note: See TracBrowser for help on using the repository browser.