source: WAeUP_SRP/trunk/WAeUPTool.py @ 1259

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

increaselevels

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