source: WAeUP_SRP/trunk/WAeUPTables.py @ 1897

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

modifications to use QueueCatalog?

  • Property svn:keywords set to Id
File size: 28.3 KB
RevLine 
[966]1#-*- mode: python; mode: fold -*-
[363]2# (C) Copyright 2005 AixtraWare <http://aixtraware.de>
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: WAeUPTables.py 1845 2007-06-02 11:01:49Z joachim $
20
21from zope.interface import implements
22from Globals import InitializeClass
23from Products.ZCatalog.ZCatalog import ZCatalog
[1620]24from Products.ZCatalog.ProgressHandler import ZLogHandler
[780]25from AccessControl import ClassSecurityInfo
26from Products.CMFCore.permissions import ModifyPortalContent
[1700]27import urllib
[1620]28import DateTime,time
[780]29import csv,re
30import logging
31import Globals
32p_home = Globals.package_home(globals())
33i_home = Globals.INSTANCE_HOME
[1845]34from Products.CMFCore.CatalogTool import CatalogTool
[1702]35from Products.AdvancedQuery import Eq, Between, Le,In
[780]36
[363]37from interfaces import IWAeUPTable
38
39class AttributeHolder(object):
40    pass
41
42def dict2ob(dict):
43    ob = AttributeHolder()
44    for key, value in dict.items():
45        setattr(ob, key, value)
46    return ob
47
[1845]48class RealCatalogTool(CatalogTool):
49    meta_type = 'Catalog Tool Real'
50    name = id = "portal_catalog_real"
51   
[834]52
[1146]53class WAeUPTable(ZCatalog): ###(
[834]54
[363]55    implements(IWAeUPTable)
[780]56    security = ClassSecurityInfo()
[834]57
[1620]58    def refreshCatalog(self, clear=0, pghandler=None):
59        """ don't refresh for a normal table """
60
61        if self.REQUEST and self.REQUEST.RESPONSE:
62            self.REQUEST.RESPONSE.redirect(
63              URL1 +
64              '/manage_catalogAdvanced?manage_tabs_message=Catalog%20refresh%20not%20implemented')
65
66    def manage_catalogClear(self, REQUEST=None, RESPONSE=None, URL1=None):
67        """ clears the whole enchilada """
68        #self._catalog.clear()
69
70        if REQUEST and RESPONSE:
71            RESPONSE.redirect(
72              URL1 +
73              '/manage_catalogAdvanced?manage_tabs_message=Catalog%20Clearing%20disabled')
74
[363]75    def addRecord(self, **data):
[502]76        # The uid is the same as "bed".
77        uid = data[self.key]
78        res = self.searchResults({"%s" % self.key : uid})
79        if len(res) > 0:
80            raise ValueError("More than one record with uid %s" % uid)
81        self.catalog_object(dict2ob(data), uid=uid)
82        return uid
[834]83
[363]84    def deleteRecord(self, uid):
85        self.uncatalog_object(uid)
[834]86
[502]87    def searchAndSetRecord(self, **data):
88        raise NotImplemented
89
90    def modifyRecord(self, **data):
91        #records = self.searchResults(uid=uid)
92        uid = data[self.key]
93        records = self.searchResults({"%s" % self.key : uid})
[363]94        if len(records) > 1:
95            # Can not happen, but anyway...
96            raise ValueError("More than one record with uid %s" % uid)
97        if len(records) == 0:
98            raise KeyError("No record for uid %s" % uid)
99        record = records[0]
100        record_data = {}
101        for field in self.schema() + self.indexes():
102            record_data[field] = getattr(record, field)
103        # Add the updated data:
104        record_data.update(data)
105        self.catalog_object(dict2ob(record_data), uid)
106
[1062]107    def reindexIndex(self, name, REQUEST,pghandler=None):
108        if isinstance(name, str):
109            name = (name,)
110        paths = self._catalog.uids.items()
111        i = 0
112        #import pdb;pdb.set_trace()
113        for p,rid in paths:
114            i += 1
115            metadata = self.getMetadataForRID(rid)
116            record_data = {}
117            for field in name:
118                record_data[field] = metadata.get(field)
119            uid = metadata.get(self.key)
120            self.catalog_object(dict2ob(record_data), uid, idxs=name,
121                                update_metadata=0)
[1082]122
[780]123    security.declareProtected(ModifyPortalContent,"exportAllRecords")
124    def exportAllRecords(self):
125        "export a WAeUPTable"
126        #import pdb;pdb.set_trace()
127        fields = [field for field in self.schema()]
128        format = ','.join(['"%%(%s)s"' % fn for fn in fields])
129        csv = []
130        csv.append(','.join(['"%s"' % fn for fn in fields]))
131        for uid in self._catalog.uids:
132            records = self.searchResults({"%s" % self.key : uid})
133            if len(records) > 1:
134                # Can not happen, but anyway...
135                raise ValueError("More than one record with uid %s" % uid)
136            if len(records) == 0:
137                raise KeyError("No record for uid %s" % uid)
138            rec = records[0]
139            csv.append(format % rec)
140        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
141        open("%s/import/%s-%s.csv" % (i_home,self.getId(),current),"w+").write('\n'.join(csv))
[834]142
[1146]143###)
[834]144
[1146]145class AccommodationTable(WAeUPTable): ###(
[834]146
[404]147    meta_type = 'WAeUP Accommodation Tool'
[502]148    name = "accommodation"
149    key = "bed"
[363]150    def __init__(self):
[404]151        WAeUPTable.__init__(self, 'portal_accommodation')
[363]152
[635]153    def searchAndReserveBed(self, student_id,bed_type):
154        records = self.searchResults({'student' : student_id})
155        if len(records) > 0:
[1293]156            return -1,"Student with Id %s already booked bed %s." % (student_id,records[0].bed)
[834]157
[673]158        records = [r for r in self.searchResults({'bed_type' : bed_type}) if not r.student]
[686]159        #import pdb;pdb.set_trace()
[635]160        if len(records) == 0:
[1306]161            return -2,"No bed available"
[635]162        rec = records[0]
163        self.modifyRecord(bed=rec.bed,student=student_id)
[1571]164        s_logger = logging.getLogger('WAeUPTables.AccommodationTable.searchAndReserveBed')
165        s_logger.info('%s reserved bed %s' % (student_id,rec.bed))
[635]166        return 1,rec.bed
[363]167
[834]168
[404]169InitializeClass(AccommodationTable)
[411]170
[1146]171###)
172
173class PinTable(WAeUPTable): ###(
[1030]174    from ZODB.POSException import ConflictError
[440]175    meta_type = 'WAeUP Pin Tool'
[502]176    name = "pins"
177    key = 'pin'
[440]178    def __init__(self):
179        WAeUPTable.__init__(self, 'portal_pins')
[1082]180
181
[710]182    def searchAndSetRecord(self, uid, student_id,prefix):
[502]183        #records = self.searchResults(uid=uid)
[710]184        records = self.searchResults(student = student_id)
[990]185        #import pdb;pdb.set_trace()
[1776]186        if len(records) > 0 and prefix in ('CLR','APP'):
[710]187            for r in records:
[834]188                if r.pin != uid and r.prefix_batch.startswith(prefix):
[710]189                    return -2
[502]190        records = self.searchResults({"%s" % self.key : uid})
191        if len(records) > 1:
192            # Can not happen, but anyway...
193            raise ValueError("More than one record with uid %s" % uid)
194        if len(records) == 0:
195            return -1
196        record = records[0]
197        if record.student == "":
198            record_data = {}
199            for field in self.schema() + self.indexes():
200                record_data[field] = getattr(record, field)
201            # Add the updated data:
[635]202            record_data['student'] = student_id
[1030]203            try:
204                self.catalog_object(dict2ob(record_data), uid)
205                return 1
206            except ConflictError:
207                return 2
[990]208        if record.student.upper() != student_id.upper():
[502]209            return 0
[997]210        if record.student.upper() == student_id.upper():
[502]211            return 2
[997]212        return -3
[440]213
214InitializeClass(PinTable)
215
[1146]216###)
[966]217
[1146]218class PumeResultsTable(WAeUPTable): ###(
219
[966]220    meta_type = 'WAeUP PumeResults Tool'
221    name = "pumeresults"
222    key = "jamb_reg_no"
223    def __init__(self):
224        WAeUPTable.__init__(self, 'portal_pumeresults')
225
226
227InitializeClass(PumeResultsTable)
228
[1146]229###)
[971]230
[1146]231class StudentsCatalog(WAeUPTable): ###(
[1620]232    security = ClassSecurityInfo()
[1146]233
[971]234    meta_type = 'WAeUP Students Catalog'
235    name = "students_catalog"
236    key = "id"
[1700]237    affected_types = {   ###(
[1749]238                      'StudentApplication':
[1707]239                          {'id': 'application',
240                           'fields':
[1700]241                             ('jamb_reg_no',
242                              'entry_mode',
[1749]243                              #'entry_level',
[1700]244                              'entry_session',
[1707]245                              )
246                              },
[1700]247                      'StudentClearance':
[1707]248                          {'id': 'clearance',
249                           'fields':
[1700]250                             ('matric_no',
[1707]251                              )
252                              },
[1700]253                         'StudentPersonal':
[1707]254                          {'id': 'personal',
255                           'fields':
[1700]256                             ('name',
257                              'sex',
258                              'email',
259                              'phone',
[1707]260                              )
261                              },
[1700]262                         'StudentStudyCourse':
[1707]263                          {'id': 'study_course',
264                           'fields':
[1700]265                             ('course',
266                              'faculty',
267                              'department',
268                              'level',
[1705]269                              'mode',
[1700]270                              'session',
271                              'verdict',
[1707]272                              )
273                              },
[1700]274                         }
275    ###)
[1625]276
[971]277    def __init__(self):
278        WAeUPTable.__init__(self, 'students_catalog')
[1620]279        return
[1625]280
[1700]281    def manage_catalogClear(self, REQUEST=None, RESPONSE=None, URL1=None):
282        """ clears the whole enchilada """
283        self._catalog.clear()
[971]284
[1700]285        if REQUEST and RESPONSE:
286            RESPONSE.redirect(
287              URL1 +
288              '/manage_catalogAdvanced?manage_tabs_message=Catalog%20Cleared')
[971]289
[1700]290    def manage_catalogReindex(self, REQUEST, RESPONSE, URL1): ###(
291        """ clear the catalog, then re-index everything """
292
293        elapse = time.time()
294        c_elapse = time.clock()
295
296        pgthreshold = self._getProgressThreshold()
297        handler = (pgthreshold > 0) and ZLogHandler(pgthreshold) or None
298        self.refreshCatalog(clear=1, pghandler=handler)
299
300        elapse = time.time() - elapse
301        c_elapse = time.clock() - c_elapse
302
303        RESPONSE.redirect(
304            URL1 +
305            '/manage_catalogAdvanced?manage_tabs_message=' +
306            urllib.quote('Catalog Updated \n'
307                         'Total time: %s\n'
308                         'Total CPU time: %s' % (`elapse`, `c_elapse`)))
309    ###)
310
311    def get_from_doc_department(self,doc): ###(
[1620]312        "return the students department"
[1700]313        if doc is None:
[1620]314            return None
[1700]315        certificate_res = self.portal_catalog(id = doc.study_course)
[1620]316        if len(certificate_res) != 1:
317            return None
318        return certificate_res[0].getPath().split('/')[-3]
319
[1700]320    def get_from_doc_faculty(self,doc):
321        "return the students faculty"
322        if doc is None:
[1620]323            return None
[1700]324        certificate_res = self.portal_catalog(id = doc.study_course)
325        if len(certificate_res) != 1:
326            return None
327        return certificate_res[0].getPath().split('/')[-4]
[1620]328
[1700]329    def get_from_doc_level(self,doc):
330        "return the students level"
331        if doc is None:
[1620]332            return None
[1700]333        return getattr(doc,'current_level',None)
[1620]334
[1705]335    def get_from_doc_mode(self,doc):
336        "return the students mode"
[1700]337        if doc is None:
[1620]338            return None
[1705]339        cm = getattr(doc,'current_mode',None)
340        return cm
[1625]341
[1749]342
[1705]343    def get_from_doc_session(self,doc):
344        "return the students current_session"
345        if doc is None:
346            return None
347        return getattr(doc,'current_session',None)
348
[1700]349    def get_from_doc_entry_session(self,doc):
350        "return the students entry_session"
351        if doc is None:
[1620]352            return None
[1705]353        es = getattr(doc,'entry_session',None)
[1729]354        if es is not None and len(es) == 2:
[1705]355            return es
[1700]356        try:
357            digit = int(doc.jamb_reg_no[0])
358        except:
359            return "xx"
360        if digit < 8:
361            return "0%c" % doc.jamb_reg_no[0]
362        return "9%c" % doc.jamb_reg_no[0]
363
364    def get_from_doc_session(self,doc):
365        "return the students session"
366        if doc is None:
[1620]367            return None
[1700]368        return getattr(doc,'current_session',None)
[1620]369
[1700]370    def get_from_doc_course(self,doc):
[1620]371        "return the students study_course"
[1700]372        if doc is None:
[1620]373            return None
[1700]374        return getattr(doc,'study_course',None)
[1620]375
[1700]376    def get_from_doc_name(self,doc):
[1620]377        "return the students name from the personal"
[1700]378        if doc is None:
[1620]379            return None
380        return "%s %s %s" % (doc.firstname,doc.middlename,doc.lastname)
381
[1700]382    def get_from_doc_verdict(self,doc):
383        "return the students study_course"
384        if doc is None:
[1620]385            return None
[1700]386        return getattr(doc,'current_verdict',None)
[1702]387    ###)
[1620]388
[1702]389    def reindexIndex(self, name, REQUEST,pghandler=None): ###(
390        if isinstance(name, str):
391            name = (name,)
[1749]392        reindextypes = {}
[1702]393        reindex_special = []
394        #import pdb;pdb.set_trace()
395        for n in name:
396            if n in ("review_state","registered_courses"):
397                reindex_special.append(n)
398            else:
399                for pt in self.affected_types.keys():
[1707]400                    if n in self.affected_types[pt]['fields']:
[1702]401                        if reindextypes.has_key(pt):
402                            reindextypes[pt].append(n)
403                        else:
404                            reindextypes[pt]= [n]
405                        break
406        students = self.portal_catalog(portal_type="Student")
407        aq_portal = self.portal_catalog.evalAdvancedQuery
408        num_objects = len(students)
409        if pghandler:
410            pghandler.init('Refreshing catalog: %s' % self.absolute_url(1), num_objects)
411        noattr = set(('StudentClearance','StudentPersonal')) & set(reindextypes.keys())
412        for i in xrange(num_objects):
413            if pghandler: pghandler.report(i)
414            student_brain = students[i]
[1707]415            student_object = student_brain.getObject()
[1702]416            data = {}
417            modified = False
418            sid = data['id'] = student_brain.getId
419            if reindex_special and 'review_state' in reindex_special:
420                modified = True
421                data['review_state'] = student_brain.review_state
[1707]422            sub_objects = False
423            for pt in reindextypes.keys():
[1702]424                modified = True
[1707]425                try:
426                    doc = getattr(student_object,self.affected_types[pt]['id']).getContent()
427                    sub_objects = True
428                except:
429                    continue
430                for field in self.affected_types[pt]['fields']:
431                    if hasattr(self,'get_from_doc_%s' % field):
432                        data[field] = getattr(self,'get_from_doc_%s' % field)(doc)
433                    else:
434                        data[field] = getattr(doc,field)
435                #from pdb import set_trace;set_trace()
436            if not sub_objects and noattr:
437                import_res = self.returning_import(id = sid)
438                if not import_res:
439                    continue
440                import_record = import_res[0]
441                data['matric_no'] = import_record.matric_no
442                data['sex'] = import_record.Sex == 'F'
443                data['name'] = "%s %s %s" % (import_record.Firstname,
444                                             import_record.Middlename,
445                                             import_record.Lastname)
[1815]446                data['jamb_reg_no'] = import_record.Entryregno
[1702]447            if reindex_special and 'registered_courses' in reindex_special:
448                query = Eq('id','study_course') & Eq('path',student_brain.getPath())
449                brains = aq_portal(query)
450                while brains:
451                    study_course_path = brains[0].getPath()
452                    level_brains = self.portal_catalog(path = study_course_path,
453                                                       portal_type = "StudentStudyLevel")
454                    if not level_brains:
455                        break
456                    modified = True
457                    level_ids = [l.getId for l in level_brains]
458                    level_ids.sort()
459                    for l in level_brains:
460                        if l.getId == level_ids[-1]:
461                            level_path = l.getPath()
462                            break
463                    result_brains = self.portal_catalog(path = level_path,
464                                                        portal_type = "StudentCourseResult")
465                    course_ids = [cr.getId for cr in result_brains]
[1749]466                    courses = []
[1702]467                    for c in course_ids:
468                        if c.endswith('_co'):
469                            courses.append(c[:-3])
470                        else:
471                            courses.append(c)
472                    data['registered_courses'] = courses
473                    break
474            if modified:
475                self.modifyRecord(**data)
476        if pghandler: pghandler.finish()
477    ###)
[1620]478
479    def refreshCatalog(self, clear=0, pghandler=None): ###(
480        """ re-index everything we can find """
481        students_folder = self.portal_url.getPortalObject().campus.students
482        if clear:
[1724]483            self._catalog.clear()
[1700]484        students = self.portal_catalog(portal_type="Student")
485        num_objects = len(students)
[1620]486        if pghandler:
487            pghandler.init('Refreshing catalog: %s' % self.absolute_url(1), num_objects)
488        for i in xrange(num_objects):
489            if pghandler: pghandler.report(i)
[1700]490            student_brain = students[i]
491            spath = student_brain.getPath()
[1727]492            student_object = student_brain.getObject()
[1620]493            data = {}
[1700]494            sid = data['id'] = student_brain.getId
495            data['review_state'] = student_brain.review_state
[1707]496            sub_objects = False
497            for pt in self.affected_types.keys():
498                modified = True
499                try:
500                    doc = getattr(student_object,self.affected_types[pt]['id']).getContent()
501                    sub_objects = True
502                except:
[1727]503                    #from pdb import set_trace;set_trace()
[1707]504                    continue
505                for field in self.affected_types[pt]['fields']:
506                    if hasattr(self,'get_from_doc_%s' % field):
507                        data[field] = getattr(self,'get_from_doc_%s' % field)(doc)
508                    else:
[1727]509                        data[field] = getattr(doc,field,None)
510            if not sub_objects:
[1700]511                import_res = self.returning_import(id = sid)
512                if not import_res:
[1620]513                    continue
[1700]514                import_record = import_res[0]
515                data['matric_no'] = import_record.matric_no
516                data['sex'] = import_record.Sex == 'F'
517                data['name'] = "%s %s %s" % (import_record.Firstname,
518                                             import_record.Middlename,
519                                             import_record.Lastname)
[1815]520                data['jamb_reg_no'] = import_record.Entryregno
[1727]521            else:
522                study_course = getattr(student_object,'study_course',None)
523                current_level = data.get('level',None)
524                data['registered_courses'] = []
525                if study_course and current_level and current_level in study_course.objectIds():
526                    level_obj = getattr(study_course,current_level)
[1749]527                    courses = []
[1727]528                    for c in level_obj.objectIds():
529                        if c.endswith('_co'):
530                            courses.append(c[:-3])
531                        else:
532                            courses.append(c)
[1749]533                    data['registered_courses'] = courses
[1700]534            self.addRecord(**data)
[1620]535        if pghandler: pghandler.finish()
536    ###)
537
[1700]538    security.declarePrivate('notify_event_listener') ###(
[1620]539    def notify_event_listener(self,event_type,object,infos):
540        "listen for events"
[1716]541        if not infos.has_key('rpath'):
542            return
[1702]543        pt = getattr(object,'portal_type',None)
544        mt = getattr(object,'meta_type',None)
[1620]545        students_catalog = self.students_catalog
[1702]546        data = {}
547        if pt == 'Student' and\
548           mt == 'CPS Proxy Folder' and\
549           event_type.startswith('workflow'):
550            data['id'] = object.getId()
551            data['review_state'] = self.portal_workflow.getInfoFor(object,'review_state',None)
552            students_catalog.modifyRecord(**data)
553            return
[1700]554        rpl = infos['rpath'].split('/')
[1731]555        if pt == 'Student' and mt == 'CPS Proxy Folder'\
556           and event_type == "sys_add_object":
[1700]557            student_id = object.id
558            try:
559                self.addRecord(id = student_id)
560            except ValueError:
561                pass
562            return
[1716]563        elif pt == 'StudentCourseResult' and mt == 'CPS Proxy Folder':
564            if event_type not in ("sys_add_object","sys_del_object"):
565                return
566            course_id = object.getId()
567            student_id = object.absolute_url_path().split('/')[-4]
568            res = self(id = student_id)
569            if not res:
570                return
571            student_rec = res[0]
572            registered_courses = student_rec.registered_courses
[1725]573            if not registered_courses:
574                level_obj = object.aq_parent
[1749]575                courses = []
[1725]576                for c in level_obj.objectIds():
577                    if c.endswith('_co'):
578                        courses.append(c[:-3])
579                    else:
580                        courses.append(c)
581                #from pdb import set_trace;set_trace()
[1749]582                registered_courses = courses
[1725]583            else:
584                if event_type == "sys_add_object":
585                    registered_courses.append(course_id)
586                if event_type == "sys_del_object":
587                    if course_id in registered_courses:
588                        registered_courses.remove(course_id)
[1716]589            data['id'] = student_id
590            data['registered_courses'] = registered_courses
591            self.modifyRecord(**data)
592        if pt not in self.affected_types.keys():
[1700]593            return
[1716]594        if event_type not in ('sys_modify_object'):
595            return
[1700]596        if mt == 'CPS Proxy Folder':
597            return
[1716]598        for field in self.affected_types[pt]['fields']:
[1700]599            if hasattr(self,'get_from_doc_%s' % field):
600                data[field] = getattr(self,'get_from_doc_%s' % field)(object)
601            else:
602                data[field] = getattr(object,field)
603        data['id'] = rpl[2]
[1716]604        self.modifyRecord(**data)
[1700]605    ###)
[1620]606
[1625]607
[971]608InitializeClass(StudentsCatalog)
609
[1146]610###)
611
612class CoursesCatalog(WAeUPTable): ###(
[1716]613    security = ClassSecurityInfo()
[1146]614
615    meta_type = 'WAeUP Courses Catalog'
616    name = "students_catalog"
617    key = "code"
618    def __init__(self):
619        WAeUPTable.__init__(self, 'courses_catalog')
620
[1716]621    def manage_catalogReindex(self, REQUEST, RESPONSE, URL1): ###(
622        """ clear the catalog, then re-index everything """
[1146]623
[1716]624        elapse = time.time()
625        c_elapse = time.clock()
626
627        pgthreshold = self._getProgressThreshold()
628        handler = (pgthreshold > 0) and ZLogHandler(pgthreshold) or None
629        self.refreshCatalog(clear=1, pghandler=handler)
630
631        elapse = time.time() - elapse
632        c_elapse = time.clock() - c_elapse
633
634        RESPONSE.redirect(
635            URL1 +
636            '/manage_catalogAdvanced?manage_tabs_message=' +
637            urllib.quote('Catalog Updated \n'
638                         'Total time: %s\n'
639                         'Total CPU time: %s' % (`elapse`, `c_elapse`)))
640    ###)
641
642    def reindexIndex(self, name, REQUEST,pghandler=None): ###(
643        if isinstance(name, str):
644            name = (name,)
645        courses = self.portal_catalog(portal_type="Course")
646        num_objects = len(courses)
647        if pghandler:
648            pghandler.init('Refreshing catalog: %s' % self.absolute_url(1), num_objects)
649        for i in xrange(num_objects):
650            if pghandler: pghandler.report(i)
651            course_brain = courses[i]
652            course_object = course_brain.getObject()
653            pl = course_brain.getPath().split('/')
654            data = {}
655            cid = data[self.key] = course_brain.getId
656            data['faculty'] = pl[-4]
657            data['department'] = pl[-3]
658            doc = course_object.getContent()
659            for field in name:
660                if field not in (self.key,'faculty','department'):
661                    data[field] = getattr(doc,field)
662            self.modifyRecord(**data)
663        if pghandler: pghandler.finish()
664    ###)
665
666    def refreshCatalog(self, clear=0, pghandler=None): ###(
667        """ re-index everything we can find """
[1724]668        if clear:
669            self._catalog.clear()
[1716]670        courses = self.portal_catalog(portal_type="Course")
671        num_objects = len(courses)
672        if pghandler:
673            pghandler.init('Refreshing catalog: %s' % self.absolute_url(1), num_objects)
[1724]674        #from pdb import set_trace;set_trace()
[1716]675        for i in xrange(num_objects):
676            if pghandler: pghandler.report(i)
677            course_brain = courses[i]
[1724]678            course_doc = course_brain.getObject().getContent()
[1716]679            pl = course_brain.getPath().split('/')
680            data = {}
[1724]681            for field in self.schema():
[1749]682                data[field] = getattr(course_doc,field,None)
[1716]683            data[self.key] = course_brain.getId
[1724]684            ai = pl.index('academics')
685            data['faculty'] = pl[ai +1]
686            data['department'] = pl[ai +2]
687            if clear:
688                self.addRecord(**data)
689            else:
690                self.modifyRecord(**data)
[1716]691        if pghandler: pghandler.finish()
692    ###)
693
694    security.declarePrivate('notify_event_listener') ###(
695    def notify_event_listener(self,event_type,object,infos):
696        "listen for events"
697        if not infos.has_key('rpath'):
698            return
699        pt = getattr(object,'portal_type',None)
700        mt = getattr(object,'meta_type',None)
701        if pt != 'Course':
702            return
703        data = {}
704        rpl = infos['rpath'].split('/')
705        if event_type not in ("sys_add_object","sys_modify_object","sys_del_object"):
706            return
707        course_id = object.getId()
708        data[self.key] = course_id
[1724]709        if event_type == "sys_add_object" and mt == 'CPS Proxy Folder':
[1716]710            try:
711                self.addRecord(**data)
712            except ValueError:
[1724]713                return
714            course_id = object.getId()
715            doc = object.getContent()
716            if doc is None:
717                return
718            for field in self.schema():
[1749]719                data[field] = getattr(doc,field,None)
[1724]720            data[self.key] = course_id
721            ai = rpl.index('academics')
722            data['faculty'] = rpl[ai +1]
723            data['department'] = rpl[ai +2]
724            self.modifyRecord(**data)
725            return
[1716]726        if event_type == "sys_del_object":
727            self.deleteRecord(course_id)
[1724]728            return
[1716]729        if event_type == "sys_modify_object" and mt == 'Course':
[1724]730            #from pdb import set_trace;set_trace()
[1716]731            for field in self.schema():
[1749]732                data[field] = getattr(object,field,None)
[1716]733            course_id = object.aq_parent.getId()
734            data[self.key] = course_id
[1724]735            ai = rpl.index('academics')
736            data['faculty'] = rpl[ai +1]
737            data['department'] = rpl[ai +2]
[1716]738            self.modifyRecord(**data)
739    ###)
740
741
[1146]742InitializeClass(CoursesCatalog)
[1151]743###)
[1146]744
[1625]745class OnlinePaymentsImport(WAeUPTable): ###(
[1620]746
747    meta_type = 'WAeUP Online Payment Transactions'
[1625]748    name = "online_payments_import"
[1620]749    key = "order_id"
750    def __init__(self):
751        WAeUPTable.__init__(self, self.name)
752
753
754InitializeClass(CoursesCatalog)
755###)
756
[1151]757class ReturningImport(WAeUPTable): ###(
[1146]758
[1151]759    meta_type = 'Returning Import Table'
760    name = "returning_import"
[1146]761    key = "matric_no"
762    def __init__(self):
[1151]763        WAeUPTable.__init__(self, 'returning_import')
[1146]764
765
[1151]766InitializeClass(ReturningImport)
767###)
[1146]768
769class ResultsImport(WAeUPTable): ###(
770
771    meta_type = 'Results Import Table'
772    name = "results_import"
773    key = "key"
774    def __init__(self):
775        WAeUPTable.__init__(self, 'results_import')
776
777
778InitializeClass(ResultsImport)
779
780###)
781
782class PaymentsCatalog(WAeUPTable): ###(
783
784    meta_type = 'WAeUP Payments Catalog'
785    name = "students_catalog"
786    key = "id"
787    def __init__(self):
788        WAeUPTable.__init__(self, 'payments_catalog')
789
790
791InitializeClass(PaymentsCatalog)
792
793###)
794
[414]795# BBB:
796AccomodationTable = AccommodationTable
Note: See TracBrowser for help on using the repository browser.