#-*- mode: python; mode: fold -*- from Globals import InitializeClass from AccessControl import ClassSecurityInfo from Products.CMFCore.utils import UniqueObject, getToolByName from Products.CMFCore.permissions import View from Products.CMFCore.permissions import ModifyPortalContent from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder #from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument from Products.CPSDocument.CPSDocument import CPSDocument from Products.CPSCore.CPSBase import CPSBaseBTreeFolder as BaseBTreeFolder from Products.WAeUP_SRP.WAeUPTables import AccommodationTable,NOT_OCCUPIED import logging import csv,re,os import Globals import DateTime import re p_home = Globals.package_home(globals()) i_home = Globals.INSTANCE_HOME class AccoFolder(CPSDocument): ###( """ WAeUP AccoFolder containing Accommodation halls """ meta_type = 'AccoFolder' portal_type = meta_type security = ClassSecurityInfo() security.declareProtected(View,"Title") def Title(self): """compose title""" return "Accommodation Section" security.declareProtected(ModifyPortalContent,"generateFreeBedsList") ###( def generateFreeBedsList(self): """ generate the free Bedslist. """ logger = logging.getLogger('Accommodation.AccoFolder.generateFreeBedsList') member = self.portal_membership.getAuthenticatedMember() logger.info('%s generated bed list' % member) bed_list = self.portal_accommodation l = self.portal_catalog({'meta_type': "AccoHall"}) halls = [] generated = [] generated.append('"Bed","BedType"' % vars()) modified = [] modified.append('"Bed","BedType","Student"' % vars()) beds_generated = [] for h in l: halls.append(h.getObject()) for hall in halls: #import pdb;pdb.set_trace() hall_doc = hall.getContent() hall_gen = {} hall_gen['name'] = hall.Title count = 0 modified_count = 0 reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',hall_doc.reserved_rooms) if r] #import pdb;pdb.set_trace() #for block in range(1,int(hall_doc.nr_of_blocks)+1): # for block in 'ABCDEFGHIJ'[:int(hall_doc.nr_of_blocks)]: blocks_for_female = getattr(hall_doc,'blocks_for_female',[]) blocks_for_male = getattr(hall_doc,'blocks_for_male',[]) beds_for_fresh = getattr(hall_doc,'beds_for_fresh',[]) beds_for_pre = getattr(hall_doc,'beds_for_pre',[]) beds_for_returning = getattr(hall_doc,'beds_for_returning',[]) beds_for_final = getattr(hall_doc,'beds_for_final',[]) if set(blocks_for_female).intersection(set(blocks_for_male)): return self.accommodation.acco_folder_view(beds_generated=beds_generated) for block in blocks_for_female + blocks_for_male: sex = 'male' if block in blocks_for_female: sex = 'female' for floor in range(1,int(hall_doc.nr_of_floors)+1): for room in range(1,int(hall_doc.rooms_per_floor)+1): for bed in 'ABCDEFGHIKLMNOPQRSTUVWXYZ'[:int(hall_doc.beds_per_room)]: room_nr = floor*100 + room bt = 'all' if (block,room_nr) in reserved: bt = "reserved" elif hall_doc.special_handling and not hall_doc.special_handling.startswith("no"): bt = hall_doc.special_handling elif bed in beds_for_fresh: bt = 'fr' elif bed in beds_for_pre: bt = 'pr' elif bed in beds_for_final: bt = 'fi' elif bed in beds_for_returning: bt = 're' if hall_doc.special_handling.startswith("no_"): bt += "_" + hall_doc.special_handling[3:] bt = "%(sex)s_%(bt)s" % vars() uid = '%s_%s_%d_%s' % (hall.getId(),block,room_nr,bed) d = {} d['bed'] = uid d['bed_type'] = bt d['sort_id'] = getattr(hall_doc,'sort_id',0) d['hall'] = hall.getId() bed_record = bed_list.getRecordByKey(uid) if bed_record is None: d['student'] = NOT_OCCUPIED bed_list.addRecord(**d) count +=1 generated.append('"%(uid)s","%(bt)s"' % vars()) elif bed_record.bed_type != bt: st = bed_record.student bed_list.modifyRecord(**d) modified.append('"%(uid)s","%(bt)s","%(st)s"' % vars()) modified_count += 1 pass # fix for ticket futminna 133, can be removed after implementation # of new allocation module #if bed_record and bed_record.student=='': # d['student'] = NOT_OCCUPIED # bed_list.modifyRecord(**d) # modified.append('"%(uid)s","%(bt)s","not_occupied"' % vars()) # modified_count += 1 hall_gen['count']= count hall_gen['modified_count']= modified_count beds_generated.append(hall_gen) current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S") open("%s/export/bedlist_%s.csv" % (i_home,current),"w+").write('\n'.join(generated)) open("%s/export/bedlist_modified_%s.csv" % (i_home,current),"w+").write('\n'.join(modified)) return self.accommodation.acco_folder_view(beds_generated=beds_generated) ###) security.declareProtected(ModifyPortalContent,"importReservedBeds")###( def importReservedBeds(self): """load Reserved Beds from CSV""" import transaction import random current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S") students_folder = self.portal_url.getPortalObject().campus.students acco_folder = self.portal_url.getPortalObject().campus.accommodation tr_count = 1 total = 0 name = 'ReservedBeds' accommodation = self.portal_accommodation students_cat = self.students_catalog no_import = [] imported = [] logger = logging.getLogger('Accommodation.AccoFolder.importReservedBeds') try: beds = csv.DictReader(open("%s/import/%s.csv" % (i_home,name),"rb")) except: logger.error('Error reading %s.csv' % name) return halls = {} start = True for bed in beds: if start: start = False logger.info('start loading from %s.csv' % name) s = ','.join(['"%s"' % fn for fn in bed.keys()]) imported.append(s) no_import.append('%s,"Error"' % s) format = ','.join(['"%%(%s)s"' % fn for fn in bed.keys()]) format_error = format + ',"%(Error)s"' no_certificate = "no certificate %s" % format student_id = bed.get('id') matric_no = bed.get('matric_no') jamb_reg_no = bed.get('jamb_reg_no') if student_id != '': res = students_cat(id = student_id) if not res: bed['Error'] = "No such student" no_import.append( format_error % bed) continue student = res[0] elif matric_no != '': res = students_cat(matric_no = matric_no) if not res: bed['Error'] = "No such student" no_import.append( format_error % bed) continue student = res[0] elif jamb_reg_no != '': res = students_cat(jamb_reg_no = jamb_reg_no) if not res: bed['Error'] = "No such student" no_import.append( format_error % bed) continue student = res[0] else: bed['Error'] = "No student identification number provided" no_import.append( format_error % bed) continue sid = student.id names = bed.get('name').split() n = 0 for na in names: if na.endswith(','): names[n] = na[:-1] names[n] = names[n].upper() n += 1 s_names = student.name.split() found = False for sn in s_names: if sn.upper() in names: found = True break if not found: bed['Error'] = "Name mismatch %s %s" % (str(names),str(s_names)) no_import.append( format_error % bed) continue hall = bed.get('hall') if hall not in halls.keys(): hall_object = getattr(acco_folder,hall, None) if hall_object is None: bed['Error'] = "No such hall" no_import.append( format_error % bed) continue halls[hall] = hall_doc = hall_object.getContent() bid = "%(hall)s_%(block)s_%(room)s_%(bed)s" % bed res = accommodation(bed = bid) psm = '' while True: if not res: psm = "No bed with this id" break bed_brain = res[0] if not bed_brain.bed_type.endswith("reserved"): psm = "Not a reserved bed" break if bed_brain.student and bed_brain.student != NOT_OCCUPIED: psm = "Bed %s already reserved for %s" % (bid,bed_brain.student) break if student.sex and not bed.get('block') in hall_doc.blocks_for_female: psm = "Sex does not match %s" % bid break break if psm != '': bed['Error'] = psm no_import.append( format_error % bed) continue already = accommodation(student=sid) if already: accommodation.modifyRecord(bed=already[0].bed,student=NOT_OCCUPIED) student_obj = getattr(students_folder, student.id) acco_id = "accommodation_%s" % self.getSessionId()[0] if acco_id in student_obj.objectIds(): acco_doc = getattr(student_obj, acco_id).getContent() info = self.getAccommodationInfo(sid) status = info['student_status'] acco_doc.edit(mapping={'bed': bid,'student_status' : status}) member = self.portal_membership.getAuthenticatedMember() logger.info('%s changed reserved bed %s for %s' % (member,bid,sid)) accommodation.modifyRecord(bed = bid, student = sid) imported.append( format % bed) 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 #from pdb import set_trace;set_trace() 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)) logger.info('finished loading from %s.csv' % name) return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1')) InitializeClass(AccoFolder) def addAccoFolder(container, id, REQUEST=None, **kw): """Add a AccoFolder.""" ob = AccoFolder(id, **kw) return CPSBase_adder(container, ob, REQUEST=REQUEST) ###) ###) class AccoHall(CPSDocument): ###( """ WAeUP AccoHall """ meta_type = 'AccoHall' portal_type = meta_type security = ClassSecurityInfo() security.declareProtected(View,"Title") ###( def Title(self): """compose title""" content = self.getContent() heading = getattr(content,'heading',None) if heading is None: return self.title return heading ###) InitializeClass(AccoHall) def addAccoHall(container, id, REQUEST=None, **kw): """Add a AccoHall.""" ob = AccoHall(id, **kw) return CPSBase_adder(container, ob, REQUEST=REQUEST) ###)