source: WAeUP_SRP/branches/srpp_on_branch/WAeUPTool.py @ 17941

Last change on this file since 17941 was 1287, checked in by Henrik Bettermann, 18 years ago

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 1287 2007-01-13 06:54:46Z henrik $
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
185        #student should not be allowed to perform this transition
186        #wftool = self.portal_workflow
187        #wftool.doActionFor(student,'return')
188
189        certcode_org = student.Coursemajorcode
190        certcode = makeCertificateCode(certcode_org)
191        certificate_brain = self.getCertificateBrain(certcode)
192        if not certificate_brain:
193            em = 'Certificate %s org-code %s not found\n' % (certcode, certcode_org)
194            logger.info(em)
195        level = student.Level
196        validlevel = False
197        try:
198            il = int(level) + 100
199            level = "%s" % il
200            validlevel = True
201        except:
202            em = '"%(matric_no)s","invalid Level","%(Level)s"' % student
203            logger.info(em)
204        if not validlevel:
205            erg = self.results_import(matric_no = student.matric_no)
206            level = 'xxx'
207            if erg:
208                level = erg[0].Level
209            try:
210                il = int(level) + 100
211                level = "%s" % il
212                em = '"%s","fixed Level from results_import","%s"' % (student.matric_no,erg[0].Level)
213                logger.info(em)
214                validlevel = True
215            except:
216                em = '"%s","invalid Level in results_import","%s"' % (student.matric_no,erg[0].Level)
217                logger.info(em)
218        matric_no = student.matric_no
219        sid = student_id
220        student_obj = getattr(students_folder,sid)
221        student_obj.invokeFactory('StudentApplication','application')
222        application = student_obj.application
223        self.portal_workflow.doActionFor(application,'open',dest_container=application)
224        da = {'Title': 'Application Data'}
225        student_obj.invokeFactory('StudentPersonal','personal')
226        da['jamb_reg_no'] = student.Entryregno
227        da['entry_mode'] = student.Mode_of_Entry
228        personal = student_obj.personal
229        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
230        dp = {'Title': 'Personal Data'}
231        student_obj.invokeFactory('StudentClearance','clearance')
232        clearance = student_obj.clearance
233        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
234        dc = {'Title': 'Clearance/Eligibility Record'}
235        dc['matric_no'] = matric_no
236        state = student.State
237        lga = student.LGA
238        if state and lga:
239            lga =  state + ' / ' + lga
240        else:
241            lga = "None"
242        da['jamb_lga'] = dc['lga'] = lga
243        da['app_email'] = dp['email'] = email
244        da['app_mobile'] = dp['phone'] = phone_nr
245        da['jamb_firstname'] = dp['firstname'] = student.Firstname
246        da['jamb_middlename'] = dp['middlename'] = student.Middlename
247        da['jamb_lastname'] = dp['lastname'] = student.Lastname
248        da['jamb_sex'] = student.Sex
249        dp['sex'] = student.Sex == 'F'
250        dp['perm_address'] = student.Permanent_Address
251        application.getContent().edit(mapping=da)
252        self.portal_workflow.doActionFor(application,'close',dest_container=application)
253        personal.getContent().edit(mapping=dp)
254        clearance.getContent().edit(mapping=dc)
255        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
256        catd = {}
257        catd['id'] = sid
258        catd['entry_mode']= da['entry_mode']
259        catd['matric_no'] = matric_no
260        catd['jamb_reg_no'] = da['jamb_reg_no']
261        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp
262        catd['sex'] = dp['sex']
263        catd['level'] = level
264        if certificate_brain:
265            cpath = certificate_brain.getPath().split('/')
266            catd['faculty'] = cpath[-4]
267            catd['department'] = cpath[-3]
268            catd['course'] = certcode
269        self.students_catalog.modifyRecord(**catd)
270        #
271        # Study Course
272        #
273        student_obj.invokeFactory('StudentStudyCourse','study_course')
274        studycourse = student_obj.study_course
275        self.portal_workflow.doActionFor(studycourse,'open',dest_container=studycourse)
276        dsc = {}
277        dsc['study_course'] = certcode
278        studycourse.getContent().edit(mapping=dsc)
279        #
280        # Level
281        #
282##        l = getattr(studycourse,level,None)
283##        if l is None:
284##            studycourse.invokeFactory('StudentStudyLevel', level)
285##            l = getattr(studycourse, level)
286##            self.portal_workflow.doActionFor(l,'open',dest_container=l)
287##            l.getContent().edit(mapping={'Title': "Level %s" % level})
288###)
289
290    security.declarePublic('makeStudentLevel') ###(
291    def makeStudentLevel(self,student_id):
292        "create the StudyLevel for a returning Student"
293        #import pdb;pdb.set_trace()
294        logger = logging.getLogger('Student.CreateLevel')
295        students_folder = self.portal_url.getPortalObject().campus.students
296        res = self.students_catalog(id=student_id)
297        if res:
298            st = res[0]
299        course = st.course
300        matric_no = st.matric_no
301        level = st.level
302        res = self.results_import(matric_no = matric_no)
303        if res:
304            results = res
305        logger.info('"%s", "creating Level", "%s"' % (student_id,level))
306        #
307        # Level
308        #
309        student_obj = getattr(self.portal_url.getPortalObject().campus.students,student_id)
310        studycourse = getattr(student_obj,"study_course",None)
311        self.portal_workflow.doActionFor(studycourse,'close_for_edit',dest_container=studycourse)
312        l = getattr(studycourse,level,None)
313        if l is None:
314            studycourse.invokeFactory('StudentStudyLevel', level)
315            l = getattr(studycourse, level)
316            self.portal_workflow.doActionFor(l,'open',dest_container=l)
317            l.getContent().edit(mapping={'Title': "Level %s" % level})
318        ###)
319
320    security.declarePublic('getAccommodationInfo') ###(
321    def getAccommodationInfo(self,bed):
322        """return Accommodation Info"""
323        info = {}
324        hall,block,room,letter = bed.split('_')
325        res = ZCatalog.searchResults(self.portal_catalog,portal_type="AccoHall",id=hall)
326        if res and len(res) == 1:
327            hall_brain = res[0]
328            hall_doc = hall_brain.getObject().getContent()
329        else:
330            return info
331        info['hall_title'] = hall_brain.Title
332        info['maintenance_code'] = hall_doc.maintenance_code
333        res = ZCatalog.searchResults(self.portal_catalog,portal_type="ScratchCardBatch")
334        batch_doc = None
335        for brain in res:
336            if brain.id.startswith(info['maintenance_code']):
337                batch_doc = brain.getObject().getContent()
338                break
339        if batch_doc is None:
340            info['maintenance_fee'] = None
341        else:
342            info['maintenance_fee'] = batch_doc.cost
343        return info
344    ###)
345
346    security.declareProtected(ModifyPortalContent,'deleteAllCourses') ###(
347    def deleteAllCourses(self,department="All"):
348        ''' delete the courses'''
349        pm = self.portal_membership
350        member = pm.getAuthenticatedMember()
351
352        if str(member) not in ("henrik","joachim"):
353            return "not possible"
354        if department == "All":
355            res = self.portal_catalog({'meta_type': 'Department'})
356        if len(res) < 1:
357            return "No Departments found"
358
359        deleted = []
360        for dep in res:
361            cf = dep.getObject().courses
362            if cf:
363                cf.manage_delObjects(ids=cf.objectIds())
364                deleted.append("deleted Courses in %s" % dep.getId)
365        return "\r".join(deleted)
366    ###)
367
368
369InitializeClass(WAeUPTool)
Note: See TracBrowser for help on using the repository browser.