Index: WAeUP_SRP/trunk/WAeUPTables.py
===================================================================
--- WAeUP_SRP/trunk/WAeUPTables.py	(revision 2083)
+++ WAeUP_SRP/trunk/WAeUPTables.py	(revision 2084)
@@ -35,4 +35,7 @@
 from Products.AdvancedQuery import Eq, Between, Le,In
 
+ADDING_SHEDULED = "adding_sheduled"
+OBJECT_CREATED = "object_created"
+
 from interfaces import IWAeUPTable
 
@@ -66,5 +69,4 @@
         #      URL1 +
         #      '/manage_catalogAdvanced?manage_tabs_message=Catalog%20Clearing%20disabled')
-
 
         self._catalog.clear()
@@ -313,5 +315,5 @@
     ###)
 
-    def fill_certificates_dict(self):
+    def fill_certificates_dict(self): ###(
         "return certificate data in  dict"
         certificates_brains = self.portal_catalog(portal_type ='Certificate')
@@ -326,5 +328,6 @@
             d[cb.getId] = ld
         return d
-            
+    ###)
+
     def get_from_doc_department(self,doc,cached_data={}): ###(
         "return the students department"
@@ -442,8 +445,15 @@
             pghandler.init('Refreshing catalog: %s' % self.absolute_url(1), num_objects)
         noattr = set(('StudentClearance','StudentPersonal')) & set(reindextypes.keys())
+        #import pdb;pdb.set_trace()
         for i in xrange(num_objects):
             if pghandler: pghandler.report(i)
             student_brain = students[i]
             student_object = student_brain.getObject()
+            # query = Eq('path',student_brain.getPath())
+            # sub_brains_list = aq_portal(query)
+            # sub_brains = {}
+            # for sub_brain in sub_brains_list:
+            #     sub_brains[sub_brain.portal_type] = sub_brain
+            # student_path = student_brain.getPath()
             data = {}
             modified = False
@@ -457,8 +467,11 @@
                 try:
                     doc = getattr(student_object,self.affected_types[pt]['id']).getContent()
+                    #doc = sub_brains[pt].getObject().getContent()
+                    # path = "%s/%s" % (student_path,self.affected_types[pt]['id'])
+                    # doc = self.unrestrictedTraverse(path).getContent()
                     sub_objects = True
                 except:
                     continue
-                for field in self.affected_types[pt]['fields']:
+                for field in set(name).intersection(self.affected_types[pt]['fields']):
                     if hasattr(self,'get_from_doc_%s' % field):
                         data[field] = getattr(self,'get_from_doc_%s' % field)(doc,
@@ -640,52 +653,4 @@
 ###)
 
-class StatisticsCatalog(StudentsCatalog): ###(
-    security = ClassSecurityInfo()
-    meta_type = 'WAeUP Statistics Catalog'
-    name = "statistics"
-    affected_types = {   ###(
-                      'StudentApplication':
-                          {'id': 'application',
-                           'fields':
-                             ('jamb_reg_no',
-                              'entry_mode',
-                              #'entry_level',
-                              'entry_session',
-                              )
-                              },
-                      'StudentClearance':
-                          {'id': 'clearance',
-                           'fields':
-                             ('matric_no',
-                              )
-                              },
-                         'StudentPersonal':
-                          {'id': 'personal',
-                           'fields':
-                             ('name',
-                              'sex',
-                              'email',
-                              'phone',
-                              )
-                              },
-                         'StudentStudyCourse':
-                          {'id': 'study_course',
-                           'fields':
-                             ('course',
-                              'faculty',
-                              'department',
-                              'level',
-                              'mode',
-                              'session',
-                              'verdict',
-                              )
-                              },
-                         }
-    ###)
-
-
-InitializeClass(StudentsCatalog)
-###)
-
 class CoursesCatalog(WAeUPTable): ###(
     security = ClassSecurityInfo()
@@ -821,12 +786,117 @@
 ###)
 
-class ResultsCatalog(WAeUPTable): ###(
+class CourseResults(WAeUPTable): ###(
     security = ClassSecurityInfo()
 
     meta_type = 'WAeUP Results Catalog'
     name = "course_results"
-    key = "key"
+    key = "key" #student_id + level + course_id
     def __init__(self):
         WAeUPTable.__init__(self, 'course_results')
+        self._queue = []
+        
+    def addRecord(self, **data): ###(
+        # The uid is the same as "bed".
+        uid = key = "%(student_id)s|%(level_id)s|%(course_id)s" % data
+        if key in self._queue:
+            return uid
+        data['queue_status'] = ADDING_SHEDULED
+        data['%s' % self.key] = uid
+        res = self.searchResults({"%s" % self.key : uid})
+        if len(res) > 0:
+            raise ValueError("More than one record with uid %s" % uid)
+        self.catalog_object(dict2ob(data), uid=uid)
+        if not hasattr(self,'_queue'):
+            self._queue = []
+        self._queue.append(key)
+        self._p_changed = 1
+        return uid
+    ###)
+
+    def deleteRecord(self, uid): ###(
+        self.uncatalog_object(uid)
+        if uid in self._queue:
+            self._queue.remove(uid)
+    ###)
+
+    def getCourses(self,student_id,level_id): ###(
+        query = Eq('student_id',student_id) & Eq('level_id', level_id)
+        carry_overs = []
+        normal = []
+        credits = 0 
+        for brain in self.course_results.evalAdvancedQuery(query):
+            d = {}
+            credits += int(brain.credits) 
+            for field in self.schema():
+                d[field] = getattr(brain,field,'')
+            d['sheduled'] = brain.queue_status == ADDING_SHEDULED
+            d['coe'] = 'Elective'
+            if brain.core_or_elective:
+                d['coe'] = 'Core'
+            d['title'] = self.courses_catalog.evalAdvancedQuery(Eq('code',brain.code))[0].title
+            if brain.code.endswith('_co'):
+                carry_overs.append(d)
+            else:
+                normal.append(d)
+        normal.sort(cmp=lambda x,y: cmp(x['semester'], y['semester']))
+        carry_overs.sort(cmp=lambda x,y: cmp(x['semester'], y['semester']))
+        return credits,carry_overs,normal
+    ###)
+
+    def addObject(self,record): ###(
+        key = record.key
+        student_id,level_id,course_id = key.split('|')
+        level = getattr(getattr(self.portal_url.getPortalObject().campus.students,student_id).study_course,level_id)
+        cr_id = level.invokeFactory('StudentCourseResult', course_id)
+        course_result = getattr(level,cr_id)
+        self.portal_workflow.doActionFor(course_result,'open')
+        d = {}
+        for field in self.schema():
+            d[field] = getattr(record,field,'')
+        course_result.getContent().edit(mapping=d)
+    ###)
+        
+    security.declareProtected(ModifyPortalContent,"process_queue") ###(
+    def process_queue(self,limit=None):
+        """adds objects and removes them from the queue.
+        If limit is specified, at most (limit) events are removed.
+        """
+        if not hasattr(self,'_queue'):
+            return 0
+        queue= self._queue
+        if not limit or len(queue) <= limit:
+            keys = self._queue[:]
+        else:
+            keys = queue[:limit]
+        if not keys:
+            records = self.evalAdvancedQuery(Eq('queue_status',ADDING_SHEDULED))
+        else:
+            records = self.evalAdvancedQuery(In("%s" % self.key,keys))
+        for record in records:
+            if record.queue_status == OBJECT_CREATED:
+                continue
+            self.addObject(record)
+            data = {}
+            data['key'] = record.key
+            data['queue_status'] = OBJECT_CREATED
+            self.modifyRecord(**data)
+        count = 0
+        for key in keys:
+            count +=1
+            if key in self._queue:
+                self._queue.remove(key)
+        self._p_changed = 1
+        return count,len(self._queue)
+    ###)
+
+    def manage_catalogClear(self, REQUEST=None, RESPONSE=None, URL1=None): ###(
+        """ clears the whole enchilada """
+        self._catalog.clear()
+
+        if REQUEST and RESPONSE:
+            RESPONSE.redirect(
+              URL1 +
+              '/manage_catalogAdvanced?manage_tabs_message=Catalog%20Cleared')
+    ###)
 
     def manage_catalogReindex(self, REQUEST, RESPONSE, URL1): ###(
@@ -838,5 +908,5 @@
         pgthreshold = self._getProgressThreshold()
         handler = (pgthreshold > 0) and ZLogHandler(pgthreshold) or None
-        #self.refreshCatalog(clear=1, pghandler=handler)
+        self.refreshCatalog(clear=1, pghandler=handler)
 
         elapse = time.time() - elapse
@@ -851,6 +921,63 @@
     ###)
 
-
-InitializeClass(ResultsCatalog)
+    def refreshCatalog(self, clear=1, pghandler=None): ###(
+        """ re-index everything we can find """
+        students_folder = self.portal_url.getPortalObject().campus.students
+        if clear:
+            self._catalog.clear()
+        course_results = self.portal_catalog(portal_type="StudentCourseResult")
+        num_objects = len(course_results)
+        if pghandler:
+            pghandler.init('Refreshing catalog: %s' % self.absolute_url(1), num_objects)
+        #import pdb;pdb.set_trace()
+        for i in xrange(num_objects):
+            if pghandler: 
+                pghandler.report(i)
+            course_result_brain = course_results[i]
+            path_list = course_result_brain.getPath().split('/')
+            course_result_object = course_result_brain.getObject()
+            course_result_doc = course_result_object.getContent()
+            data = {}
+            level_id = path_list[-2]
+            course_id = path_list[-1]
+            student_id = path_list[-4]
+            for field in self.schema():
+                data[field] = getattr(course_result_doc,field,'')
+            data['key'] = key = "%(student_id)s|%(level_id)s|%(course_id)s" % vars()
+            data['student_id'] = student_id 
+            data['level_id'] = level_id 
+            data['queue_status'] = OBJECT_CREATED
+            self.catalog_object(dict2ob(data), uid=key)
+        if pghandler: pghandler.finish()
+    ###)
+
+    security.declarePrivate('notify_event_listener') ###(
+    def notify_event_listener(self,event_type,object,infos):
+        "listen for events"
+        if not infos.has_key('rpath'):
+            return
+        pt = getattr(object,'portal_type',None)
+        mt = getattr(object,'meta_type',None)
+        data = {}
+        rpl = infos['rpath'].split('/')
+        if mt == 'CPS Proxy Folder':
+            return
+        if pt == 'StudentCourseResult' and event_type == "sys_modify_object":
+            data["%s" % self.key] = uid = "%s|%s|%s" % (rpl[-5],rpl[-3],rpl[-2])
+            records = self.searchResults({"%s" % self.key : uid})
+            if len(records) > 1:
+                # Can not happen, but anyway...
+                raise ValueError("More than one record with uid %s" % uid)
+            if len(records) == 0:
+                raise KeyError("No record for uid %s" % uid)
+            record = records[0]
+            #import pdb;pdb.set_trace()
+            for field in ('core_or_elective','score'):
+                value = getattr(object,field,None)
+                data[field] = value
+            self.modifyRecord(record,**data)
+    ###)
+
+InitializeClass(CourseResults)
 ###)
 
Index: WAeUP_SRP/trunk/profiles/default/course_results.xml
===================================================================
--- WAeUP_SRP/trunk/profiles/default/course_results.xml	(revision 2084)
+++ WAeUP_SRP/trunk/profiles/default/course_results.xml	(revision 2084)
@@ -0,0 +1,31 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/xsl" href="catalog.xsl"?>
+<object name="course_results" meta_type="WAeUP Table">
+ <column value="key"/>
+ <column value="code"/>
+ <column value="carry_over"/>
+ <column value="core_or_elective"/>
+ <column value="credits"/>
+ <column value="grade"/>
+ <column value="student_id"/>
+ <column value="level_id"/>
+ <column value="score"/>
+ <column value="grade"/>
+ <column value="semester"/>
+ <column value="queue_status"/>
+ <index name="key" meta_type="FieldIndex">
+  <indexed_attr value="key"/>
+ </index>
+ <index name="code" meta_type="FieldIndex">
+  <indexed_attr value="code"/>
+ </index>
+ <index name="student_id" meta_type="FieldIndex">
+  <indexed_attr value="student_id"/>
+ </index>
+ <index name="level_id" meta_type="FieldIndex">
+  <indexed_attr value="level_id"/>
+ </index>
+ <index name="queue_status" meta_type="FieldIndex">
+  <indexed_attr value="queue_status"/>
+ </index>
+</object>
