source: WAeUP_SRP/trunk/WAeUPTool.py @ 1170

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

createReturningStudent?matric_no=All,
now creates all students-baseobject. Commits every 100 objects
100 students with commit takes about 38 seconds.

  • Property svn:keywords set to Id
File size: 10.6 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 1170 2007-01-01 18:08:45Z joachim $
20"""The WAeUPTool.
21
22$Id: WAeUPTool.py 1170 2007-01-01 18:08:45Z joachim $
23"""
24
25from AccessControl import ClassSecurityInfo
26from Acquisition import aq_inner
27from Acquisition import aq_parent
28from Globals import DTMLFile
29from Globals import InitializeClass
30from OFS.SimpleItem import SimpleItem
31
32from Products.CMFCore.ActionProviderBase import ActionProviderBase
33from Products.CMFCore.permissions import View
34from Products.ZCatalog.ZCatalog import ZCatalog
35from Products.CMFCore.permissions import ModifyPortalContent
36from Products.CMFCore.utils import UniqueObject
37from Students import makeCertificateCode
38import logging
39import transaction
40
41
42class WAeUPTool(UniqueObject, SimpleItem, ActionProviderBase):
43    """WAeUP tool"""
44
45    id = 'waeup_tool'
46    meta_type = 'WAeUP Tool'
47    _actions = ()
48
49    security = ClassSecurityInfo()
50    security.declareObjectProtected(View)
51
52    manage_options = ( ActionProviderBase.manage_options
53                     + SimpleItem.manage_options
54                     )
55
56    def generateStudentId(self,letter): ###(
57        import random
58        r = random
59        if letter not in ('ABCDEFGIHKLMNOPQRSTUVWXY'):
60            letter= r.choice('ABCDEFGHKLMNPQRSTUVWXY')
61        students = self.portal_url.getPortalObject().campus.students
62        sid = "%c%d" % (letter,r.randint(99999,1000000))
63        while hasattr(students, sid):
64            sid = "%c%d" % (letter,r.randint(99999,1000000))
65        return sid
66    ###)
67
68    security.declareProtected(ModifyPortalContent,'createOne') ###(
69    def createOne(self,student_brain,commit=False):
70        students_folder = self.portal_url.getPortalObject().campus.students
71        sid = self.waeup_tool.generateStudentId('?')
72        students_folder.invokeFactory('Student', sid)
73        student = getattr(students_folder,sid)
74        self.portal_workflow.doActionFor(student,'return')
75        student.manage_setLocalRoles(sid, ['Owner',])
76        matric_no = student_brain.matric_no
77        jamb_reg_no = student_brain.Entryregno
78        self.students_catalog.addRecord(id = sid,
79                                           matric_no = matric_no,
80                                           jamb_reg_no = jamb_reg_no,
81                                           sex = student_brain.Sex == "F",
82                                           name = "%s %s %s" % (student_brain.Firstname,
83                                                                student_brain.Middlename,
84                                                                student_brain.Lastname)
85                                        )
86        if commit:
87            transaction.commit()
88        return sid,jamb_reg_no
89    ###)
90
91    security.declarePublic('getCertificateBrain') ###(
92    def getCertificateBrain(self,cert_id):
93        "do it"
94        res = ZCatalog.searchResults(self.portal_catalog,
95                                {'portal_type':"Certificate",
96                                      'id': cert_id})
97        if res:
98            return res[0]
99        return None
100    ###)
101
102    security.declarePublic('findStudentByMatricelNo') ###(
103    def findStudentByMatricelNo(self,matric_no):
104        "do it"
105        res = ZCatalog.searchResults(self.portal_catalog,
106                                {'portal_type':"StudentClearance",
107                                 'SearchableText': matric_no})
108        if res:
109            return res[0]
110        return None
111    ###)
112
113    security.declarePublic('makeStudentMember') ###(
114    def makeStudentMember(self,sid,password='uNsEt'):
115        """make the student a member"""
116        membership = self.portal_membership
117        membership.addMember(sid,
118                             password ,
119                             roles=('Member',
120                                     'Student',
121                                     ),
122                             domains='',
123                             properties = {'memberareaCreationFlag': False,
124                                           'homeless': True},)
125        member = membership.getMemberById(sid)
126        self.portal_registration.afterAdd(member, sid, password, None)
127        self.manage_setLocalRoles(sid, ['Owner',])
128    ###)
129
130    security.declarePublic('makeStudentData') ###(
131    def makeStudentData(self,student_id,email=None,phone_nr=None):
132        "create Datastructure for a returning Student"
133        #import pdb;pdb.set_trace()
134        logger = logging.getLogger('Student.CreateData')
135        students_folder = self.portal_url.getPortalObject().campus.students
136        res = self.students_catalog(id=student_id)
137        if res:
138            st = res[0]
139        res = self.returning_import(matric_no = st.matric_no)
140        if res:
141            student = res[0]
142        logger.info('"%s", "creating Datastructure"' % student_id)
143        certcode_org = student.Coursemajorcode
144        certcode = makeCertificateCode(certcode_org)
145        certificate_brain = self.getCertificateBrain(certcode)
146        if not certificate_brain:
147            em = 'Certificate %s org-code %s not found\n' % (certcode, certcode_org)
148            logger.info(em)
149        level = student.Level
150        try:
151            int(level)
152        except:
153            em = '"%(matric_no)s","invalid Level","%(Level)s"' % student
154            logger.info(em)
155        matric_no = student.matric_no
156        sid = student_id
157        student_obj = getattr(students_folder,sid)
158        student_obj.invokeFactory('StudentApplication','application')
159        application = student_obj.application
160        self.portal_workflow.doActionFor(application,'open',dest_container=application)
161        da = {'Title': 'Application Data'}
162        student_obj.invokeFactory('StudentPersonal','personal')
163        da['jamb_reg_no'] = student.Entryregno
164        da['entry_mode'] = student.Mode_of_Entry
165        personal = student_obj.personal
166        self.portal_workflow.doActionFor(personal,'open',dest_container=personal)
167        dp = {'Title': 'Personal Data'}
168        student_obj.invokeFactory('StudentClearance','clearance')
169        clearance = student_obj.clearance
170        self.portal_workflow.doActionFor(clearance,'open',dest_container=clearance)
171        dc = {'Title': 'Clearance/Eligibility Record'}
172        dc['matric_no'] = matric_no
173        state = student.State
174        lga = student.LGA
175        if state and lga:
176            lga =  state + ' / ' + lga
177        else:
178            lga = "None"
179        dc['lga'] = lga
180        dp['email'] = email
181        dp['phone'] = phone_nr
182        dp['firstname'] = student.Firstname
183        dp['middlename'] = student.Middlename
184        dp['lastname'] = student.Lastname
185        dp['sex'] = student.Sex == 'F'
186        dp['perm_address'] = student.Permanent_Address
187        application.getContent().edit(mapping=da)
188        self.portal_workflow.doActionFor(application,'close',dest_container=application)
189        personal.getContent().edit(mapping=dp)
190        clearance.getContent().edit(mapping=dc)
191        self.portal_workflow.doActionFor(clearance,'close',dest_container=clearance)
192        catd = {}
193        catd['id'] = sid
194        catd['entry_mode']= da['entry_mode']
195        catd['matric_no'] = matric_no
196        catd['jamb_reg_no'] = da['jamb_reg_no']
197        catd['name'] = "%(firstname)s %(middlename)s %(lastname)s" % dp 
198        catd['sex'] = dp['sex']
199        catd['level'] = level
200        if certificate_brain:
201            cpath = certificate_brain.getPath().split('/')
202            catd['faculty'] = cpath[-4]
203            catd['department'] = cpath[-3]
204            catd['course'] = certcode
205        self.students_catalog.modifyRecord(**catd)
206        #
207        # Study Course
208        #
209        student_obj.invokeFactory('StudentStudyCourse','study_course')
210        studycourse = student_obj.study_course
211        self.portal_workflow.doActionFor(studycourse,'open',dest_container=studycourse)
212        dsc = {}
213        dsc['study_course'] = certcode
214        studycourse.getContent().edit(mapping=dsc)
215        #
216        # Level
217        #
218##        l = getattr(studycourse,level,None)
219##        if l is None:
220##            studycourse.invokeFactory('StudentStudyLevel', level)
221##            l = getattr(studycourse, level)
222##            self.portal_workflow.doActionFor(l,'open',dest_container=l)
223##            l.getContent().edit(mapping={'Title': "Level %s" % level})
224
225    security.declarePublic('getAccommodationInfo') ###(
226    def getAccommodationInfo(self,bed):
227        """return Accommodation Info"""
228        info = {}
229        hall,block,room,letter = bed.split('_')
230        res = ZCatalog.searchResults(self.portal_catalog,portal_type="AccoHall",id=hall)
231        if res and len(res) == 1:
232            hall_brain = res[0]
233            hall_doc = hall_brain.getObject().getContent()
234        else:
235            return info
236        info['hall_title'] = hall_brain.Title
237        info['maintenance_code'] = hall_doc.maintenance_code
238        res = ZCatalog.searchResults(self.portal_catalog,portal_type="ScratchCardBatch")
239        batch_doc = None
240        for brain in res:
241            if brain.id.startswith(info['maintenance_code']):
242                batch_doc = brain.getObject().getContent()
243                break
244        if batch_doc is None:
245            info['maintenance_fee'] = None
246        else:
247            info['maintenance_fee'] = batch_doc.cost
248        return info
249    ###)
250
251    security.declareProtected(ModifyPortalContent,'deleteAllCourses') ###(
252    def deleteAllCourses(self,department="All"):
253        ''' delete the courses'''
254        pm = self.portal_membership
255        member = pm.getAuthenticatedMember()
256
257        if str(member) not in ("henrik","joachim"):
258            return "not possible"
259        if department == "All":
260            res = self.portal_catalog({'meta_type': 'Department'})
261        if len(res) < 1:
262            return "No Departments found"
263
264        deleted = []
265        for dep in res:
266            cf = dep.getObject().courses
267            if cf:
268                cf.manage_delObjects(ids=cf.objectIds())
269                deleted.append("deleted Courses in %s" % dep.getId)
270        return "\r".join(deleted)
271    ###)
272
273
274InitializeClass(WAeUPTool)
Note: See TracBrowser for help on using the repository browser.