def compare( self, c1, c2 ): """ """ if c1.getSession() == None and c2.getSession() == None: return 0 elif c1.getSession() == None: return +1 elif c2.getSession() == None: return -1 return cmp(natural_sort_key(c1.getSession().getTitle().lower().strip()), natural_sort_key(c2.getSession().getTitle().lower().strip()))
def _adjust_blockings(self, rooms, filters, availability): if availability is None: return rooms blocked_rooms = get_blockings_with_rooms(filters['start_dt'], filters['end_dt']) nonoverridable_blocked_rooms = filter_blocked_rooms( blocked_rooms, nonoverridable_only=True) if availability: # Remove nonoverridable blockings from available rooms nonoverridable_blocked_rooms_ids = [ room.room_id for room in nonoverridable_blocked_rooms ] rooms = [ room for room in rooms if room[0] not in nonoverridable_blocked_rooms_ids ] else: # Add nonoverridable blockings to unavailable rooms and re-sort results rooms_ids = [room[0] for room in rooms] missing_rooms = [(room.room_id, room.room.full_name) for room in nonoverridable_blocked_rooms if room.room_id not in rooms_ids] if filters.get('favorite'): favorites = { r.id for r in session.user.favorite_rooms if not r.is_deleted } missing_rooms = [(room_id, room_name) for room_id, room_name in missing_rooms if room_id in favorites] rooms = sorted(rooms + missing_rooms, key=lambda room: natural_sort_key(room[1])) return rooms
def get_sorted_rooms(self, location): result = [ {"name": room.full_name, "id": room.id, "venue_id": room.location_id} for room in location.rooms if room.is_active ] return sorted(result, key=lambda x: natural_sort_key(x["name"]))
def _process(self): rooms = sorted(self._location.rooms, key=lambda r: natural_sort_key(r.full_name)) kpi = {} if self._with_kpi: kpi['occupancy'] = calculate_rooms_occupancy(self._location.rooms) kpi['total_rooms'] = len(self._location.rooms) kpi['active_rooms'] = sum(1 for room in self._location.rooms if room.is_active) kpi['reservable_rooms'] = sum(1 for room in self._location.rooms if room.is_reservable) kpi['reservable_capacity'] = sum(room.capacity or 0 for room in self._location.rooms if room.is_reservable) kpi['reservable_surface'] = sum(room.surface_area or 0 for room in self._location.rooms if room.is_reservable) kpi['booking_stats'] = compose_rooms_stats(self._location.rooms) kpi['booking_count'] = Reservation.find( Reservation.room.has(Room.location == self._location)).count() return WPRoomBookingAdminLocation( self, 'rb-rooms', location=self._location, rooms=rooms, action_succeeded=self._actionSucceeded, equipment_types=self._location.equipment_types.all(), attributes=self._location.attributes.all(), kpi=kpi).display()
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 get_sorted_rooms(self, location): result = [{ 'name': room.full_name, 'id': room.id, 'venue_id': room.location_id } for room in location.rooms] return sorted(result, key=lambda x: natural_sort_key(x['name']))
def _process(self): rooms = sorted(self._location.rooms, key=lambda r: natural_sort_key(r.full_name)) kpi = {} if self._with_kpi: kpi['occupancy'] = calculate_rooms_occupancy( self._location.rooms.all()) kpi['total_rooms'] = self._location.rooms.count() kpi['active_rooms'] = self._location.rooms.filter_by( is_active=True).count() kpi['reservable_rooms'] = self._location.rooms.filter_by( is_reservable=True).count() kpi['reservable_capacity'] = (self._location.rooms.with_entities( func.sum( Room.capacity)).filter_by(is_reservable=True).scalar()) kpi['reservable_surface'] = (self._location.rooms.with_entities( func.sum( Room.surface_area)).filter_by(is_reservable=True).scalar()) kpi['booking_stats'] = compose_rooms_stats( self._location.rooms.all()) kpi['booking_count'] = Reservation.find( Reservation.room_id.in_( r.id for r in self._location.rooms)).count() return WPRoomBookingAdminLocation( self, location=self._location, rooms=rooms, action_succeeded=self._actionSucceeded, equipment_types=self._location.equipment_types.all(), attributes=self._location.attributes.all(), kpi=kpi).display()
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 _checkParams(self): try: location = Location.find_one(name=self._params['location']) except NoResultFound: raise ServiceError( 'ERR-RB0', 'Invalid location name: {0}.'.format(self._params['location'])) self._rooms = sorted(location.rooms, key=lambda r: natural_sort_key(r.full_name))
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()
def get_room_calendar(start_date, end_date, room_ids, include_inactive=False, **filters): start_dt = datetime.combine(start_date, time(hour=0, minute=0)) end_dt = datetime.combine(end_date, time(hour=23, minute=59)) query = _bookings_query(dict(filters, start_dt=start_dt, end_dt=end_dt, room_ids=room_ids, include_inactive=include_inactive)) bookings = query.order_by(db.func.indico.natsort(Room.full_name)).all() rooms = set() if room_ids: rooms = set(Room.query .filter(~Room.is_deleted, Room.id.in_(room_ids)) .options(joinedload('location'))) rooms.update(b.reservation.room for b in bookings) rooms = sorted(rooms, key=lambda r: natural_sort_key(r.full_name)) occurrences_by_room = groupby(bookings, attrgetter('reservation.room_id')) unbookable_hours = get_rooms_unbookable_hours(rooms) nonbookable_periods = get_rooms_nonbookable_periods(rooms, start_dt, end_dt) blocked_rooms = get_rooms_blockings(rooms, start_dt, end_dt) nonoverridable_blocked_rooms = group_blocked_rooms(filter_blocked_rooms(blocked_rooms, nonoverridable_only=True, explicit=True)) overridable_blocked_rooms = group_blocked_rooms(filter_blocked_rooms(blocked_rooms, overridable_only=True, explicit=True)) dates = [d.date() for d in iterdays(start_dt, end_dt)] calendar = {room.id: { 'room_id': room.id, 'nonbookable_periods': group_nonbookable_periods(nonbookable_periods.get(room.id, []), dates), 'unbookable_hours': unbookable_hours.get(room.id, []), 'blockings': group_blockings(nonoverridable_blocked_rooms.get(room.id, []), dates), 'overridable_blockings': group_blockings(overridable_blocked_rooms.get(room.id, []), dates), } for room in rooms} for room_id, occurrences in occurrences_by_room: occurrences = list(occurrences) pre_bookings = [occ for occ in occurrences if occ.reservation.is_pending] existing_bookings = [occ for occ in occurrences if not occ.reservation.is_pending and occ.is_valid] concurrent_pre_bookings = get_concurrent_pre_bookings(pre_bookings) additional_data = { 'bookings': group_by_occurrence_date(existing_bookings), 'pre_bookings': group_by_occurrence_date(pre_bookings), 'concurrent_pre_bookings': group_by_occurrence_date(concurrent_pre_bookings) } if include_inactive: additional_data.update({ 'cancellations': group_by_occurrence_date(occ for occ in occurrences if occ.is_cancelled), 'rejections': group_by_occurrence_date(occ for occ in occurrences if occ.is_rejected) }) calendar[room_id].update(additional_data) return calendar
def _load_contribution_data(self): def _format_contrib(contrib): if contrib.getSession() is None: return to_unicode(contrib.getTitle()) else: return _('{contrib} (in session "{session}")').format( session=to_unicode(contrib.getSession().getTitle()), contrib=to_unicode(contrib.getTitle()) ) contribs = sorted([contrib for contrib in self._conf.getContributionList() if contrib.getStartDate()], key=lambda c: natural_sort_key(c.getTitle())) return [(contrib.getId(), escape(_format_contrib(contrib))) for contrib in contribs]
def _load_contribution_data(self): def _format_contrib(contrib): if contrib.session is None: return contrib.title else: return _('{contrib} (in session "{session}")').format( session=contrib.session.title, contrib=contrib.title ) contribs = sorted([contrib for contrib in self.event_new.contributions if contrib.timetable_entry], key=lambda c: natural_sort_key(c.title)) return [(contrib.id, escape(_format_contrib(contrib))) for contrib in contribs]
def _load_contribution_data(self): def _format_contrib(contrib): if contrib.session is None: return contrib.title else: return _('{contrib} (in session "{session}")').format( session=contrib.session.title, contrib=contrib.title ) contribs = sorted((contrib for contrib in self.event.contributions if contrib.timetable_entry), key=lambda c: natural_sort_key(c.title)) return [(contrib.id, escape(_format_contrib(contrib))) for contrib in contribs]
def _main(args): if not args.locations: rooms = Room.getRooms() else: rooms = itertools.chain.from_iterable(Room.getRooms(location=loc, allFast=True) for loc in args.locations) rooms = sorted(rooms, key=lambda x: natural_sort_key(x.getFullName())) print 'Month\tYear\tRoom' for room in rooms: print '{1:.3f}\t{2:.3f}\t{0}'.format(room.getFullName(), room.getMyAverageOccupation('pastmonth') * 100, room.getMyAverageOccupation('pastyear') * 100)
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 _main(args): if not args.locations: rooms = Room.getRooms() else: rooms = itertools.chain.from_iterable( Room.getRooms(location=loc, allFast=True) for loc in args.locations) rooms = sorted(rooms, key=lambda x: natural_sort_key(x.getFullName())) print 'Month\tYear\tRoom' for room in rooms: print '{1:.3f}\t{2:.3f}\t{0}'.format( room.getFullName(), room.getMyAverageOccupation('pastmonth') * 100, room.getMyAverageOccupation('pastyear') * 100)
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()
def _main(location): yesterday = date.today() - relativedelta(days=1) past_month = yesterday - relativedelta(days=29) past_year = yesterday - relativedelta(years=1) query = Room.query if location: query = query.join(Location).filter(Location.name.in_(location)) rooms = sorted( query, key=lambda r: natural_sort_key(r.location_name + r.full_name)) 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 _process(self): tags = sorted(self.event.registration_tags, key=lambda tag: natural_sort_key(tag.title)) choices = [(str(tag.id), (tag.title, tag.color)) for tag in tags] form = RegistrationTagsAssignForm( regform=self.regform, registration_id=[reg.id for reg in self.registrations]) form.add.choices = choices form.remove.choices = choices if form.validate_on_submit(): _assign_registration_tags(self.event, self.registrations, form.add.data, form.remove.data) return jsonify_data() return jsonify_form( form, form_header_kwargs={'classes': 'registration-tags-assign-form'})
def _process(self): rooms = sorted(self._location.rooms, key=lambda r: natural_sort_key(r.full_name)) kpi = {} if self._with_kpi: kpi['occupancy'] = calculate_rooms_occupancy(self._location.rooms) kpi['total_rooms'] = len(self._location.rooms) kpi['active_rooms'] = sum(1 for room in self._location.rooms if room.is_active) kpi['reservable_rooms'] = sum(1 for room in self._location.rooms if room.is_reservable) kpi['reservable_capacity'] = sum(room.capacity or 0 for room in self._location.rooms if room.is_reservable) kpi['reservable_surface'] = sum(room.surface_area or 0 for room in self._location.rooms if room.is_reservable) kpi['booking_stats'] = compose_rooms_stats(self._location.rooms) kpi['booking_count'] = Reservation.find(Reservation.room.has(Room.location == self._location)).count() return WPRoomBookingAdminLocation(self, 'rb-rooms', location=self._location, rooms=rooms, action_succeeded=self._actionSucceeded, equipment_types=self._location.equipment_types.all(), attributes=self._location.attributes.all(), kpi=kpi).display()
def _process(self): rooms = sorted(self._location.rooms, key=lambda r: natural_sort_key(r.full_name)) kpi = {} if self._with_kpi: kpi['occupancy'] = calculate_rooms_occupancy(self._location.rooms.all()) kpi['total_rooms'] = self._location.rooms.count() kpi['active_rooms'] = self._location.rooms.filter_by(is_active=True).count() kpi['reservable_rooms'] = self._location.rooms.filter_by(is_reservable=True).count() kpi['reservable_capacity'] = (self._location.rooms.with_entities(func.sum(Room.capacity)) .filter_by(is_reservable=True).scalar()) kpi['reservable_surface'] = (self._location.rooms.with_entities(func.sum(Room.surface_area)) .filter_by(is_reservable=True).scalar()) kpi['booking_stats'] = compose_rooms_stats(self._location.rooms.all()) kpi['booking_count'] = Reservation.find(Reservation.room_id.in_(r.id for r in self._location.rooms)).count() return WPRoomBookingAdminLocation(self, location=self._location, rooms=rooms, action_succeeded=self._actionSucceeded, equipment_types=self._location.equipment_types.all(), attributes=self._location.attributes.all(), kpi=kpi).display()
def sort_rooms(self, data, many): if many: data = sorted(data, key=lambda x: natural_sort_key(x['room']['full_name'])) return data
def _checkParams(self): self._rooms = sorted(Room.find_all(is_active=True), key=lambda r: natural_sort_key(r.full_name)) self._form_data = self._get_form_data() self._form = BookingSearchForm(self._form_data) self._form.room_ids.choices = [(r.id, None) for r in self._rooms]
def sort_list(self, data, many, **kwargs): if many: data = sorted(data, key=lambda e: natural_sort_key(e['verbose_title'])) return data
def sort_list(self, data, many, **kwargs): if many: data = sorted(data, key=lambda ft: natural_sort_key(ft['name'])) return data
def _checkParams(self): self._rooms = sorted(Room.find_all(is_active=True), key=lambda r: natural_sort_key(r.full_name)) self._form_data = self._get_form_data() self._form = BookingSearchForm(self._form_data, csrf_enabled=False) self._form.room_ids.choices = [(r.id, None) for r in self._rooms]
def sort_func(item): if isinstance(item, basestring): item = item.lower() return natural_sort_key(item)
def sort_rooms(self, location): location['rooms'] = sorted(location['rooms'], key=lambda x: natural_sort_key(x['full_name'])) return location
def find_all(cls, *args, **kwargs): """Retrieves rooms, sorted by location and full name""" rooms = super(Room, cls).find_all(*args, **kwargs) rooms.sort(key=lambda r: natural_sort_key(r.location_name + r.full_name)) return rooms
def get_sorted_rooms(self, location): result = [{'name': room.full_name, 'id': room.id, 'venue_id': room.location_id} for room in location.rooms if room.is_active] return sorted(result, key=lambda x: natural_sort_key(x['name']))
def calculate_monthly_stats(start_dt, end_dt): """Calculate monthly stats for the Burotel system, based on a date range.""" room = aliased(Room) months = list(rrule(freq=MONTHLY, dtstart=start_dt, until=end_dt)) desk_count = (db.session.query(db.func.count(room.id)).filter( Room.building == room.building, Room.division == room.division, room.is_reservable, ~room.is_deleted)).label('desk_count') # a first query which retrieves building data as well as the total number of bookings building_query = _build_per_building_query( Room.building.label('number'), Room.division.label('experiment'), desk_count, db.func.count( db.func.concat( Reservation.id, ReservationOccurrence.start_dt)).label('bookings')).filter( ReservationOccurrence.start_dt >= start_dt, ReservationOccurrence.end_dt <= end_dt).order_by('number') parts = [] for n, month_start in enumerate(months): month_end = (month_start + relativedelta(months=1, days=-1)).replace( hour=23, minute=59) parts.append( _build_per_building_query( Room.building.label('number'), Room.division.label('experiment'), bindparam('month-{}'.format(n), n).label('month'), db.func.count( db.func.concat( Reservation.id, ReservationOccurrence.start_dt)).label( 'bookings')).filter( ReservationOccurrence.start_dt >= month_start, ReservationOccurrence.end_dt <= month_end)) # create a union with all month queries. this will return a (second) query which will provide # separate totals for each month month_query = parts[0].union(*parts[1:]) # rearrange the returned rows in a more processable format bldg_exp_map = [((building, experiment), { 'bookings': bookings, 'desk_count': count, 'months': [0] * len(months) }) for building, experiment, count, bookings in building_query] # convert the previous list in to a nested dict object bldg_map = { k: {bldg_exp[1]: data for bldg_exp, data in v} for k, v in itertools.groupby(bldg_exp_map, lambda w: w[0][0]) } # merge the "month query" into the "building query" for number, experiment, month, bookings in month_query: bldg_map[number][experiment]['months'][month] = bookings # this is a third query which adds in buildings/experiments not matched in the previous ones unmatched_query = (db.session.query( Room.building, Room.division, desk_count).filter(Room.is_reservable, ~Room.is_deleted).group_by(Room.building, Room.division)) # let's add all "unmatched" buildings/experiments with zeroed totals for building, experiment, desk_count in unmatched_query: if not bldg_map.get(building, {}).get(experiment): bldg_map.setdefault(building, {}) bldg_map[building][experiment] = { 'bookings': 0, 'desk_count': desk_count, 'months': [0] * len(months) } # resulted sorted by building/experiment result = [(number, [(experiment, data) for experiment, data in sorted(v.viewitems())]) for number, v in sorted(bldg_map.viewitems(), key=lambda x: natural_sort_key(x[0]))] return result, months
def _process_args(self): self._rooms = sorted(Room.find_all(is_active=True), key=lambda r: natural_sort_key(r.full_name)) self._form_data = self._get_form_data() self._form = BookingSearchForm(self._form_data, csrf_enabled=False) self._form.room_ids.choices = [(r.id, None) for r in self._rooms]
def _checkParams(self): try: location = Location.find_one(name=self._params['location']) except NoResultFound: raise ServiceError('ERR-RB0', 'Invalid location name: {0}.'.format(self._params['location'])) self._rooms = sorted(location.rooms, key=lambda r: natural_sort_key(r.full_name))
def sort_list(self, data, many, **kwargs): if many: data = sorted(data, key=lambda tag: natural_sort_key(tag['title'])) return data
def sort_rooms(self, data, many, **kwargs): if many: data = sorted(data, key=lambda x: natural_sort_key(x['room']['full_name'])) return data
def sort_tags(self, data, **kwargs): data['tags'].sort( key=lambda tag: natural_sort_key(tag['verbose_title'])) return data
def sort_rooms(self, location): location['rooms'] = sorted( location['rooms'], key=lambda x: natural_sort_key(x['full_name'])) return location
def _order_func(object_list): return sorted(object_list, key=lambda r: natural_sort_key(r[1].full_name))
def _get_registration_tag_choices(self): tags = sorted(self.event.registration_tags, key=lambda tag: natural_sort_key(tag.title)) return {str(tag.id): tag.title for tag in tags}