def update( self, udpateReservationIndex=True ): """ Documentation in base class. """ ReservationBase.update( self ) if udpateReservationIndex: self._removeFromDayReservationsIndex() self._addToDayReservationsIndex() self._p_changed = True
def rebuildRoomReservationsIndex(): from MaKaC.common.db import DBMgr from MaKaC.rb_location import CrossLocationDB from MaKaC.rb_room import RoomBase from MaKaC.plugins.RoomBooking.default.dalManager import DALManager from BTrees.OOBTree import OOBTree DBMgr.getInstance().startRequest() CrossLocationDB.connect() root = DALManager.root resvEx = ReservationBase() resvEx.isConfirmed = None allResvs = CrossLocationQueries.getReservations( resvExample = resvEx ) print "There are " + str( len( allResvs ) ) + " resvs and pre-resvs to index..." c = 0 root[_ROOM_RESERVATIONS_INDEX] = OOBTree() print "Room => Reservations Index branch created" for resv in allResvs: roomReservationsIndexBTree = root[_ROOM_RESERVATIONS_INDEX] resvs = roomReservationsIndexBTree.get( resv.room.id ) if resvs == None: resvs = [] # New list of reservations for this room roomReservationsIndexBTree.insert( resv.room.id, resvs ) resvs.append( resv ) roomReservationsIndexBTree[resv.room.id] = resvs c += 1 if c % 100 == 0: print c CrossLocationDB.commit() CrossLocationDB.disconnect() DBMgr.getInstance().endRequest()
def getExcludedDays(self): ReservationBase.getExcludedDays(self) from copy import copy lst = copy(self._excludedDays) lst.sort() return lst
def insert( self ): """ Documentation in base class. """ ReservationBase.insert( self ) resvBTree = Reservation.getReservationsRoot() # Ensure ID if self.id == None: # Maximum ID + 1 if len( resvBTree ) > 0: self.id = resvBTree.maxKey() + 1 else: self.id = 1 # Can not use maxKey for 1st record in a tree # Add self to the BTree resvBTree[self.id] = self # Update room => room reservations index roomReservationsIndexBTree = Reservation.getRoomReservationsIndexRoot() resvs = roomReservationsIndexBTree.get( self.room.id ) if resvs == None: resvs = [] # New list of reservations for this room roomReservationsIndexBTree.insert( self.room.id, resvs ) resvs.append( self ) roomReservationsIndexBTree[self.room.id] = resvs # Update user => user reservations index userReservationsIndexBTree = Reservation.getUserReservationsIndexRoot() resvs = userReservationsIndexBTree.get( self.createdBy ) if resvs == None: resvs = [] # New list of reservations for this room userReservationsIndexBTree.insert( self.createdBy, resvs ) resvs.append( self ) userReservationsIndexBTree[self.createdBy] = resvs # Update day => reservations index self._addToDayReservationsIndex()
def includeDay( self, dayD ): """ Inserts dayD into list of excluded days. dayD should be of date type (not datetime). """ ReservationBase.includeDay( self, dayD ) lst = self._excludedDays lst.remove( dayD ) self._excludedDays = lst # Force update
def _getAnswer(self): p = ReservationBase() p.startDT = self._startDT p.endDT = self._endDT p.repeatability = self._repeatability rooms = CrossLocationQueries.getRooms(location=self._location, resvExample=p, available=True) return [room.id for room in rooms]
def excludeDay( self, dayD ): """ Inserts dayD into list of excluded days. dayD should be of date type (NOT datetime). """ ReservationBase.excludeDay( self, dayD ) lst = self._excludedDays if not dayD in lst: lst.append( dayD ) self._excludedDays = lst # Force update
def _postprocess(self, obj, fossil, iface): if iface is IRoomMetadataWithReservationsFossil: (startDT, endDT) = (self._fromDT or MIN_DATETIME, self._toDT or MAX_DATETIME) if self._fromDT or self._toDT: toDate = self._toDT.date() if self._toDT else None fromDate = self._fromDT.date() if self._fromDT else None resvEx = ReservationBase() resvEx.startDT = startDT resvEx.endDT = endDT resvEx.room = obj resvEx.isRejected = False resvEx.isCancelled = False if fromDate != toDate: resvEx.repeatability = RepeatabilityEnum.daily resvs = set(c.withReservation for c in resvEx.getCollisions()) else: resvs = obj.getReservations() iresvs1, iresvs2 = itertools.tee(itertools.ifilter(self._resvFilter, resvs), 2) fresvs = fossilize(iresvs1, IRoomReservationMetadataFossil, tz=self._tz, naiveTZ=self._serverTZ) for fresv, resv in itertools.izip(iter(fresvs), iresvs2): self._addOccurrences(fresv, resv, startDT, endDT) fossil['reservations'] = fresvs return fossil
def changeCreator(oldUser, newUser): dbi = DBMgr.getInstance() dbi.startRequest() Factory.getDALManager().connect() # check if the users exist if AvatarHolder().getById(oldUser) is None: print "There is no user with id %s" % oldUser return if AvatarHolder().getById(newUser) is None: print "There is no user with id %s" % newUser return resvEx = ReservationBase() resvEx.createdBy = oldUser allResv4OldUser = CrossLocationQueries.getReservations(resvExample=resvEx) if allResv4OldUser == []: print "No reservations for user %s" % oldUser return # resvs = ReservationBase.getReservations() # allResv4OldUser = [x for x in allResv if x.createdBy == oldUser] if type(allResv4OldUser) is not list: allResv4OldUser = [allResv4OldUser] # Modify reservations for r in allResv4OldUser: r.createdBy = newUser #print r.createdBy, r.id # Update index userReservationsIndexBTree = Reservation.getUserReservationsIndexRoot() newUserResvs = userReservationsIndexBTree.get(newUser) if newUserResvs == None: newUserResvs = [] # New list of reservations for this room userReservationsIndexBTree.insert(newUser, newUserResvs) newUserResvs.extend(allResv4OldUser) userReservationsIndexBTree[newUser] = newUserResvs[:] if userReservationsIndexBTree.has_key(oldUser): userReservationsIndexBTree.pop(oldUser) userReservationsIndexBTree._p_changed = 1 # close DB connection Factory.getDALManager().commit() Factory.getDALManager().disconnect() dbi.endRequest() print "%s reservations have moved from creator %s to creator %s" % ( len(allResv4OldUser), oldUser, newUser)
def changeCreator(oldUser, newUser): dbi = DBMgr.getInstance() dbi.startRequest() Factory.getDALManager().connect() # check if the users exist if AvatarHolder().getById(oldUser) is None: print "There is no user with id %s"%oldUser return if AvatarHolder().getById(newUser) is None: print "There is no user with id %s"%newUser return resvEx = ReservationBase() resvEx.createdBy = oldUser allResv4OldUser = CrossLocationQueries.getReservations( resvExample = resvEx) if allResv4OldUser == []: print "No reservations for user %s"%oldUser return # resvs = ReservationBase.getReservations() # allResv4OldUser = [x for x in allResv if x.createdBy == oldUser] if type(allResv4OldUser) is not list: allResv4OldUser = [allResv4OldUser] # Modify reservations for r in allResv4OldUser: r.createdBy = newUser #print r.createdBy, r.id # Update index userReservationsIndexBTree = Reservation.getUserReservationsIndexRoot() newUserResvs = userReservationsIndexBTree.get( newUser ) if newUserResvs == None: newUserResvs = [] # New list of reservations for this room userReservationsIndexBTree.insert( newUser, newUserResvs ) newUserResvs.extend( allResv4OldUser ) userReservationsIndexBTree[newUser] = newUserResvs[:] if userReservationsIndexBTree.has_key(oldUser): userReservationsIndexBTree.pop(oldUser) userReservationsIndexBTree._p_changed = 1 # close DB connection Factory.getDALManager().commit() Factory.getDALManager().disconnect() dbi.endRequest() print "%s reservations have moved from creator %s to creator %s" % (len(allResv4OldUser), oldUser, newUser)
def listResv4User(user): dbi = DBMgr.getInstance() dbi.startRequest() Factory.getDALManager().connect() resvEx = ReservationBase() resvEx.createdBy = user allResv = CrossLocationQueries.getReservations( resvExample = resvEx) print "User %s has %s resevations created by him/her"%(user, len(allResv)) Factory.getDALManager().disconnect() dbi.endRequest()
def getReservations2(): from MaKaC.rb_room import RoomBase Test.dalManager.connect() resvEx = Factory.newReservation() resvEx.startDT = datetime( 2006, 12, 01, 10 ) resvEx.endDT = datetime( 2006, 12, 14, 15 ) resvEx.repeatability = 0 # Daily #ReservationBase.getReservations( \ # roomExample = roomEx, # resvExample = resvEx, # available = True ) resv = ReservationBase.getReservations( resvID = 363818 ) print resv r = Reservation() r.room = resv.room r.startDT = datetime( 2006, 10, 13, 8, 30 ) r.endDT = datetime( 2006, 10, 13, 17, 30 ) col = r.getCollisions() print col Test.dalManager.disconnect()
def getAverageOccupation( **kwargs ): """ FINAL (not intented to be overriden) Returns float <0, 1> representing how often - on the avarage - the rooms are booked during the working hours. (1 == all the time, 0 == never). """ name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName ) # Get active, publically reservable rooms from MaKaC.rb_factory import Factory roomEx = Factory.newRoom() roomEx.isActive = True roomEx.isReservable = True rooms = CrossLocationQueries.getRooms( roomExample = roomEx, location = name ) # Find collisions with last month period from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum resvEx = ReservationBase() now = datetime.now() resvEx.endDT = datetime( now.year, now.month, now.day, 17, 30 ) resvEx.startDT = resvEx.endDT - timedelta( 30, 9 * 3600 ) # - 30 days and 9 hours resvEx.repeatability = RepeatabilityEnum.daily collisions = resvEx.getCollisions( rooms = rooms ) totalWorkingDays = 0 weekends = 0 for day in iterdays( resvEx.startDT, resvEx.endDT ): if day.weekday() in [5,6]: # Skip Saturday and Sunday weekends += 1 continue # if c.startDT is CERN Holiday: continue totalWorkingDays += 1 booked = timedelta( 0 ) for c in collisions: if c.startDT.weekday() in [5,6]: # Skip Saturday and Sunday continue # if c.startDT is CERN Holiday: continue booked = booked + ( c.endDT - c.startDT ) totalBookableTime = totalWorkingDays * 9 * len( rooms ) # Hours bookedTime = booked.days * 24 + 1.0 * booked.seconds / 3600 # Hours if totalBookableTime > 0: return bookedTime / totalBookableTime else: return 0 # Error (no rooms in db)
def _process( self ): from MaKaC.rb_room import RoomBase from datetime import datetime,timedelta from MaKaC.rb_reservation import ReservationBase startdt = enddt = datetime.now() today = startdt.date() startdt.replace( hour = 0, minute = 0) enddt.replace( hour = 23, minute = 59) self._req.content_type = "text/xml" XG = xmlGen.XMLGen() XG.openTag("response") rooms = RoomBase.getRooms() nbRooms = len(rooms) nbPublicRooms = nbPrivateRooms = nbSemiPrivateRooms = 0 for r in rooms: if not r.isReservable: nbPrivateRooms += 1 elif not r.resvsNeedConfirmation: nbPublicRooms += 1 else: nbSemiPrivateRooms += 1 self._createIndicator(XG, "total", "total number of managed rooms", nbRooms) self._createIndicator(XG, "public", "number of public rooms", nbPublicRooms) self._createIndicator(XG, "semiprivate", "number of semi-private rooms", nbSemiPrivateRooms) self._createIndicator(XG, "private", "number of private rooms", nbPrivateRooms) resvex = ReservationBase() resvex.isConfirmed = True resvex.isCancelled = False nbResvs = len(ReservationBase.getReservations( resvExample = resvex, days = [ startdt.date() ] )) resvex.usesAVC = True nbAVResvs = len(ReservationBase.getReservations( resvExample = resvex, days = [ startdt.date() ] )) resvex.needsAVCSupport = True resvex.needsAssistance = False nbAVResvsWithSupport = len(ReservationBase.getReservations( resvExample = resvex, days = [ startdt.date() ] )) self._createIndicator(XG, "nbbookings", "total number of bookings for today", nbResvs) self._createIndicator(XG, "nbvc", "number of remote collaboration bookings (video or phone conference)", nbAVResvs) self._createIndicator(XG, "nbvcsupport", "number of remote collaboration bookings with planned IT support", nbAVResvsWithSupport) XG.closeTag("response") return XG.getXml()
def insert(self): """ Documentation in base class. """ ReservationBase.insert(self) resvBTree = Reservation.getReservationsRoot() # Ensure ID if self.id == None: # # Maximum ID + 1 # if len( resvBTree ) > 0: # self.id = resvBTree.maxKey() + 1 # else: # self.id = 1 # Can not use maxKey for 1st record in a tree #Faster version of the code above try: self.id = resvBTree.maxKey() + 1 except ValueError: self.id = 1 # Add self to the BTree resvBTree[self.id] = self # Update room => room reservations index roomReservationsIndexBTree = Reservation.getRoomReservationsIndexRoot() resvs = roomReservationsIndexBTree.get(self.room.id) if resvs == None: resvs = [] # New list of reservations for this room roomReservationsIndexBTree.insert(self.room.id, resvs) resvs.append(self) roomReservationsIndexBTree[self.room.id] = resvs # Update user => user reservations index userReservationsIndexBTree = Reservation.getUserReservationsIndexRoot() resvs = userReservationsIndexBTree.get(self.createdBy) if resvs == None: resvs = [] # New list of reservations for this room userReservationsIndexBTree.insert(self.createdBy, resvs) resvs.append(self) userReservationsIndexBTree[self.createdBy] = resvs # Update day => reservations index self._addToDayReservationsIndex() # Update room+day => reservations index self._addToRoomDayReservationsIndex() self._notify('reservationCreated')
def insert(self): """ Documentation in base class. """ ReservationBase.insert(self) resvBTree = Reservation.getReservationsRoot() # Ensure ID if self.id == None: # # Maximum ID + 1 # if len( resvBTree ) > 0: # self.id = resvBTree.maxKey() + 1 # else: # self.id = 1 # Can not use maxKey for 1st record in a tree # Faster version of the code above try: self.id = resvBTree.maxKey() + 1 except ValueError: self.id = 1 # Add self to the BTree resvBTree[self.id] = self # Update room => room reservations index roomReservationsIndexBTree = Reservation.getRoomReservationsIndexRoot() resvs = roomReservationsIndexBTree.get(self.room.id) if resvs == None: resvs = [] # New list of reservations for this room roomReservationsIndexBTree.insert(self.room.id, resvs) resvs.append(self) roomReservationsIndexBTree[self.room.id] = resvs # Update user => user reservations index userReservationsIndexBTree = Reservation.getUserReservationsIndexRoot() resvs = userReservationsIndexBTree.get(self.createdBy) if resvs == None: resvs = [] # New list of reservations for this room userReservationsIndexBTree.insert(self.createdBy, resvs) resvs.append(self) userReservationsIndexBTree[self.createdBy] = resvs # Update day => reservations index self._addToDayReservationsIndex() # Update room+day => reservations index self._addToRoomDayReservationsIndex() self._notify("reservationCreated")
def includeDay(self, dayD): """ Inserts dayD into list of excluded days. dayD should be of date type (not datetime). """ ReservationBase.includeDay(self, dayD) lst = self._excludedDays lst.remove(dayD) self._excludedDays = lst # Force update # Re-indexing that day dayReservationsIndexBTree = Reservation.getDayReservationsIndexRoot() resvs = dayReservationsIndexBTree.get(dayD) if resvs is None: resvs = [] dayReservationsIndexBTree.insert(dayD, resvs) resvs.append(self) dayReservationsIndexBTree[dayD] = resvs
def getReservations( self, resvExample = None, archival = None ): """ FINAL (not intented to be overriden) Returns reservations of this room, meeting specified criteria. Look ReservationBase.getReservations for details. """ # Simply redirect to the plugin from MaKaC.rb_reservation import ReservationBase return ReservationBase.getReservations( resvExample = resvExample, rooms = [self], archival = archival )
def excludeDay( self, dayD, unindex = False ): """ Inserts dayD into list of excluded days. dayD should be of date type (NOT datetime). """ ReservationBase.excludeDay( self, dayD ) lst = self._excludedDays if not dayD in lst: lst.append( dayD ) self._excludedDays = lst # Force update if unindex: dayReservationsIndexBTree = Reservation.getDayReservationsIndexRoot() if dayReservationsIndexBTree.has_key(dayD): try: resvs = dayReservationsIndexBTree[dayD] resvs.remove( self ) dayReservationsIndexBTree[dayD] = resvs except ValueError, e: Logger.get('RoomBooking').debug("excludeDay: Unindexing a day (%s) which is not indexed"%dayD)
def getReservations( self, resvExample = None, archival = None ): """ FINAL (not intented to be overriden) Returns reservations of this room, meeting specified criteria. Look ReservationBase.getReservations for details. """ # Simply redirect to the plugin from MaKaC.rb_factory import Factory from MaKaC.rb_reservation import ReservationBase return ReservationBase.getReservations( resvExample = resvExample, rooms = [self], archival = archival )
def _process( self ): from MaKaC.rb_room import RoomBase from datetime import datetime,timedelta from MaKaC.rb_reservation import ReservationBase startdt = enddt = datetime.now() today = startdt.date() startdt.replace( hour = 0, minute = 0) enddt.replace( hour = 23, minute = 59) self._responseUtil.content_type = 'text/xml' XG = xmlGen.XMLGen() XG.openTag("response") rooms = RoomBase.getRooms() nbRooms = len(rooms) nbPublicRooms = nbPrivateRooms = nbSemiPrivateRooms = 0 for r in rooms: if not r.isReservable: nbPrivateRooms += 1 elif not r.resvsNeedConfirmation: nbPublicRooms += 1 else: nbSemiPrivateRooms += 1 self._createIndicator(XG, "total", "total number of managed rooms", nbRooms) self._createIndicator(XG, "public", "number of public rooms", nbPublicRooms) self._createIndicator(XG, "semiprivate", "number of semi-private rooms", nbSemiPrivateRooms) self._createIndicator(XG, "private", "number of private rooms", nbPrivateRooms) resvex = ReservationBase() resvex.isConfirmed = True resvex.isCancelled = False nbResvs = len(ReservationBase.getReservations( resvExample = resvex, days = [ startdt.date() ] )) resvex.usesAVC = True nbAVResvs = len(ReservationBase.getReservations( resvExample = resvex, days = [ startdt.date() ] )) resvex.needsAVCSupport = True resvex.needsAssistance = False nbAVResvsWithSupport = len(ReservationBase.getReservations( resvExample = resvex, days = [ startdt.date() ] )) self._createIndicator(XG, "nbbookings", "total number of bookings for today", nbResvs) self._createIndicator(XG, "nbvc", "number of remote collaboration bookings (video or phone conference)", nbAVResvs) self._createIndicator(XG, "nbvcsupport", "number of remote collaboration bookings with planned IT support", nbAVResvsWithSupport) XG.closeTag("response") return XG.getXml()
def excludeDay(self, day, unindex=False): """ Inserts day into list of excluded days. day should be of date type (NOT datetime). """ ReservationBase.excludeDay(self, day) lst = self._excludedDays if not day in lst: lst.append(day) self._excludedDays = lst # Force update if unindex: day_resv_idx = Reservation.getDayReservationsIndexRoot() room_day_resv_idx = Reservation.getRoomDayReservationsIndexRoot() if day in day_resv_idx: try: resvs = day_resv_idx[day] resvs.remove(self) day_resv_idx[day] = resvs except ValueError, e: Logger.get("RoomBooking").debug( "excludeDay: DayReservationsIndex - unindexing " "a day ({0}) which is not indexed".format(day) ) key = (self.room.id, day) if key in room_day_resv_idx: try: resvs = room_day_resv_idx[key] resvs.remove(self) room_day_resv_idx[key] = resvs except ValueError, e: Logger.get("RoomBooking").debug( "excludeDay: RoomDayReservationsIndex - unindexing " "a key ({0}) which is not indexed".format(key) )
def reservation(self, locList): Factory.getDALManager().connect() resvEx = ReservationBase() resvEx.startDT = self._fromDT resvEx.endDT = self._toDT locList = filter(lambda loc: Location.parse(loc) is not None, locList) if self._fromDT or self._toDT: daysParam = (day.date() for day in rrule.rrule(rrule.DAILY, dtstart=self._fromDT, until=self._toDT)) else: # slow! daysParam = None for loc in sorted(locList): resvs = CrossLocationQueries.getReservations(location=loc, resvExample=resvEx, days=daysParam) for obj in self._process(resvs, filter=self._resvFilter): yield obj Factory.getDALManager().disconnect()
def getAverageOccupation(**kwargs): """ FINAL (not intented to be overriden) Returns float <0, 1> representing how often - on the avarage - the rooms are booked during the working hours. (1 == all the time, 0 == never). """ name = kwargs.get("location", Location.getDefaultLocation().friendlyName) # Get active, publically reservable rooms from MaKaC.rb_factory import Factory roomEx = Factory.newRoom() roomEx.isActive = True roomEx.isReservable = True rooms = CrossLocationQueries.getRooms(roomExample=roomEx, location=name) # Find collisions with last month period from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum resvEx = ReservationBase() resvEx.endDT = datetime.combine(date.today(), time(17, 30)) resvEx.startDT = resvEx.endDT.replace(hour=8) - timedelta(days=30) resvEx.repeatability = RepeatabilityEnum.daily collisions = resvEx.getCollisions(rooms=rooms) totalWorkingDays = sum(1 for day in iterdays(resvEx.startDT, resvEx.endDT) if day.weekday() not in (5, 6)) booked = timedelta() for c in collisions: if c.startDT.weekday() in (5, 6): # skip Saturday and Sunday continue booked += c.endDT - c.startDT totalBookableTime = totalWorkingDays * 9 * len(rooms) # Hours bookedTime = (booked.days * 86400 + booked.seconds) / 3600.0 if totalBookableTime > 0: return bookedTime / totalBookableTime else: return 0
def sendStartNotifications(logger): if getRoomBookingOption('notificationHour') != datetime.now().hour: if DEBUG: print 'Outside notification hour. Continuing anyway due to debug mode.' else: return days = _getRoomSpecificNotificationBeforeDays() days.add(getRoomBookingOption('notificationBefore')) dates = [date.today() + timedelta(days=day) for day in days] if DEBUG: print 'Dates to check: %r' % map(str, dates) for resv in ReservationBase.getReservations(days=dates): # for testing, remove location later se = resv.getStartEndNotification() se.sendStartNotification(logger)
def sendStartNotifications(logger): if getRoomBookingOption('notificationHour') != datetime.now().hour: if DEBUG: print 'Outside notification hour. Continuing anyway due to debug mode.' else: return days = _getRoomSpecificNotificationBeforeDays() days.add(getRoomBookingOption('notificationBefore')) dates = [date.today() + timedelta(days=day) for day in days] if DEBUG: print 'Dates to check: %r' % map(str, dates) for resv in ReservationBase.getReservations( days=dates): # for testing, remove location later se = resv.getStartEndNotification() se.sendStartNotification(logger)
def getLiveReservations(self, resvExample=None): """ FINAL (not intented to be overriden) Returns valid, non archival reservations of this room, meeting specified criteria. Look ReservationBase.getReservations for details. """ from MaKaC.rb_factory import Factory from MaKaC.rb_reservation import ReservationBase if resvExample is None: resvExample = Factory.newReservation() resvExample.isCancelled = False resvExample.isRejected = False return ReservationBase.getReservations(resvExample=resvExample, rooms=[self], archival=False)
def getLiveReservations( self, resvExample = None ): """ FINAL (not intented to be overriden) Returns valid, non archival reservations of this room, meeting specified criteria. Look ReservationBase.getReservations for details. """ from MaKaC.rb_factory import Factory from MaKaC.rb_reservation import ReservationBase if resvExample == None: resvExample = Factory.newReservation() resvExample.isCancelled = False resvExample.isRejected = False return ReservationBase.getReservations( resvExample = resvExample, rooms = [self], archival = False )
def getMyAverageOccupation(self, period="pastmonth"): """ FINAL (not intented to be overriden) Returns float <0, 1> representing how often - on the avarage - the room is booked during the working hours. (1 == all the time, 0 == never). """ # Find collisions with last month period from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum resvEx = ReservationBase() now = datetime.now() if period == "pastmonth": resvEx.endDT = datetime(now.year, now.month, now.day, 17, 30) resvEx.startDT = resvEx.endDT - timedelta( 30, 9 * 3600) # - 30 days and 9 hours elif period == "thisyear": resvEx.endDT = datetime(now.year, now.month, now.day, 17, 30) resvEx.startDT = datetime(now.year, 1, 1, 0, 0) resvEx.repeatability = RepeatabilityEnum.daily collisions = resvEx.getCollisions(rooms=[self]) totalWorkingDays = 0 weekends = 0 for day in iterdays(resvEx.startDT, resvEx.endDT): if day.weekday() in [5, 6]: # Skip Saturday and Sunday weekends += 1 continue # if c.startDT is CERN Holiday: continue totalWorkingDays += 1 booked = timedelta(0) for c in collisions: if c.startDT.weekday() in [5, 6]: # Skip Saturday and Sunday continue # if c.startDT is CERN Holiday: continue booked = booked + (c.endDT - c.startDT) totalBookableTime = totalWorkingDays * 9 # Hours bookedTime = booked.days * 24 + 1.0 * booked.seconds / 3600 # Hours if totalBookableTime > 0: return bookedTime / totalBookableTime else: return 0
def getReservations(): from MaKaC.rb_room import RoomBase Test.dalManager.connect() roomEx = Factory.newRoom() roomEx.name = 'TH AMPHITHEATRE' resvEx = Factory.newReservation() resvEx.startDT = datetime( 2006, 12, 01, 10 ) resvEx.endDT = datetime( 2006, 12, 14, 15 ) #resvEx.bookedForName = 'Jean-Jacques Blais' resvs = ReservationBase.getReservations( resvExample = resvEx, rooms = [roomEx] ) for resv in resvs: print "=============================" print resv Test.dalManager.disconnect()
def getAverageOccupation(**kwargs): """ FINAL (not intented to be overriden) Returns float <0, 1> representing how often - on the avarage - the rooms are booked during the working hours. (1 == all the time, 0 == never). """ name = kwargs.get('location', Location.getDefaultLocation().friendlyName) # Get active, publically reservable rooms from MaKaC.rb_factory import Factory roomEx = Factory.newRoom() roomEx.isActive = True roomEx.isReservable = True rooms = CrossLocationQueries.getRooms(roomExample=roomEx, location=name) # Find collisions with last month period from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum resvEx = ReservationBase() now = datetime.now() resvEx.endDT = datetime(now.year, now.month, now.day, 17, 30) resvEx.startDT = resvEx.endDT - timedelta( 30, 9 * 3600) # - 30 days and 9 hours resvEx.repeatability = RepeatabilityEnum.daily collisions = resvEx.getCollisions(rooms=rooms) totalWorkingDays = 0 weekends = 0 for day in iterdays(resvEx.startDT, resvEx.endDT): if day.weekday() in [5, 6]: # Skip Saturday and Sunday weekends += 1 continue # if c.startDT is CERN Holiday: continue totalWorkingDays += 1 booked = timedelta(0) for c in collisions: if c.startDT.weekday() in [5, 6]: # Skip Saturday and Sunday continue # if c.startDT is CERN Holiday: continue booked = booked + (c.endDT - c.startDT) totalBookableTime = totalWorkingDays * 9 * len(rooms) # Hours bookedTime = booked.days * 24 + 1.0 * booked.seconds / 3600 # Hours if totalBookableTime > 0: return bookedTime / totalBookableTime else: return 0 # Error (no rooms in db)
def getMyAverageOccupation( self, period="pastmonth" ): """ FINAL (not intented to be overriden) Returns float <0, 1> representing how often - on the avarage - the room is booked during the working hours. (1 == all the time, 0 == never). """ # Find collisions with last month period from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum resvEx = ReservationBase() now = datetime.now() if period == "pastmonth": resvEx.endDT = datetime( now.year, now.month, now.day, 17, 30 ) resvEx.startDT = resvEx.endDT - timedelta( 30, 9 * 3600 ) # - 30 days and 9 hours elif period == "thisyear": resvEx.endDT = datetime( now.year, now.month, now.day, 17, 30 ) resvEx.startDT = datetime( now.year, 1, 1, 0, 0 ) resvEx.repeatability = RepeatabilityEnum.daily collisions = resvEx.getCollisions( rooms = [self] ) totalWorkingDays = 0 weekends = 0 for day in iterdays( resvEx.startDT, resvEx.endDT ): if day.weekday() in [5,6]: # Skip Saturday and Sunday weekends += 1 continue # if c.startDT is CERN Holiday: continue totalWorkingDays += 1 booked = timedelta( 0 ) for c in collisions: if c.startDT.weekday() in [5,6]: # Skip Saturday and Sunday continue # if c.startDT is CERN Holiday: continue booked = booked + ( c.endDT - c.startDT ) totalBookableTime = totalWorkingDays * 9 # Hours bookedTime = booked.days * 24 + 1.0 * booked.seconds / 3600 # Hours if totalBookableTime > 0: return bookedTime / totalBookableTime else: return 0
def getMyAverageOccupation(self, period="pastmonth"): """ FINAL (not intented to be overriden) Returns float <0, 1> representing how often - on the avarage - the room is booked during the working hours. (1 == all the time, 0 == never). """ # Find collisions with the givenmonth period from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum resvEx = ReservationBase() resvEx.endDT = datetime.combine(date.today(), time(17, 30)) if period == "thisyear": resvEx.startDT = datetime(date.today().year, 1, 1, 8, 30) elif period == "pastmonth": resvEx.startDT = resvEx.endDT.replace(hour=8) - timedelta(days=30) elif period == "pastyear": resvEx.startDT = resvEx.endDT.replace(hour=8) - timedelta(days=365) else: raise ValueError("Invalid period: {0}".format(period)) resvEx.repeatability = RepeatabilityEnum.daily collisions = resvEx.getCollisions(rooms=[self]) totalWorkingDays = sum(1 for day in iterdays(resvEx.startDT, resvEx.endDT) if day.weekday() not in (5, 6)) booked = timedelta() for c in collisions: if c.startDT.weekday() in (5, 6): # skip Saturday and Sunday continue booked += c.endDT - c.startDT totalBookableTime = totalWorkingDays * 9 # Hours bookedTime = (booked.days * 86400 + booked.seconds) / 3600.0 if totalBookableTime > 0: return bookedTime / totalBookableTime else: return 0
def __init__(self): ReservationBase.__init__(self) self._excludedDays = [] self.useVC = [] self.resvHistory = ResvHistoryHandler() self.startEndNotification = None
def countReservations( *args, **kwargs ): """ Documentation in base class. """ kwargs['countOnly'] = True return ReservationBase.getReservations( **kwargs )
def getExcludedDays( self ): ReservationBase.getExcludedDays( self ) from copy import copy lst = copy( self._excludedDays ) lst.sort() return lst
def setExcludedDays( self, excludedDays ): ReservationBase.setExcludedDays( self, excludedDays ) self._excludedDays = excludedDays
def __init__( self ): ReservationBase.__init__( self ) self._excludedDays = [] self.useVC = []
def dayIsExcluded( self, dayD ): ReservationBase.dayIsExcluded( self, dayD ) return dayD in self.getExcludedDays()
def update(self): ReservationBase.update(self) self._notify('reservationUpdated')