Index: /WAeUP_SRP/trunk/Students.py
===================================================================
--- /WAeUP_SRP/trunk/Students.py	(revision 1288)
+++ /WAeUP_SRP/trunk/Students.py	(revision 1289)
@@ -869,5 +869,5 @@
                 table.addRecord(**student)
             except ValueError:
-                import pdb;pdb.set_trace()
+                #import pdb;pdb.set_trace()
                 student['Error'] = "Duplicate"
                 no_import.append( format_error % student)
@@ -896,4 +896,104 @@
         return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
     ###)
+
+
+
+
+    security.declareProtected(ModifyPortalContent,"updateReturningStudents")###(
+    def updateReturningStudents(self):
+        """load and overwrite Returning Student Data from CSV values"""
+        import transaction
+        import random
+        #from pdb import set_trace
+        wftool = self.portal_workflow
+        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
+        students_folder = self.portal_catalog({'meta_type': 'StudentsFolder'})[-1].getObject()
+        tr_count = 1
+        total = 0
+        #name = 'pume_results'
+        name = 'Returning_update'
+        table = self.returning_import
+        no_import = []
+        imported = []
+        logger = logging.getLogger('Import.%s' % name)
+        try:
+            returning = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb"))
+        except:
+            logger.error('Error reading %s.csv' % name)
+            return
+        l = self.portal_catalog({'meta_type': "Certificate"})
+        certs = {}
+        cert_docs = {}
+        for f in l:
+            certs[f.getId] = f.getObject().getContent()
+        start = True
+        res = table()
+        regs = []
+        if len(res) > 0:
+            regs = [s.matric_no for s in res]
+        for student in returning:
+            if start:
+                start = False
+                logger.info('start loading from %s.csv' % name)
+                s = ','.join(['"(%s)"' % fn for fn in student.keys()])
+                imported.append(s)
+                no_import.append('%s,"Error"' % s)
+                format = ','.join(['"%%(%s)s"' % fn for fn in student.keys()])
+                format_error = format + ',"%(Error)s"'
+                no_certificate = "no certificate %s" % format
+            matric_no = student.get('matric_no').upper()
+            student['matric_no'] = matric_no
+            if matric_no == '':
+                student['Error'] = "Empty matric_no"
+                no_import.append( format_error % student)
+                continue
+#            if matric_no in regs or self.returning_import(matric_no = matric_no):
+#                student['Error'] = "Duplicate"
+#                no_import.append( format_error % student)
+#                continue
+#            cert_id = makeCertificateCode(student.get('Coursemajorcode'))
+#            if cert_id not in certs.keys():
+#                student['Error'] = "No Certificate %s" % cert_id
+#                no_import.append( format_error % student)
+#                continue
+            try:
+                table.modifyRecord(**student)
+            except KeyError:
+                #import pdb;pdb.set_trace()
+                student['Error'] = "no Student found to update"
+                no_import.append( format_error % student)
+                continue
+            s = self.students_catalog(matric_no=matric_no)
+            if s:
+                level = "%s" % (int(student.get('Level')) + 100)
+                self.students_catalog.modifyRecord(id = s[0].id,
+                                                       level=level)
+
+            regs.append(student.get('matric_no'))
+            imported.append(format % student)
+            tr_count += 1
+            if tr_count > 1000:
+                if len(no_import) > 0:
+                    open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
+                             '\n'.join(no_import) + '\n')
+                    no_import = []
+                open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
+                                            '\n'.join(no_import) + "\n")
+                imported = []
+                em = '%d transactions commited total %s\n' % (tr_count,total)
+                transaction.commit()
+                regs = []
+                logger.info(em)
+                total += tr_count
+                tr_count = 0
+        open("%s/import/%simported%s.csv" % (i_home,name,current),"a").write(
+                                            '\n'.join(imported))
+        open("%s/import/%s_not_imported%s.csv" % (i_home,name,current),"a").write(
+                                                '\n'.join(no_import))
+        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
+    ###)
+
+
+
 
     security.declareProtected(ModifyPortalContent,"importResults")###(
Index: /WAeUP_SRP/trunk/skins/waeup_accommodation/getBedStatusFromHall.py
===================================================================
--- /WAeUP_SRP/trunk/skins/waeup_accommodation/getBedStatusFromHall.py	(revision 1289)
+++ /WAeUP_SRP/trunk/skins/waeup_accommodation/getBedStatusFromHall.py	(revision 1289)
@@ -0,0 +1,50 @@
+## Script (Python) "getBedStatusFromHall"
+##bind container=container
+##bind context=context
+##bind namespace=
+##bind script=script
+##bind subpath=traverse_subpath
+##parameters=code=None
+##title=
+##
+# $Id: change_bed.py 1206 2007-01-05 18:24:56Z joachim $
+"""
+"""
+import logging
+logger = logging.getLogger('Student.Accommodation.change_bed')
+import re
+request = context.REQUEST
+redirect = request.RESPONSE.redirect
+mtool = context.portal_membership
+wf = context.portal_workflow
+member = mtool.getAuthenticatedMember()
+member_id = str(member)
+path_info = request.get('PATH_INFO').split('/')
+
+hall,block,room,bed = code.split('_')
+hres = context.portal_catalog(id = hall)
+if not hres:
+    return None
+h = hres[0].getObject().getContent()
+sex = 'male'
+if block in h.blocks_for_female:
+    sex = 'female'
+room_nr = int(room)
+bt = 're'
+reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',h.reserved_rooms)
+                                     if r]
+if (block,room_nr) in reserved:
+    bt = "reserved"
+elif not h.special_handling.startswith("no"):
+    bt = h.special_handling
+elif bed in h.beds_for_fresh:
+    bt = 'fr'
+#elif bed in h.beds_for_returning:
+#    bt = 're'
+elif bed in h.beds_for_final:
+    bt = 'fi'
+if h.special_handling.startswith("no_"):
+    bt += "_" + h.special_handling[3:]
+bt = "%s_%s" % (sex,bt)
+uid = '%s_%s_%d_%s' % (hall,block,room_nr,bed)
+return bt
Index: /WAeUP_SRP/trunk/skins/waeup_accommodation/reallocateBed.py
===================================================================
--- /WAeUP_SRP/trunk/skins/waeup_accommodation/reallocateBed.py	(revision 1289)
+++ /WAeUP_SRP/trunk/skins/waeup_accommodation/reallocateBed.py	(revision 1289)
@@ -0,0 +1,107 @@
+## Script (Python) "change_bed"
+##bind container=container
+##bind context=context
+##bind namespace=
+##bind script=script
+##bind subpath=traverse_subpath
+##parameters=
+##title=
+##
+# $Id: reallocateBed.py 1206 2007-01-05 18:24:56Z joachim $
+"""
+reallocate beds
+"""
+import logging
+logger = logging.getLogger('Student.Accommodation.reallocate_bed')
+
+request = context.REQUEST
+redirect = request.RESPONSE.redirect
+mtool = context.portal_membership
+wf = context.portal_workflow
+member = mtool.getAuthenticatedMember()
+member_id = str(member)
+path_info = request.get('PATH_INFO').split('/')
+
+if mtool.isAnonymousUser():
+    return None
+students = context.portal_url.getPortalObject().campus.students
+beds = context.portal_accommodation
+studs = context.students_catalog
+student_id = context.getStudentId()
+
+if student_id is not None:
+    logger.info('"%s", "requests bed_change for", "%s"' % (member_id,student_id))
+    info = context.getAccommodationInfo(student_id)
+    res = beds(student=student_id)
+    if len(res) == 0:
+        logger.info('"%s", "no bed found"' % (student_id))
+        redirect("%s/%s" % (students.absolute_url(),student_id))
+    allocated_bed = res[0]
+    status = info['student_status']
+    student = student_id
+    bedtype = context.getBedStatusFromHall(allocated_bed.bed)
+    if not bedtype.endswith("reserved"):
+        logger.info('"%s", "allocated bed is NOT reserved","%s"' % (student_id,bedtype))
+        redirect("%s/%s/%s" % (students.absolute_url(),student,info['acco_id']))
+    logger.info('"%s", "reallocate reserved bed", "%s/%s"' % (student_id,bedtype,status))
+    beds.modifyRecord(bed=allocated_bed.bed,
+                      student='',
+                      bed_type=bedtype)
+    code,bed = beds.searchAndReserveBed(student_id,status)
+    if code > 0:
+        #from Products.zdb import set_trace; set_trace()
+        d = {}
+        d['bed'] = bed
+        d['student_status'] = status
+        acco_info = context.waeup_tool.getAccommodationInfo(bed)
+        d['acco_maint_code'] = acco_info.get('maintenance_code')
+        d['acco_maint_fee'] = acco_info.get('maintenance_fee')
+        acco_doc = info['acco_doc']
+        acco_doc.edit(mapping=d)
+        return redirect("%s/%s/%s" % (students.absolute_url(),student,info['acco_id']))
+    logger.info('"%s", "new bed allocation failed","%s"' % (student_id,code))
+    redirect("%s/%s/%s" % (students.absolute_url(),student,info['acco_id']))
+
+info = {}
+#records = [r for r in beds() if  r.student]
+records = beds.uniqueValuesFor('bed')
+list = []
+to_modify = []
+for b in records:
+    r = beds(bed=b)[0]
+    bedtype = context.getBedStatusFromHall(r.bed)
+    if not bedtype.endswith("reserved"):
+        #logger.info('"%s", "allocated bed is NOT reserved","%s"' % (student_id,bedtype))
+        #list.append("Student %s bed_type %s ok" % (r.student,bedtype))
+        continue
+    if not r.student:
+        beds.modifyRecord(bed=b,
+                      bed_type=bedtype)
+        list.append("empty bed %s set to %s" % (r.bed,bedtype))
+        continue
+    info = context.getAccommodationInfo(r.student)
+    sbt = info.get('student_status',None)
+    if sbt is None:
+        continue
+    list.append("Student %s bed_type %s != %s" % (r.student,
+                                                  r.bed_type,
+                                                  bedtype))
+    to_modify.append((r.bed,r.student,info['student_status'],info['acco_doc'],bedtype))
+for former_bed, student, status,acco_doc,bedtype in to_modify:
+    beds.modifyRecord(bed=former_bed,
+                      student='',
+                      bed_type=bedtype)
+    code,bed = beds.searchAndReserveBed(student,status)
+    if code > 0:
+        #from Products.zdb import set_trace; set_trace()
+        d = {}
+        d['bed'] = bed
+        d['student_status'] = status
+        acco_info = context.waeup_tool.getAccommodationInfo(bed)
+        d['acco_maint_code'] = acco_info.get('maintenance_code')
+        d['acco_maint_fee'] = acco_info.get('maintenance_fee')
+        acco_doc.edit(mapping=d)
+        list.append("Student %s new bed %s assigned code = %s" % (student,
+                                                              bed,
+                                                              code))
+return "\r".join(list)
