source: WAeUP_SRP/trunk/WAeUPTool.py @ 1413

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

names from students_catalog

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