source: WAeUP_SRP/trunk/WAeUPTool.py @ 1285

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

upload passport foto during login for returning students.
filename of foto is matric_no.jpg in import/pictures_returning

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