Exemplo n.º 1
0
def test_find_with_filters(create_room, create_blocking):
    rooms = [create_room(), create_room()]
    blockings = [
        create_blocking(start_date=date.today(),
                        end_date=date.today(),
                        room=rooms[0],
                        state=BlockedRoom.State.accepted),
        create_blocking(start_date=date.today() + timedelta(days=1),
                        end_date=date.today() + timedelta(days=1),
                        room=rooms[1]),
        create_blocking(start_date=date.today() + timedelta(days=1),
                        end_date=date.today() + timedelta(days=1),
                        room=rooms[1]),
    ]
    assert set(BlockedRoom.find_with_filters({})) == set(b.blocked_rooms[0]
                                                         for b in blockings)
    filters = {
        'start_date': date.today(),
        'end_date': date.today(),
        'room_ids': {rooms[0].id},
        'state': BlockedRoom.State.accepted
    }
    assert set(BlockedRoom.find_with_filters(filters)) == {
        blockings[0].blocked_rooms[0]
    }
Exemplo n.º 2
0
    def migrate_blockings(self):
        state_map = {
            None: BlockedRoom.State.pending,
            False: BlockedRoom.State.rejected,
            True: BlockedRoom.State.accepted
        }

        print cformat('%{white!}migrating blockings')
        for old_blocking_id, old_blocking in self.rb_root['RoomBlocking'][
                'Blockings'].iteritems():
            b = Blocking(id=old_blocking.id,
                         created_by_id=self.merged_avatars.get(
                             old_blocking._createdBy, old_blocking._createdBy),
                         created_dt=as_utc(old_blocking._utcCreatedDT),
                         start_date=old_blocking.startDate,
                         end_date=old_blocking.endDate,
                         reason=convert_to_unicode(old_blocking.message))

            print cformat(u'- %{cyan}{}').format(b.reason)
            for old_blocked_room in old_blocking.blockedRooms:
                br = BlockedRoom(
                    state=state_map[old_blocked_room.active],
                    rejected_by=old_blocked_room.rejectedBy,
                    rejection_reason=convert_to_unicode(
                        old_blocked_room.rejectionReason),
                )
                room = Room.get(get_room_id(old_blocked_room.roomGUID))
                room.blocked_rooms.append(br)
                b.blocked_rooms.append(br)
                print cformat(u'  %{blue!}Room:%{reset} {} ({})').format(
                    room.full_name,
                    BlockedRoom.State(br.state).title)

            for old_principal in old_blocking.allowed:
                principal_id = old_principal._id
                if old_principal._type == 'Avatar':
                    principal_id = int(
                        self.merged_avatars.get(old_principal._id,
                                                old_principal._id))
                    principal_type = 'User'
                else:
                    principal_type = 'Group'
                bp = BlockingPrincipal(
                    _principal=[principal_type, principal_id])
                b._allowed.add(bp)
                print cformat(u'  %{blue!}Allowed:%{reset} {}({})').format(
                    bp.entity_type, bp.entity_id)
            db.session.add(b)
        db.session.commit()
Exemplo n.º 3
0
 def _create_blocking(**params):
     room = params.pop('room', dummy_room)
     state = params.pop('state', BlockedRoom.State.pending)
     params.setdefault('start_date', date.today())
     params.setdefault('end_date', date.today())
     params.setdefault('reason', u'Blocked')
     params.setdefault('created_by_user', dummy_avatar.user)
     blocking = Blocking(**params)
     if room is not None:
         br = BlockedRoom(room=room, state=state, blocking=blocking)
         if state == BlockedRoom.State.accepted:
             br.approve(notify_blocker=False)
     db.session.add(blocking)
     db.session.flush()
     return blocking
Exemplo n.º 4
0
 def _create_blocking(**params):
     room = params.pop('room', dummy_room)
     state = params.pop('state', BlockedRoom.State.pending)
     params.setdefault('start_date', date.today())
     params.setdefault('end_date', date.today())
     params.setdefault('reason', u'Blocked')
     params.setdefault('created_by_user', dummy_user)
     blocking = Blocking(**params)
     if room is not None:
         br = BlockedRoom(room=room, state=state, blocking=blocking)
         if state == BlockedRoom.State.accepted:
             br.approve(notify_blocker=False)
     db.session.add(blocking)
     db.session.flush()
     return blocking
Exemplo n.º 5
0
    def validate_blocked_rooms(self, field):
        try:
            field.data = map(int, field.data)
        except Exception as e:
            # In case someone sent crappy data
            raise ValidationError(str(e))

        # Make sure all room ids are valid
        if len(field.data) != Room.find(Room.id.in_(field.data)).count():
            raise ValidationError('Invalid rooms')

        if hasattr(self, '_blocking'):
            start_date = self._blocking.start_date
            end_date = self._blocking.end_date
            blocking_id = self._blocking.id
        else:
            start_date = self.start_date.data
            end_date = self.end_date.data
            blocking_id = None

        overlap = BlockedRoom.find_first(
            BlockedRoom.room_id.in_(field.data),
            BlockedRoom.state != BlockedRoom.State.rejected,
            Blocking.start_date <= end_date,
            Blocking.end_date >= start_date,
            Blocking.id != blocking_id,
            _join=Blocking
        )
        if overlap:
            msg = 'Your blocking for {} is overlapping with another blocking.'.format(overlap.room.full_name)
            raise ValidationError(msg)
Exemplo n.º 6
0
    def __init__(self, occurrences, start_dt, end_dt, candidates=None, rooms=None, specific_room=None,
                 repeat_frequency=None, repeat_interval=None, flexible_days=0, show_blockings=True):
        self.occurrences = occurrences
        self.start_dt = start_dt
        self.end_dt = end_dt
        self.candidates = candidates
        self.rooms = rooms
        self.specific_room = specific_room
        self.repeat_frequency = repeat_frequency
        self.repeat_interval = repeat_interval
        self.flexible_days = flexible_days
        self.show_blockings = show_blockings

        self.conflicts = 0
        self.bars = []

        if self.specific_room and self.rooms:
            raise ValueError('specific_room and rooms are mutually exclusive')

        if self.specific_room:
            self.rooms = [self.specific_room]
        elif self.rooms is None:
            self.rooms = Room.find_all(is_active=True)
        self.rooms = sorted(self.rooms, key=lambda x: natural_sort_key(x.full_name))

        if self.show_blockings:
            self.blocked_rooms = BlockedRoom.find_with_filters({'room_ids': [r.id for r in self.rooms],
                                                                'state': BlockedRoom.State.accepted,
                                                                'start_date': self.start_dt.date(),
                                                                'end_date': self.end_dt.date()})
        else:
            self.blocked_rooms = []

        self._produce_bars()
Exemplo n.º 7
0
 def _save(self):
     blocking = self._blocking
     blocking.reason = self._form.reason.data
     # Just overwrite the whole list
     blocking.allowed = [
         BlockingPrincipal(entity_type=item['_type'], entity_id=item['id'])
         for item in self._form.principals.data
     ]
     # Blocked rooms need some more work as we can't just overwrite them
     old_blocked = {br.room_id for br in blocking.blocked_rooms}
     new_blocked = set(self._form.blocked_rooms.data)
     added_blocks = new_blocked - old_blocked
     removed_blocks = old_blocked - new_blocked
     for room_id in removed_blocks:
         blocked_room = next(br for br in blocking.blocked_rooms
                             if br.room_id == room_id)
         blocking.blocked_rooms.remove(blocked_room)
     added_blocked_rooms = []
     for room_id in added_blocks:
         blocked_room = BlockedRoom(room_id=room_id)
         blocking.blocked_rooms.append(blocked_room)
         added_blocked_rooms.append(blocked_room)
     db.session.flush()
     flash(_(u'Blocking updated'), 'success')
     self._process_blocked_rooms(added_blocked_rooms)
Exemplo n.º 8
0
def _populate_blocking(blocking, room_ids, allowed_principals, reason):
    blocking.blocked_rooms = [BlockedRoom(room_id=room.id) for room in Room.query.filter(Room.id.in_(room_ids))]
    blocking.reason = reason
    blocking.allowed = [GroupProxy(_group_id_or_name(pr), provider=pr['provider'])
                        if pr.get('is_group')
                        else User.get_one(pr['id'])
                        for pr in allowed_principals]
Exemplo n.º 9
0
    def validate_blocked_rooms(self, field):
        try:
            field.data = map(int, field.data)
        except Exception as e:
            # In case someone sent crappy data
            raise ValidationError(str(e))

        # Make sure all room ids are valid
        if len(field.data) != Room.find(Room.id.in_(field.data)).count():
            raise ValidationError('Invalid rooms')

        if hasattr(self, '_blocking'):
            start_date = self._blocking.start_date
            end_date = self._blocking.end_date
            blocking_id = self._blocking.id
        else:
            start_date = self.start_date.data
            end_date = self.end_date.data
            blocking_id = None

        overlap = BlockedRoom.find_first(
            BlockedRoom.room_id.in_(field.data),
            BlockedRoom.state != BlockedRoom.State.rejected,
            Blocking.start_date <= end_date,
            Blocking.end_date >= start_date,
            Blocking.id != blocking_id,
            _join=Blocking)
        if overlap:
            msg = 'Your blocking for {} is overlapping with another blocking.'.format(
                overlap.room.full_name)
            raise ValidationError(msg)
Exemplo n.º 10
0
    def __init__(self,
                 occurrences,
                 start_dt,
                 end_dt,
                 candidates=None,
                 rooms=None,
                 specific_room=None,
                 repeat_frequency=None,
                 repeat_interval=None,
                 flexible_days=0,
                 show_blockings=True):
        self.occurrences = occurrences
        self.start_dt = start_dt
        self.end_dt = end_dt
        self.candidates = candidates
        self.rooms = rooms
        self.specific_room = specific_room
        self.repeat_frequency = repeat_frequency
        self.repeat_interval = repeat_interval
        self.flexible_days = flexible_days
        self.show_blockings = show_blockings

        self.conflicts = 0
        self.bars = []

        if self.specific_room and self.rooms:
            raise ValueError('specific_room and rooms are mutually exclusive')

        if self.specific_room:
            self.rooms = [self.specific_room]
        elif self.rooms is None:
            self.rooms = Room.find_all(is_active=True)
        self.rooms = sorted(self.rooms,
                            key=lambda x: natural_sort_key(x.full_name))

        if self.show_blockings:
            # avoid loading user data we don't care about
            user_strategy = defaultload('blocking').defaultload(
                'created_by_user')
            user_strategy.noload('*')
            user_strategy.load_only('first_name', 'last_name')
            room_ids = [r.id for r in self.rooms]
            filters = {
                'room_ids': room_ids,
                'state': BlockedRoom.State.accepted,
                'start_date': self.start_dt.date(),
                'end_date': self.end_dt.date()
            }
            self.blocked_rooms = BlockedRoom.find_with_filters(
                filters).options(user_strategy)
            self.nonbookable_periods = NonBookablePeriod.find(
                NonBookablePeriod.room_id.in_(room_ids),
                NonBookablePeriod.overlaps(self.start_dt, self.end_dt)).all()
        else:
            self.blocked_rooms = []

        self._produce_bars()
Exemplo n.º 11
0
def test_find_with_filters_dates(create_blocking, start_date, end_date, matches):
    start_date = datetime.strptime(start_date, "%Y-%m-%d").date()
    end_date = datetime.strptime(end_date, "%Y-%m-%d").date()
    blockings = [
        create_blocking(start_date=date(2014, 12, 5), end_date=date(2014, 12, 7)),
        create_blocking(start_date=date(2014, 12, 6), end_date=date(2014, 12, 8)),
    ]
    filters = {"start_date": start_date, "end_date": end_date}
    assert set(BlockedRoom.find_with_filters(filters)) == set(blockings[i].blocked_rooms[0] for i in matches)
Exemplo n.º 12
0
def test_find_with_filters_dates(create_blocking, start_date, end_date, matches):
    start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
    end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
    blockings = [
        create_blocking(start_date=date(2014, 12, 5), end_date=date(2014, 12, 7)),
        create_blocking(start_date=date(2014, 12, 6), end_date=date(2014, 12, 8))
    ]
    filters = {'start_date': start_date,
               'end_date': end_date}
    assert set(BlockedRoom.find_with_filters(filters)) == set(blockings[i].blocked_rooms[0] for i in matches)
Exemplo n.º 13
0
def test_find_with_filters(create_room, create_blocking):
    rooms = [create_room(), create_room()]
    blockings = [
        create_blocking(start_date=date.today(),
                        end_date=date.today(),
                        room=rooms[0],
                        state=BlockedRoom.State.accepted),
        create_blocking(start_date=date.today() + timedelta(days=1),
                        end_date=date.today() + timedelta(days=1),
                        room=rooms[1]),
        create_blocking(start_date=date.today() + timedelta(days=1),
                        end_date=date.today() + timedelta(days=1),
                        room=rooms[1]),
    ]
    assert set(BlockedRoom.find_with_filters({})) == set(b.blocked_rooms[0] for b in blockings)
    filters = {'start_date': date.today(),
               'end_date': date.today(),
               'room_ids': {rooms[0].id},
               'state': BlockedRoom.State.accepted}
    assert set(BlockedRoom.find_with_filters(filters)) == {blockings[0].blocked_rooms[0]}
Exemplo n.º 14
0
def create_blocking(rooms, start_date, end_date, reason, allowed_principals):
    blocking = Blocking()
    blocking.start_date = start_date
    blocking.end_date = end_date
    blocking.reason = reason
    blocking.created_by_user = session.user
    blocking.allowed = allowed_principals
    blocking.blocked_rooms = [BlockedRoom(room_id=room.id) for room in rooms]
    db.session.add(blocking)
    db.session.flush()
    return blocking
Exemplo n.º 15
0
 def _save(self):
     self._blocking = blocking = Blocking()
     blocking.start_date = self._form.start_date.data
     blocking.end_date = self._form.end_date.data
     blocking.created_by_user = session.user
     blocking.reason = self._form.reason.data
     blocking.allowed = self._form.principals.data
     blocking.blocked_rooms = [BlockedRoom(room_id=room_id) for room_id in self._form.blocked_rooms.data]
     db.session.add(blocking)
     db.session.flush()  # synchronizes relationships (e.g. BlockedRoom.room)
     flash(_(u'Blocking created'), 'success')
     self._process_blocked_rooms(blocking.blocked_rooms)
Exemplo n.º 16
0
    def __init__(self,
                 occurrences,
                 start_dt,
                 end_dt,
                 candidates=None,
                 rooms=None,
                 specific_room=None,
                 repeat_frequency=None,
                 repeat_interval=None,
                 flexible_days=0,
                 show_blockings=True):
        self.occurrences = occurrences
        self.start_dt = start_dt
        self.end_dt = end_dt
        self.candidates = candidates
        self.rooms = rooms
        self.specific_room = specific_room
        self.repeat_frequency = repeat_frequency
        self.repeat_interval = repeat_interval
        self.flexible_days = flexible_days
        self.show_blockings = show_blockings

        self.conflicts = 0
        self.bars = []

        if self.specific_room and self.rooms:
            raise ValueError('specific_room and rooms are mutually exclusive')

        if self.specific_room:
            self.rooms = [self.specific_room]
        elif self.rooms is None:
            self.rooms = Room.find_all(is_active=True)
        self.rooms = sorted(self.rooms,
                            key=lambda x: natural_sort_key(x.full_name))

        if self.show_blockings:
            self.blocked_rooms = BlockedRoom.find_with_filters({
                'room_ids': [r.id for r in self.rooms],
                'state':
                BlockedRoom.State.accepted,
                'start_date':
                self.start_dt.date(),
                'end_date':
                self.end_dt.date()
            })
        else:
            self.blocked_rooms = []

        self._produce_bars()
def _update_blocked_rooms(blocking, room_ids):
    old_blocked = {br.room_id for br in blocking.blocked_rooms}
    new_blocked = set(room_ids)
    added_blocks = new_blocked - old_blocked
    removed_blocks = old_blocked - new_blocked
    blocked_rooms_by_room = {br.room_id: br for br in blocking.blocked_rooms}
    for room_id in removed_blocks:
        blocking.blocked_rooms.remove(blocked_rooms_by_room[room_id])
    added_blocked_rooms = set()
    rooms = {r.id: r for r in Room.query.filter(~Room.is_deleted, Room.id.in_(added_blocks))}
    for room_id in added_blocks:
        blocked_room = BlockedRoom(room=rooms[room_id])
        blocking.blocked_rooms.append(blocked_room)
        added_blocked_rooms.add(blocked_room)
    db.session.flush()
    _approve_or_request_rooms(blocking, added_blocked_rooms)
Exemplo n.º 18
0
    def __init__(self, occurrences, start_dt, end_dt, candidates=None, rooms=None, specific_room=None,
                 repeat_frequency=None, repeat_interval=None, flexible_days=0, show_blockings=True):
        self.occurrences = occurrences
        self.start_dt = start_dt
        self.end_dt = end_dt
        self.candidates = candidates
        self.rooms = rooms
        self.specific_room = specific_room
        self.repeat_frequency = repeat_frequency
        self.repeat_interval = repeat_interval
        self.flexible_days = flexible_days
        self.show_blockings = show_blockings

        self.conflicts = 0
        self.bars = []

        if self.specific_room and self.rooms:
            raise ValueError('specific_room and rooms are mutually exclusive')

        if self.specific_room:
            self.rooms = [self.specific_room]
        elif self.rooms is None:
            self.rooms = Room.find_all(is_active=True)
        self.rooms = sorted(self.rooms, key=lambda x: natural_sort_key(x.full_name))

        if self.show_blockings:
            # avoid loading user data we don't care about
            user_strategy = defaultload('blocking').defaultload('created_by_user')
            user_strategy.noload('*')
            user_strategy.load_only('first_name', 'last_name')
            room_ids = [r.id for r in self.rooms]
            filters = {
                'room_ids': room_ids,
                'state': BlockedRoom.State.accepted,
                'start_date': self.start_dt.date(),
                'end_date': self.end_dt.date()
            }
            self.blocked_rooms = BlockedRoom.find_with_filters(filters).options(user_strategy)
            self.nonbookable_periods = NonBookablePeriod.find(
                NonBookablePeriod.room_id.in_(room_ids),
                NonBookablePeriod.overlaps(self.start_dt, self.end_dt)
            ).all()
        else:
            self.blocked_rooms = []

        self._produce_bars()
Exemplo n.º 19
0
 def _save(self):
     blocking = self._blocking
     blocking.reason = self._form.reason.data
     # Update the ACL. We don't use `=` here to prevent SQLAlchemy
     # from deleting and re-adding unchanged entries.
     blocking.allowed |= self._form.principals.data
     blocking.allowed &= self._form.principals.data
     # Add/remove blocked rooms if necessary
     old_blocked = {br.room_id for br in blocking.blocked_rooms}
     new_blocked = set(self._form.blocked_rooms.data)
     added_blocks = new_blocked - old_blocked
     removed_blocks = old_blocked - new_blocked
     for room_id in removed_blocks:
         blocked_room = next(br for br in blocking.blocked_rooms if br.room_id == room_id)
         blocking.blocked_rooms.remove(blocked_room)
     added_blocked_rooms = []
     for room_id in added_blocks:
         blocked_room = BlockedRoom(room_id=room_id)
         blocking.blocked_rooms.append(blocked_room)
         added_blocked_rooms.append(blocked_room)
     db.session.flush()
     flash(_(u'Blocking updated'), 'success')
     self._process_blocked_rooms(added_blocked_rooms)
Exemplo n.º 20
0
 def _process_args(self):
     self.blocked_room = BlockedRoom.get(self._params['blocked_room_id'])
Exemplo n.º 21
0
 def _checkParams(self):
     self.blocked_room = BlockedRoom.get(self._params['blocked_room_id'])
Exemplo n.º 22
0
def test_find_with_filters_state(create_blocking, state):
    other_state = next(s for s in BlockedRoom.State if s != state)
    create_blocking(state=other_state)
    blocking = create_blocking(state=state)
    assert set(BlockedRoom.find_with_filters({"state": state})) == {blocking.blocked_rooms[0]}
Exemplo n.º 23
0
 def _checkParams(self):
     self.blocked_room = BlockedRoom.get(self._params['blocked_room_id'])
Exemplo n.º 24
0
def test_find_with_filters_state(create_blocking, state):
    other_state = next(s for s in BlockedRoom.State if s != state)
    create_blocking(state=other_state)
    blocking = create_blocking(state=state)
    assert set(BlockedRoom.find_with_filters(
        {'state': state})) == {blocking.blocked_rooms[0]}
Exemplo n.º 25
0
def test_state_name(state):
    assert BlockedRoom(state=state).state_name == state.title