def _process(self): form = self._form if self._is_submitted() and form.validate(): if form.data.get('is_only_my_rooms'): form.room_ids.data = [ room.id for room in Room.find_all() if room.is_owned_by(session.user) ] occurrences = ReservationOccurrence.find_with_filters( form.data, session.user).all() rooms = self._filter_displayed_rooms( [r for r in self._rooms if r.id in set(form.room_ids.data)], occurrences) return WPRoomBookingSearchBookingsResults( self, rooms=rooms, occurrences=occurrences, show_blockings=self.show_blockings, start_dt=form.start_dt.data, end_dt=form.end_dt.data, form=form, form_data=self._form_data, menu_item=self.menu_item).display() my_rooms = [r.id for r in Room.get_owned_by(session.user)] return WPRoomBookingSearchBookings(self, errors=form.error_list, rooms=self._rooms, my_rooms=my_rooms, form=form).display()
def test_find_with_filters(db, dummy_room, create_room, dummy_user, create_equipment_type, create_room_attribute, dummy_reservation): # Simple testcase that ensures we find the room when many filters are used other_room = create_room() assert set(Room.find_with_filters({}, dummy_user)) == {dummy_room, other_room} create_room_attribute(u'attr') eq = create_equipment_type(u'eq') dummy_room.capacity = 100 dummy_room.is_reservable = True dummy_room.available_equipment.append(eq) dummy_room.set_attribute_value(u'attr', u'meowmeow') db.session.flush() filters = { 'available_equipment': {eq}, 'capacity': 90, 'only_public': True, 'is_only_my_rooms': True, 'details': u'meow', 'available': 0, 'repeatability': 'None', 'start_dt': dummy_reservation.start_dt, 'end_dt': dummy_reservation.end_dt } assert set(Room.find_with_filters(filters, dummy_user)) == {dummy_room}
def test_find_with_filters_only_my_rooms(dummy_room, create_user, owner_id, match): user = create_user(owner_id, legacy=True) if match: assert set(Room.find_with_filters({'is_only_my_rooms': True}, user)) == {dummy_room} else: assert not Room.find_with_filters({'is_only_my_rooms': True}, user)
def test_find_with_filters_details_cols(db, dummy_room, create_room, col): create_room() # some room we won't find! assert set(Room.find_with_filters({}, None)) == set(Room.find_all()) assert not Room.find_with_filters({'details': u'meow'}, None) setattr(dummy_room, col, u'meow') db.session.flush() assert set(Room.find_with_filters({'details': u'meow'}, None)) == {dummy_room}
def test_find_with_filters_availability_error(): with pytest.raises(ValueError): filters = { 'available': 123, 'repeatability': 'None', 'start_dt': datetime.now(), 'end_dt': datetime.now() } Room.find_with_filters(filters, None)
def test_find_with_filters_only_public(dummy_room, create_room_attribute, is_reservable, booking_group, match): create_room_attribute(u'allowed-booking-group') dummy_room.is_reservable = is_reservable dummy_room.set_attribute_value(u'allowed-booking-group', booking_group) if match: assert set(Room.find_with_filters({'is_only_public': True}, None)) == {dummy_room} else: assert not Room.find_with_filters({'is_only_public': True}, None)
def test_find_with_filters_details_values(db, dummy_room, create_room, value, search_value, other_value): other_room = create_room() assert set(Room.find_with_filters({}, None)) == set(Room.find_all()) assert not Room.find_with_filters({'details': search_value}, None) dummy_room.comments = value other_room.comments = other_value db.session.flush() assert set(Room.find_with_filters({'details': search_value}, None)) == {dummy_room}
def _merge_users(target, source, **kwargs): BlockingPrincipal.merge_users(target, source, 'blocking') Blocking.find(created_by_id=source.id).update( {Blocking.created_by_id: target.id}) Reservation.find(created_by_id=source.id).update( {Reservation.created_by_id: target.id}) Reservation.find(booked_for_id=source.id).update( {Reservation.booked_for_id: target.id}) Room.find(owner_id=source.id).update({Room.owner_id: target.id}) rb_settings.acls.merge_users(target, source)
def test_find_with_attribute(dummy_room, create_room, create_room_attribute): assert Room.find_all() == [dummy_room] # one room without the attribute assert not Room.find_with_attribute(u'foo') create_room_attribute(u'foo') assert not Room.find_with_attribute(u'foo') expected = set() for room in [create_room(), create_room()]: value = u'bar-{}'.format(room.id) room.set_attribute_value(u'foo', value) expected.add((room, value)) assert set(Room.find_with_attribute(u'foo')) == expected
def test_find_with_filters_details_attrs(dummy_room, create_room, create_room_attribute, value, search_value, other_value): other_room = create_room() assert set(Room.find_with_filters({}, None)) == set(Room.find_all()) assert not Room.find_with_filters({'details': search_value}, None) create_room_attribute(u'foo') assert not Room.find_with_filters({'details': search_value}, None) dummy_room.set_attribute_value(u'foo', value) other_room.set_attribute_value(u'foo', other_value) assert set(Room.find_with_filters({'details': search_value}, None)) == {dummy_room}
def _create_room(**params): params.setdefault('building', u'1') params.setdefault('floor', u'2') params.setdefault('number', u'3') params.setdefault('name', '') params.setdefault('owner', dummy_user) params.setdefault('location', dummy_location) room = Room(**params) room.update_name() db.session.add(room) db.session.flush() return room
def test_ownership_functions(dummy_room, create_user, create_room_attribute, create_group, is_owner, has_group, in_group, expected): other_user = create_user(123) create_room_attribute(u'manager-group') if is_owner: dummy_room.owner = other_user if has_group: dummy_room.set_attribute_value(u'manager-group', u'123') if in_group: other_user.local_groups.add(create_group(123).group) assert dummy_room.is_owned_by(other_user) == expected assert Room.user_owns_rooms(other_user) == expected assert set( Room.get_owned_by(other_user)) == ({dummy_room} if expected else set())
def test_find_with_filters_capacity(db, dummy_room, create_room, capacity, other_capacity, search_capacity, match, match_other): other_room = create_room() assert set(Room.find_with_filters({}, None)) == set(Room.find_all()) dummy_room.capacity = capacity other_room.capacity = other_capacity db.session.flush() expected = set() if match: expected.add(dummy_room) if match_other: expected.add(other_room) assert set(Room.find_with_filters({'capacity': search_capacity}, None)) == expected
def _main(location): yesterday = date.today() - relativedelta(days=1) past_month = yesterday - relativedelta(days=29) past_year = yesterday - relativedelta(years=1) if not location: rooms = Room.find_all() else: rooms = Room.find_all(Location.name.in_(location), _join=Location) print 'Month\tYear\tPublic?\tRoom' for room in rooms: print '{2:.2f}%\t{3:.2f}%\t{1}\t{0}'.format( room.full_name, "Y" if room.is_public else "N", calculate_rooms_occupancy([room], past_month, yesterday) * 100, calculate_rooms_occupancy([room], past_year, yesterday) * 100)
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)
def _make_select_room_form(self): # Step 1 self._rooms = sorted(Room.find_all(is_active=True), key=lambda r: natural_sort_key(r.full_name)) form_obj, self.date_changed = self._get_select_room_form_defaults() form = NewBookingCriteriaForm(obj=form_obj) form.room_ids.choices = [(r.id, None) for r in self._rooms] return form
def _getAnswer(self): if not config.ENABLE_ROOMBOOKING: return {} criteria = {'_eager': Room.location} if self._isActive is not None: criteria['is_active'] = self._isActive rooms = Room.find_all(**criteria) return {room.id: '{}: {}'.format(room.location_name, room.full_name) for room in rooms}
def _process(self): state = BlockedRoom.State.get(self.state) my_blocks = defaultdict(list) for room in Room.get_owned_by(session.user): roomBlocks = room.blocked_rooms.filter(True if state is None else BlockedRoom.state == state).all() if roomBlocks: my_blocks[room] += roomBlocks return WPRoomBookingBlockingsForMyRooms(self, room_blocks=my_blocks).display()
def test_get_with_data(db, create_room, create_equipment_type, only_active, data): eq = create_equipment_type(u'eq') vc = create_equipment_type(u'Video conference') vc1 = create_equipment_type(u'vc1') vc2 = create_equipment_type(u'vc2') vc.children.append(vc1) vc.children.append(vc2) rooms = { 'inactive': { 'room': create_room(is_active=False), 'equipment': set(), 'vc_equipment': set(), 'non_vc_equipment': set() }, 'no_eq': { 'room': create_room(), 'equipment': set(), 'vc_equipment': set(), 'non_vc_equipment': set() }, 'non_vc_eq': { 'room': create_room(), 'equipment': {eq}, 'vc_equipment': set(), 'non_vc_equipment': {eq} }, 'vc_eq': { 'room': create_room(), 'equipment': {vc, vc1, vc2}, 'vc_equipment': {vc1, vc2}, 'non_vc_equipment': {vc} }, 'all_eq': { 'room': create_room(), 'equipment': {eq, vc, vc1, vc2}, 'vc_equipment': {vc1, vc2}, 'non_vc_equipment': {vc, eq} } } room_types = { room_data['room']: type_ for type_, room_data in rooms.iteritems() } for room in rooms.itervalues(): room['room'].available_equipment = room['equipment'] db.session.flush() results = list(Room.get_with_data(*data, only_active=only_active)) assert len(results) == len(rooms) - only_active for row in results: room = row.pop('room') assert set(row.viewkeys()) == set(data) room_type = room_types[room] if room_type == 'inactive': assert not only_active for key in data: assert set(row[key]) == {x.name for x in rooms[room_type][key]}
def _process_confirm(self): # The form needs the room to create the equipment list, so we need to get it "manually"... room = Room.get(int(request.form['room_id'])) form = self._make_confirm_form(room) if not room.can_be_booked(session.user) and not room.can_be_prebooked( session.user): raise Forbidden('You cannot book this room') if form.validate_on_submit(): return self._create_booking_response(form, room) # There was an error in the form return self._show_confirm(room, form)
def _process_args(self): blocking_id = self._params.get('blocking_id') self._room = Room.get(self._params['room_id']) self._blocking = Blocking.get(blocking_id) if blocking_id else None if 'start_dt' in self._params and 'end_dt' in self._params: start_dt = datetime.strptime(self._params['start_dt'], '%H:%M %Y-%m-%d') end_dt = datetime.strptime(self._params['end_dt'], '%H:%M %Y-%m-%d') self._nonbookable = bool(NonBookablePeriod.find_first(NonBookablePeriod.room_id == self._room.id, NonBookablePeriod.overlaps(start_dt, end_dt))) else: self._nonbookable = False
def _sidemenu_sections(sender, **kwargs): user_has_rooms = session.user is not None and Room.user_owns_rooms( session.user) yield SideMenuSection('search', _("Search"), 40, icon='search', active=True) if user_has_rooms: yield SideMenuSection('my_rooms', _("My Rooms"), 30, icon='user') yield SideMenuSection('blocking', _("Room Blocking"), 20, icon='lock')
def _process(self): room = self._room rooms = Room.find_all() form = self._make_form() if form.is_submitted() and not form.validate(): occurrences = {} candidates = {} conflicts = {} pre_conflicts = {} only_conflicts = False else: occurrences, candidates = self._get_all_occurrences( [self._room.id], form) conflicts, pre_conflicts = self._get_all_conflicts( self._room, form) candidate_days = { occ.date for candidate in candidates.itervalues() for occ in candidate } conflicting_days = {occ.date for occ in conflicts.iterkeys()} only_conflicts = candidate_days <= conflicting_days if form.validate_on_submit() and not form.submit_check.data: booking_limit_days = room.booking_limit_days or rb_settings.get( 'booking_limit') if not self._validate_room_booking_limit(form, booking_limit_days): msg = (_( u'Bookings for the room "{}" may not be longer than {} days' ).format(room.name, booking_limit_days)) return jsonify(success=False, url=url_for('rooms.room_book', room), msg=msg) return self._create_booking_response(form, room) can_override = room.can_be_overridden(session.user) return self._get_view(form=form, room=room, rooms=rooms, occurrences=occurrences, candidates=candidates, conflicts=conflicts, only_conflicts=only_conflicts, pre_conflicts=pre_conflicts, start_dt=form.start_dt.data, end_dt=form.end_dt.data, repeat_frequency=form.repeat_frequency.data, repeat_interval=form.repeat_interval.data, can_override=can_override, past_date=not form.is_submitted() and self.past_date, date_changed=not form.is_submitted() and self.date_changed).display()
def test_filter_available(dummy_room, create_reservation, create_blocking, has_booking, has_blocking, has_pre_booking, include_pre_bookings, has_pending_blocking, include_pending_blockings, filtered): if has_booking: create_reservation(start_dt=datetime.combine(date.today(), time(8)), end_dt=datetime.combine(date.today(), time(10))) if has_pre_booking: create_reservation(start_dt=datetime.combine(date.today(), time(10)), end_dt=datetime.combine(date.today(), time(12)), is_accepted=False) if has_blocking: create_blocking(state=BlockedRoom.State.accepted) if has_pending_blocking: create_blocking(state=BlockedRoom.State.pending) availabilty_filter = Room.filter_available( get_day_start(date.today()), get_day_end(date.today()), (RepeatFrequency.NEVER, 0), include_pre_bookings=include_pre_bookings, include_pending_blockings=include_pending_blockings) assert set(Room.find_all(availabilty_filter)) == (set() if filtered else {dummy_room})
def _process_select_room(self): # Step 1: Room(s), dates, repetition selection form = self._make_select_room_form() if form.validate_on_submit(): flexible_days = form.flexible_dates_range.data day_start_dt = datetime.combine(form.start_dt.data.date(), time()) day_end_dt = datetime.combine(form.end_dt.data.date(), time(23, 59)) selected_rooms = [ r for r in self._rooms if r.id in form.room_ids.data ] selected_period_days = (day_end_dt - day_start_dt).days for room in selected_rooms: booking_limit_days = room.booking_limit_days or rb_settings.get( 'booking_limit') if selected_period_days > booking_limit_days: flash( _(u'Bookings for the room "{}" may not be longer than {} days' ).format(room.name, booking_limit_days), 'error') return redirect(url_for('rooms.book')) occurrences, candidates = self._get_all_occurrences( form.room_ids.data, form, flexible_days) period_form_defaults = FormDefaults( repeat_interval=form.repeat_interval.data, repeat_frequency=form.repeat_frequency.data) period_form = self._make_select_period_form(period_form_defaults) # Show step 2 page return self._get_view('select_period', rooms=selected_rooms, occurrences=occurrences, candidates=candidates, start_dt=day_start_dt, end_dt=day_end_dt, period_form=period_form, form=form, repeat_frequency=form.repeat_frequency.data, repeat_interval=form.repeat_interval.data, flexible_days=flexible_days).display() # GET or form errors => show step 1 page return self._get_view( 'select_room', errors=form.error_list, rooms=self._rooms, form=form, my_rooms=[r.id for r in Room.get_owned_by(session.user)], max_room_capacity=Room.max_capacity, can_override=rb_is_admin(session.user), date_changed=not form.is_submitted() and self.date_changed, ).display()
def _process_args(self): RHRoomBookingBookingMixin._process_args(self) # use 'room' if passed through GET room_id = request.args.get('room', None) if room_id is None: # otherwise default to reservation's self._room = self._reservation.room else: self._room = Room.get(int(room_id)) if self._room is None: raise NotFound(u'This room does not exist')
def test_find_with_filters_availability(dummy_room, dummy_reservation, available): if available: start_dt = dummy_reservation.end_dt + timedelta(days=1) end_dt = start_dt + timedelta(days=1) else: start_dt = dummy_reservation.start_dt end_dt = dummy_reservation.end_dt filters = { 'available': int(available), 'repeatability': 'None', 'start_dt': start_dt, 'end_dt': end_dt } assert set(Room.find_with_filters(filters, None)) == {dummy_room}
def _process_select_period(self): form = self._make_select_period_form() if form.is_submitted(): # Errors in here are only caused by users messing with the submitted data so it's not # worth making the code more complex to show the errors nicely on the originating page. # Doing so would be very hard anyway as we don't keep all data necessary to show step 2 # when it's not a step 1 form submission. if not form.validate(): raise fossirError(u'<br>'.join(form.error_list)) room = Room.get(form.room_id.data) if not room: raise fossirError(u'Invalid room') # Show step 3 page confirm_form_defaults = FormDefaults(form.data) return self._show_confirm(room, form, self._step, confirm_form_defaults)
def export_roomName(self, user): loc = Location.find_first(name=self._location) if loc is None: return search_str = '%{}%'.format(self._room_name) rooms_data = Room.get_with_data( 'vc_equipment', 'non_vc_equipment', filters=[ Room.location_id == loc.id, or_((Room.building + '-' + Room.floor + '-' + Room.number).ilike(search_str), Room.name.ilike(search_str)) ]) for result in rooms_data: yield _serializable_room(result)
def test_find_with_filters_equipment(db, dummy_room, create_room, create_equipment_type): other_room = create_room() assert set(Room.find_with_filters({}, None)) == set(Room.find_all()) eq1 = create_equipment_type(u'eq1') eq2 = create_equipment_type(u'eq2') assert not Room.find_with_filters({'available_equipment': {eq1}}, None) dummy_room.available_equipment.append(eq1) db.session.flush() assert set(Room.find_with_filters({'available_equipment': {eq1}}, None)) == {dummy_room} assert not Room.find_with_filters({'available_equipment': {eq1, eq2}}, None) dummy_room.available_equipment.append(eq2) other_room.available_equipment.append(eq2) db.session.flush() assert set(Room.find_with_filters({'available_equipment': {eq1}}, None)) == {dummy_room} assert set(Room.find_with_filters({'available_equipment': {eq2}}, None)) == {dummy_room, other_room} assert set( Room.find_with_filters({'available_equipment': {eq1, eq2}}, None)) == {dummy_room}