Ejemplo n.º 1
0
 def getNumberOfReservableRooms( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns number of rooms which can be reserved.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     return location.factory.newRoom().getNumberOfReservableRooms(location=name)
Ejemplo n.º 2
0
 def getNumberOfRooms( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns total number of rooms in database.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     return location.factory.newRoom().getNumberOfRooms(location=name)
Ejemplo n.º 3
0
 def getNumberOfActiveRooms( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns number of rooms that are active (not logicaly deleted).
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     return location.factory.newRoom().getNumberOfActiveRooms(location=name)
Ejemplo n.º 4
0
 def getNumberOfActiveRooms( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns number of rooms that are active (not logicaly deleted).
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     return location.factory.newRoom().getNumberOfActiveRooms(location=name)
Ejemplo n.º 5
0
 def getNumberOfRooms( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns total number of rooms in database.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     return location.factory.newRoom().getNumberOfRooms(location=name)
Ejemplo n.º 6
0
 def getNumberOfReservableRooms( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns number of rooms which can be reserved.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     return location.factory.newRoom().getNumberOfReservableRooms(location=name)
Ejemplo n.º 7
0
    def removeEquipment( equipmentName, *args, **kwargs ):
        from MaKaC.rb_location import Location
        location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )

        lst = EquipmentManager.getRoot()
        lst[location].remove( equipmentName )
        Factory.getDALManager().getRoot()[_EQUIPMENT_LIST] = lst
Ejemplo n.º 8
0
 def getNumberOfReservableRooms( *args, **kwargs ):
     """ Documentation in base class. """
     location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     room = Factory.newRoom()
     room.isReservable = True
     room.isActive = True
     return Room.countRooms( roomExample = room, location = location )
Ejemplo n.º 9
0
    def testReservationSpecificBlockingMethods(self):
        block = self._createTestBlocking()
        candResv = Location.getDefaultLocation().factory.newReservation()
        candResv.startDT = datetime.combine(block.startDate - timedelta(days=1), time())
        candResv.endDT = datetime.combine(block.endDate + timedelta(days=1), time(23, 59))
        candResv.repeatability = RepeatabilityEnum.daily
        candResv.isConfirmed = None

        candResv.room = self._room7
        self.assertTrue(candResv.getBlockingConflictState() is None) # No blocking
        self.assertEqual(candResv.getBlockedDates(), [])
        br = self._blockRoom(block, self._room7, False)
        block.update()
        self.assertEqual(candResv.getBlockingConflictState(), 'pending') # Pending blocking
        self.assertEqual(candResv.getBlockedDates(), [])
        br.approve(sendNotification=False)
        self.assertEqual(candResv.getBlockingConflictState(), 'active') # Active blocking
        blockingDays = frozenset((date(2010, 12, 31), date(2011, 1, 1)))
        self.assertEqual(frozenset(candResv.getBlockedDates()), blockingDays)
        # Test with various users set. This basically tests if all people who are allowed to override can actually override
        self.assertTrue(candResv.getBlockingConflictState(self._avatar1) is None) # room owner
        self.assertEqual(candResv.getBlockedDates(self._avatar1), [])
        self.assertTrue(candResv.getBlockingConflictState(self._avatar2) is None) # blocking owner
        self.assertEqual(candResv.getBlockedDates(self._avatar2), [])
        self.assertEqual(candResv.getBlockingConflictState(self._avatar3), 'active') # not permitted to override
        self.assertEqual(frozenset(candResv.getBlockedDates(self._avatar3)), blockingDays)
        self.assertTrue(candResv.getBlockingConflictState(self._avatar4) is None) # on blocking ACL
        self.assertEqual(candResv.getBlockedDates(self._avatar4), [])
        # Rejecting an existing blocking is not possible via the UI, but we can test it anyway
        br.reject(sendNotification=False)
        self.assertTrue(candResv.getBlockingConflictState() is None) # No blocking
        self.assertEqual(candResv.getBlockedDates(), [])
Ejemplo n.º 10
0
 def getNumberOfReservableRooms( *args, **kwargs ):
     """ Documentation in base class. """
     location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     room = Factory.newRoom()
     room.isReservable = True
     room.isActive = True
     return Room.countRooms( roomExample = room, location = location )
Ejemplo n.º 11
0
 def setPossibleEquipment( equipmentList, *args, **kwargs ):
     from MaKaC.rb_location import Location
     location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     
     lst = EquipmentManager.getRoot()
     lst[location] = equipmentList
     Factory.getDALManager().getRoot()[_EQUIPMENT_LIST] = lst     # Force update
Ejemplo n.º 12
0
    def removeEquipment(equipmentName, *args, **kwargs):
        from MaKaC.rb_location import Location
        location = kwargs.get('location',
                              Location.getDefaultLocation().friendlyName)

        lst = EquipmentManager.getRoot()
        lst[location].remove(equipmentName)
        Factory.getDALManager().getRoot()[_EQUIPMENT_LIST] = lst
Ejemplo n.º 13
0
    def setPossibleEquipment(equipmentList, *args, **kwargs):
        from MaKaC.rb_location import Location
        location = kwargs.get('location',
                              Location.getDefaultLocation().friendlyName)

        lst = EquipmentManager.getRoot()
        lst[location] = equipmentList
        Factory.getDALManager().root[_EQUIPMENT_LIST] = lst  # Force update
Ejemplo n.º 14
0
 def getAttributes( *args, **kwargs ):
     location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     
     root = CustomAttributesManager.getRoot()
     
     if not root.has_key( location ):
         CustomAttributesManager.setAttributes( [], location = location )
     
     return CustomAttributesManager.getRoot()[location]
Ejemplo n.º 15
0
 def getTotalSurfaceAndCapacity( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns (total_surface, total_capacity) of all Active rooms.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     roomEx = location.factory.newRoom()
     roomEx.isActive = True
     roomEx.isReservable = True
     rooms = CrossLocationQueries.getRooms( roomExample = roomEx, location = name )
     totalSurface, totalCapacity = 0, 0
     for r in rooms:
         if r.surfaceArea:
             totalSurface += r.surfaceArea
         if r.capacity:
             totalCapacity += r.capacity
     return ( totalSurface, totalCapacity )
Ejemplo n.º 16
0
 def getTotalSurfaceAndCapacity( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns (total_surface, total_capacity) of all Active rooms.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     roomEx = location.factory.newRoom()
     roomEx.isActive = True
     roomEx.isReservable = True
     rooms = CrossLocationQueries.getRooms( roomExample = roomEx, location = name )
     totalSurface, totalCapacity = 0, 0
     for r in rooms:
         if r.surfaceArea:
             totalSurface += r.surfaceArea
         if r.capacity:
             totalCapacity += r.capacity
     return ( totalSurface, totalCapacity )
Ejemplo n.º 17
0
    def insertEquipment( equipmentName, *args, **kwargs ):
        from MaKaC.rb_location import Location
        location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )

        lst = EquipmentManager.getRoot()
        if lst.get( location ) == None:
            lst[location] = []
        lst[location].append( equipmentName )
        Factory.getDALManager().getRoot()[_EQUIPMENT_LIST] = lst
Ejemplo n.º 18
0
    def _getAnswer( self ):

        res = []

        if Location.parse( self._location ):
            for room in CrossLocationQueries.getRooms( location = self._location ):
                res.append((room.name, room.getFullName()))

        return res
Ejemplo n.º 19
0
    def _getAnswer(self):

        res = {}
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(location=self._location):
                    res[room.name] = room.name
        return sorted(res)
Ejemplo n.º 20
0
    def _getAnswer(self):

        res = []
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(location=self._location, allFast=True):
                        res.append((room.name, room.getFullName()))
        return res
Ejemplo n.º 21
0
    def getPossibleEquipment( *args, **kwargs ):
        from MaKaC.rb_location import Location
        location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )

        lst = EquipmentManager.getRoot()
        if lst.get( location ) == None:
            lst[location] = []
            Factory.getDALManager().getRoot()[_EQUIPMENT_LIST] = lst
        return lst[location]
Ejemplo n.º 22
0
def initializeRoomBookingDB(location, force=False):
    """
    Modifies Indico main database.
    - location list

    Creates necessary branches in room booking database.
    - rooms branch
    - bookings branch
    - several indexes
    """
    indicoRoot = MaKaC.common.DBMgr.getInstance().getDBConnection().root()
    root = DALManagerCERN().getRoot()
    # 1. Location -----------------------------------------------------------

    initialLocation = Location(location, FactoryCERN)
    if force or not indicoRoot.has_key('RoomBookingLocationList'):
        indicoRoot['RoomBookingLocationList'] = [initialLocation]
    if force or not indicoRoot.has_key('DefaultRoomBookingLocation'):
        indicoRoot['DefaultRoomBookingLocation'] = location

    # 2. Rooms & Bookings ---------------------------------------------------

    # Create rooms branch
    if force or not root.has_key('Rooms'):
        root['Rooms'] = IOBTree()

    # Create reservations branch
    if force or not root.has_key('Reservations'):
        root['Reservations'] = IOBTree()

    # Create blocking branch
    if force or not root.has_key('RoomBlocking'):
        root['RoomBlocking'] = OOBTree()
        root['RoomBlocking']['Blockings'] = IOBTree()
        root['RoomBlocking']['Indexes'] = OOBTree()
        root['RoomBlocking']['Indexes']['OwnerBlockings'] = OOBTree()
        root['RoomBlocking']['Indexes']['DayBlockings'] = CalendarDayIndex()
        root['RoomBlocking']['Indexes']['RoomBlockings'] = OOBTree()

    # Create indexes
    if force or not root.has_key('RoomReservationsIndex'):
        root['RoomReservationsIndex'] = OOBTree()
    if force or not root.has_key('UserReservationsIndex'):
        root['UserReservationsIndex'] = OOBTree()
    if force or not root.has_key('DayReservationsIndex'):
        root['DayReservationsIndex'] = OOBTree()
    if force or not root.has_key('RoomDayReservationsIndex'):
        root['RoomDayReservationsIndex'] = OOBTree()

    # Create possible equipment branch
    if force or not root.has_key('EquipmentList'):
        root['EquipmentList'] = {}

    # update Catalog with new rb indexes
    Catalog.updateDB()

    DALManagerCERN().commit()
Ejemplo n.º 23
0
    def approve(self, sendNotification=True):
        """
        Approve the room blocking and reject colloding bookings
        """
        self.active = True
        # If the blocking has not been saved yet, don't reject anything - will be done later in block.insert()
        if self.block.id is None:
            return
        # Create a fake reservation candidate to find bookings colliding with the blocking
        candResv = Location.parse(self.room.locationName).factory.newReservation()
        candResv.room = self.room
        candResv.startDT = datetime.datetime.combine(self.block.startDate, datetime.time())
        candResv.endDT = datetime.datetime.combine(self.block.endDate, datetime.time(23, 59))
        candResv.repeatability = RepeatabilityEnum.daily
        candResv.isConfirmed = None
        collisions = candResv.getCollisions()
        rejectionReason = "Conflict with blocking %s: %s" % (self.block.id, self.block.message)
        emailsToBeSent = []
        for coll in collisions:
            collResv = coll.withReservation
            if collResv.isRejected:
                continue
            elif self.block.canOverride(collResv.createdByUser(), self.room):
                continue
            elif collResv.repeatability is None or (
                collResv.startDT.date() >= self.block.startDate and collResv.endDT.date() <= self.block.endDate
            ):
                collResv.rejectionReason = rejectionReason
                collResv.reject()  # Just sets isRejected = True
                collResv.update()
                emails = collResv.notifyAboutRejection()
                emailsToBeSent += emails

                # Add entry to the booking history
                info = []
                info.append("Booking rejected")
                info.append("Reason: '%s'" % collResv.rejectionReason)
                histEntry = ResvHistoryEntry(self.block.createdByUser, info, emails)
                collResv.getResvHistory().addHistoryEntry(histEntry)
            else:  # repeatable -> only reject the specific days
                rejectDate = coll.startDT.date()
                collResv.excludeDay(rejectDate, unindex=True)
                collResv.update()
                emails = collResv.notifyAboutRejection(date=rejectDate, reason=rejectionReason)
                emailsToBeSent += emails

                # Add entry to the booking history
                info = []
                info.append("Booking occurence of the %s rejected" % rejectDate.strftime("%d %b %Y"))
                info.append("Reason: '%s'" % rejectionReason)
                histEntry = ResvHistoryEntry(self.block.createdByUser, info, emails)
                collResv.getResvHistory().addHistoryEntry(histEntry)
        if sendNotification:
            emailsToBeSent += RoomBlockingNotification.blockingRequestProcessed(self)
        for email in emailsToBeSent:
            GenericMailer.send(GenericNotification(email))
Ejemplo n.º 24
0
    def insertEquipment(equipmentName, *args, **kwargs):
        from MaKaC.rb_location import Location
        location = kwargs.get('location',
                              Location.getDefaultLocation().friendlyName)

        lst = EquipmentManager.getRoot()
        if lst.get(location) == None:
            lst[location] = []
        lst[location].append(equipmentName)
        Factory.getDALManager().getRoot()[_EQUIPMENT_LIST] = lst
Ejemplo n.º 25
0
    def setHidden( customAttributeName, isHidden, *args, **kwargs ):
        """ Makes attribute hidden."""
        location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )

        attsList = CustomAttributesManager.getAttributes( location = location )
        for at in attsList:
            if at['name'] == customAttributeName:
                at['hidden'] = isHidden
                break;
        CustomAttributesManager.setAttributes( attsList, location = location )
Ejemplo n.º 26
0
 def removeAttribute( customAttributeName, *args, **kwargs ):
     """ Deletes attribute from the list of custom attributes. """
     location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     
     attsList = CustomAttributesManager.getAttributes( location = location )
     for at in attsList:
         if at['name'] == customAttributeName:
             attsList.remove( at )
             break;
     CustomAttributesManager.setAttributes( attsList, location = location )
Ejemplo n.º 27
0
    def setRequired( customAttributeName, isRequired, *args, **kwargs ):
        """ Makes attribute required."""
        location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )

        attsList = CustomAttributesManager.getAttributes( location = location )
        for at in attsList:
            if at['name'] == customAttributeName:
                at['required'] = isRequired
                break;
        CustomAttributesManager.setAttributes( attsList, location = location )
Ejemplo n.º 28
0
    def getPossibleEquipment(*args, **kwargs):
        from MaKaC.rb_location import Location
        location = kwargs.get('location',
                              Location.getDefaultLocation().friendlyName)

        lst = EquipmentManager.getRoot()
        if lst.get(location) == None:
            lst[location] = []
            Factory.getDALManager().getRoot()[_EQUIPMENT_LIST] = lst
        return lst[location]
Ejemplo n.º 29
0
    def _getAnswer(self):

        res = []
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(
                        location=self._location):
                    res.append((room.name, room.getFullName()))
        return res
Ejemplo n.º 30
0
    def _getAnswer( self ):

        if not Location.parse( self._location ):
            return {}

        res = {}
        for room in CrossLocationQueries.getRooms( location = self._location ):
            res[room.name] = room.name

        return sorted(res)
Ejemplo n.º 31
0
    def _getAnswer(self):

        res = {}
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(
                        location=self._location):
                    res[room.name] = room.name
        return sorted(res)
Ejemplo n.º 32
0
    def _getAnswer(self):

        if not Location.parse(self._location):
            return {}

        res = {}
        for room in CrossLocationQueries.getRooms(location=self._location):
            res[room.name] = room.name

        return sorted(res)
Ejemplo n.º 33
0
def initializeRoomBookingDB(location, force=False):
    """
    Modifies Indico main database.
    - location list

    Creates necessary branches in room booking database.
    - rooms branch
    - bookings branch
    - several indexes
    """
    indicoRoot = MaKaC.common.DBMgr.getInstance().getDBConnection().root()
    root = DALManagerCERN().root

    # 1. Location -----------------------------------------------------------

    initialLocation = Location(location, FactoryCERN)
    if force or not indicoRoot.has_key('RoomBookingLocationList'):
        indicoRoot['RoomBookingLocationList'] = [initialLocation]
        print "Locations branch created (Indico db)"
    if force or not indicoRoot.has_key('DefaultRoomBookingLocation'):
        indicoRoot['DefaultRoomBookingLocation'] = location
        print "Default location set to " + location

    # 2. Rooms & Bookings ---------------------------------------------------

    # Create rooms branch
    if force or not root.has_key('Rooms'):
        root['Rooms'] = IOBTree()
        print "Rooms branch created"

    # Create reservations branch
    if force or not root.has_key('Reservations'):
        root['Reservations'] = IOBTree()
        print "Reservations branch created"

    # Create indexes
    if force or not root.has_key('RoomReservationsIndex'):
        root['RoomReservationsIndex'] = OOBTree()
        print "Room => Reservations Index branch created"
    if force or not root.has_key('UserReservationsIndex'):
        root['UserReservationsIndex'] = OOBTree()
        print "User => Reservations Index branch created"
    if force or not root.has_key('DayReservationsIndex'):
        root['DayReservationsIndex'] = OOBTree()
        print "Day => Reservations Index branch created"

    # Create possible equipment branch
    if force or not root.has_key('EquipmentList'):
        root['EquipmentList'] = {}
        print "Equipment branch created"

    AvatarHolder().invalidateRoomManagerIdList()
    print "Cached list of room managers invalidated"

    DALManagerCERN().commit()
Ejemplo n.º 34
0
    def approve(self, sendNotification=True):
        """
        Approve the room blocking and reject colloding bookings
        """
        self.active = True
        # If the blocking has not been saved yet, don't reject anything - will be done later in block.insert()
        if self.block.id is None:
            return
        # Create a fake reservation candidate to find bookings colliding with the blocking
        candResv = Location.parse(self.room.locationName).factory.newReservation()
        candResv.room = self.room
        candResv.startDT = datetime.datetime.combine(self.block.startDate, datetime.time())
        candResv.endDT = datetime.datetime.combine(self.block.endDate, datetime.time(23, 59))
        candResv.repeatability = RepeatabilityEnum.daily
        candResv.isConfirmed = None
        collisions = candResv.getCollisions()
        rejectionReason = "Conflict with blocking %s: %s" % (self.block.id, self.block.message)
        emailsToBeSent = []
        for coll in collisions:
            collResv = coll.withReservation
            if collResv.isRejected:
                continue
            elif self.block.canOverride(collResv.createdByUser(), self.room):
                continue
            elif (collResv.repeatability is None or
                (collResv.startDT.date() >= self.block.startDate and collResv.endDT.date() <= self.block.endDate)):
                collResv.rejectionReason = rejectionReason
                collResv.reject() # Just sets isRejected = True
                collResv.update()
                emails = collResv.notifyAboutRejection()
                emailsToBeSent += emails

                # Add entry to the booking history
                info = []
                info.append("Booking rejected")
                info.append("Reason: '%s'" % collResv.rejectionReason)
                histEntry = ResvHistoryEntry(self.block.createdByUser, info, emails)
                collResv.getResvHistory().addHistoryEntry(histEntry)
            else: # repeatable -> only reject the specific days
                rejectDate = coll.startDT.date()
                collResv.excludeDay(rejectDate, unindex=True)
                collResv.update()
                emails = collResv.notifyAboutRejection(date=rejectDate, reason=rejectionReason)
                emailsToBeSent += emails

                # Add entry to the booking history
                info = []
                info.append("Booking occurence of the %s rejected" % rejectDate.strftime("%d %b %Y"))
                info.append("Reason: '%s'" % rejectionReason)
                histEntry = ResvHistoryEntry(self.block.createdByUser, info, emails)
                collResv.getResvHistory().addHistoryEntry(histEntry)
        if sendNotification:
            emailsToBeSent += RoomBlockingNotification.blockingRequestProcessed(self)
        for email in emailsToBeSent:
            GenericMailer.send(GenericNotification(email))
Ejemplo n.º 35
0
    def setAttributes( attsList, *args, **kwargs  ):
        location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )

        for at in attsList:
            errors = CustomAttributesManagerBase.checkAttribute( at )
            if errors: raise str( errors )

        dic = CustomAttributesManager.getRoot()
        dic[location] = attsList
        root = Factory.getDALManager().root
        root[_CUSTOM_ATTRIBUTES_LIST] = dic
Ejemplo n.º 36
0
    def insertAttribute( customAttribute, *args, **kwargs ):
        """ Adds new attribute to the list of custom attributes."""
        location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
        
        errors = []
        errors = CustomAttributesManagerBase.checkAttribute( customAttribute )
        if errors: raise str( errors )

        attsList = CustomAttributesManager.getAttributes( location = location )
        attsList.append( customAttribute )
        CustomAttributesManager.setAttributes( attsList, location = location )
Ejemplo n.º 37
0
 def supportsAttributeManagement( *args, **kwargs ):
     location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     
     # CERN uses generic ZODB-based plugin which DOES allow
     # dynamic room attributes management.
     # However, CERN-specific needs require to turn off this 
     # feature, because rooms are managed centrally, and we
     # just import them.
     #if location == "CERN":
     #    return False
     
     return True
Ejemplo n.º 38
0
    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)
Ejemplo n.º 39
0
    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)
Ejemplo n.º 40
0
    def testReservationSpecificBlockingMethods(self):
        block = self._createTestBlocking()
        candResv = Location.getDefaultLocation().factory.newReservation()
        candResv.startDT = datetime.combine(
            block.startDate - timedelta(days=1), time())
        candResv.endDT = datetime.combine(block.endDate + timedelta(days=1),
                                          time(23, 59))
        candResv.repeatability = RepeatabilityEnum.daily
        candResv.isConfirmed = None

        candResv.room = self._room7
        self.assertTrue(
            candResv.getBlockingConflictState() is None)  # No blocking
        self.assertEqual(candResv.getBlockedDates(), [])
        br = self._blockRoom(block, self._room7, False)
        block.update()
        self.assertEqual(candResv.getBlockingConflictState(),
                         'pending')  # Pending blocking
        self.assertEqual(candResv.getBlockedDates(), [])
        br.approve(sendNotification=False)
        self.assertEqual(candResv.getBlockingConflictState(),
                         'active')  # Active blocking
        blockingDays = frozenset((date(2010, 12, 31), date(2011, 1, 1)))
        self.assertEqual(frozenset(candResv.getBlockedDates()), blockingDays)
        # Test with various users set. This basically tests if all people who are allowed to override can actually override
        self.assertTrue(
            candResv.getBlockingConflictState(self._avatar1) is
            None)  # room owner
        self.assertEqual(candResv.getBlockedDates(self._avatar1), [])
        self.assertTrue(
            candResv.getBlockingConflictState(self._avatar2) is
            None)  # blocking owner
        self.assertEqual(candResv.getBlockedDates(self._avatar2), [])
        self.assertEqual(candResv.getBlockingConflictState(self._avatar3),
                         'active')  # not permitted to override
        self.assertEqual(frozenset(candResv.getBlockedDates(self._avatar3)),
                         blockingDays)
        self.assertTrue(
            candResv.getBlockingConflictState(self._avatar4) is
            None)  # on blocking ACL
        self.assertEqual(candResv.getBlockedDates(self._avatar4), [])
        # Rejecting an existing blocking is not possible via the UI, but we can test it anyway
        br.reject(sendNotification=False)
        self.assertTrue(
            candResv.getBlockingConflictState() is None)  # No blocking
        self.assertEqual(candResv.getBlockedDates(), [])
Ejemplo n.º 41
0
    def start(self, obj):
        super(RoomBooking_Feature, self).start(obj)

        with obj._context('database'):
            # Tell indico to use the current database for roombooking stuff
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            cfg = Configuration.Config.getInstance()
            minfo.setRoomBookingDBConnectionParams(cfg.getDBConnectionParams())

            obj._ph.getById('RoomBooking').setActive(True)

            DALManagerCERN.connect()
            initializeRoomBookingDB("Universe", force=False)
            DALManagerCERN.disconnect()
            # do not use the method for it as it tries to re-create jsvars and fails
            minfo._roomBookingModuleActive = True
            DALManagerCERN.connect()

            # Create dummy rooms in obj._roomN - owners are fake1 and fake2 (r1 has f1, r2 has f2, r3 has f1, ...)
            location = Location.getDefaultLocation()
            obj._rooms = []
            for i in xrange(1, 8):
                room = location.newRoom()
                room.locationName = location.friendlyName
                room.name = 'DummyRoom%d' % i
                room.site = 'a'
                room.building = 1
                room.floor = 'b'
                room.roomNr = 'c'
                room.latitude = ''
                room.longitude = ''
                room.isActive = True
                room.isReservable = True
                room.resvsNeedConfirmation = False
                room.responsibleId = 'fake-%d' % (((i - 1) % 2) + 1)
                room.whereIsKey = 'Nowhere'
                room.telephone = '123456789'
                room.capacity = 10
                room.division = ''
                room.surfaceArea = 50
                room.comments = ''
                room.setEquipment([])
                room.setAvailableVC([])
                room.insert()
                obj._rooms.append(room)
                setattr(obj, '_room%d' % i, room)
Ejemplo n.º 42
0
    def start(self, obj):
        super(RoomBooking_Feature, self).start(obj)

        with obj._context('database'):
            # Tell indico to use the current database for roombooking stuff
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            cfg = Configuration.Config.getInstance()
            minfo.setRoomBookingDBConnectionParams(cfg.getDBConnectionParams())

            obj._ph.getById('RoomBooking').setActive(True)

            DALManagerCERN.connect()
            initializeRoomBookingDB("Universe", force=False)
            DALManagerCERN.disconnect()
            # do not use the method for it as it tries to re-create jsvars and fails
            minfo._roomBookingModuleActive = True
            DALManagerCERN.connect()

            # Create dummy rooms in obj._roomN - owners are fake1 and fake2 (r1 has f1, r2 has f2, r3 has f1, ...)
            location = Location.getDefaultLocation()
            obj._rooms = []
            for i in xrange(1, 8):
                room = location.newRoom()
                room.locationName = location.friendlyName
                room.name = 'DummyRoom%d' % i
                room.site = 'a'
                room.building = 1
                room.floor = 'b'
                room.roomNr = 'c'
                room.latitude = ''
                room.longitude = ''
                room.isActive = True
                room.isReservable = True
                room.resvsNeedConfirmation = False
                room.responsibleId = 'fake-%d' % (((i - 1) % 2) + 1)
                room.whereIsKey = 'Nowhere'
                room.telephone = '123456789'
                room.capacity = 10
                room.division = ''
                room.surfaceArea = 50
                room.comments = ''
                room.setEquipment([])
                room.setAvailableVC([])
                room.insert()
                obj._rooms.append(room)
                setattr(obj, '_room%d' % i, room)
Ejemplo n.º 43
0
 def _createResv(self, room, user, startDate, endDate, pre=False):
     resv = Location.getDefaultLocation().factory.newReservation()
     resv.room = room
     resv.startDT = datetime.combine(startDate, time(8, 30))
     resv.endDT = datetime.combine(endDate, time(17, 30))
     if startDate != endDate:
         resv.repeatability = RepeatabilityEnum.daily
     resv.reason = ''
     resv.needsAVCSupport = False
     resv.usesAVC = False
     resv.createdDT = datetime.now()
     resv.createdBy = str(user.getId())
     resv.bookedForName = user.getFullName()
     resv.contactEmail = user.getEmail()
     resv.contactPhone = user.getTelephone()
     resv.isRejected = False
     resv.isCancelled = False
     resv.isConfirmed = True if not pre else None
     resv.insert()
     return resv
Ejemplo n.º 44
0
 def _createResv(self, room, user, startDate, endDate, pre=False):
     resv = Location.getDefaultLocation().factory.newReservation()
     resv.room = room
     resv.startDT = datetime.combine(startDate, time(8, 30))
     resv.endDT = datetime.combine(endDate, time(17, 30))
     if startDate != endDate:
         resv.repeatability = RepeatabilityEnum.daily
     resv.reason = ''
     resv.needsAVCSupport = False
     resv.usesAVC = False
     resv.createdDT = datetime.now()
     resv.createdBy = str(user.getId())
     resv.bookedForName = user.getFullName()
     resv.contactEmail = user.getEmail()
     resv.contactPhone = user.getTelephone()
     resv.isRejected = False
     resv.isCancelled = False
     resv.isConfirmed = True if not pre else None
     resv.insert()
     return resv
Ejemplo n.º 45
0
    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
Ejemplo n.º 46
0
    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()
Ejemplo n.º 47
0
        'bottomRightLatitude': '46.295676244254715',
        'bottomRightLongitude': '6.115661859512329',
        'zoomLevel': 17,
        'defaultOnStartup': False
    },
    {
        'id': 6,
        'name': 'POINT 8',
        'centerLatitude': 46.24158691675184,
        'centerLongitude': 6.097038745847385,
        'topLeftLatitude': '46.2393607911537',
        'topLeftLongitude': '6.092873811721802',
        'bottomRightLatitude': '46.24381295202931',
        'bottomRightLongitude': '6.101188659667969',
        'zoomLevel': 17,
        'defaultOnStartup': False
    },
]

DBMgr.getInstance().startRequest()
Factory.getDALManager().connect()

location = Location.parse('CERN')

for aspectData in aspects:
    aspect = MapAspect()
    aspect.updateFromDictionary(aspectData)
    location.addAspect(aspect)

DBMgr.getInstance().endRequest()
Ejemplo n.º 48
0
 def _checkParams( self ):
     self._location = Location.parse(self._param("location"))
Ejemplo n.º 49
0
 def _checkParams( self ):
     self._location = Location.parse(self._param("location"))
     self._aspectId = self._param("aspectId")
Ejemplo n.º 50
0
 def getNumberOfRooms( *args, **kwargs ):
     """ Documentation in base class. """
     location = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     return Room.countRooms( location = location )
Ejemplo n.º 51
0
 def _getGuid(self):
     if self.id == None or self.locationName == None:
         return None
     return RoomGUID(Location.parse(self.locationName), self.id)
Ejemplo n.º 52
0
 def getLocationName(self):
     if self.__class__.__name__ == 'RoomBase':
         return Location.getDefaultLocation().friendlyName
         #raise 'This method is purely virtual. Call it only on derived objects.'
     return self.getLocationName()  # Subclass