source: WAeUP_SRP/trunk/WAeUPTables.py @ 1838

Last change on this file since 1838 was 1815, checked in by Henrik Bettermann, 17 years ago

reindex of matric_no and jamb_reg_no fixed

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