def _process(self, args): room = Room.get_one(args.pop('room_id')) user_id = args.pop('user_id', None) booked_for = User.get_one(user_id) if user_id else session.user is_prebooking = args.pop('is_prebooking') # Check that the booking is not longer than allowed booking_limit_days = room.booking_limit_days or rb_settings.get( 'booking_limit') if not self._validate_room_booking_limit( args['start_dt'], args['end_dt'], booking_limit_days): msg = ( _('Bookings for the room "{}" may not be longer than {} days' ).format(room.name, booking_limit_days)) return jsonify(success=False, msg=msg) try: Reservation.create_from_data(room, dict(args, booked_for_user=booked_for), session.user, prebook=is_prebooking) db.session.flush() except NoReportError as e: db.session.rollback() return jsonify(success=False, msg=unicode(e)) return jsonify(success=True, is_prebooking=is_prebooking)
def _process(self): args = self.args user_id = args.pop('user_id', None) booked_for = User.get_one(user_id, is_deleted=False) if user_id else session.user # Check that the booking is not longer than allowed booking_limit_days = self.room.booking_limit_days or rb_settings.get('booking_limit') if not self._validate_room_booking_limit(args['start_dt'], args['end_dt'], booking_limit_days): msg = (_('Bookings for the room "{}" may not be longer than {} days') .format(self.room.name, booking_limit_days)) raise ExpectedError(msg) try: resv = Reservation.create_from_data(self.room, dict(args, booked_for_user=booked_for), session.user, prebook=self.prebook) if args.get('link_type') is not None and args.get('link_id') is not None: self._link_booking(resv, args['link_type'], args['link_id'], args['link_back']) db.session.flush() except NoReportError as e: db.session.rollback() raise ExpectedError(unicode(e)) serialized_occurrences = serialize_occurrences(group_by_occurrence_date(resv.occurrences.all())) if self.prebook: data = {'pre_bookings': serialized_occurrences} else: data = {'bookings': serialized_occurrences} return jsonify(room_id=self.room.id, booking=reservation_details_schema.dump(resv).data, calendar_data=data)
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]
def _process(self, args): room = Room.get_one(args.pop('room_id')) user_id = args.pop('user_id', None) booked_for = User.get_one(user_id) if user_id else session.user is_prebooking = args.pop('is_prebooking') # Check that the booking is not longer than allowed booking_limit_days = room.booking_limit_days or rb_settings.get('booking_limit') if not self._validate_room_booking_limit(args['start_dt'], args['end_dt'], booking_limit_days): msg = (_('Bookings for the room "{}" may not be longer than {} days') .format(room.name, booking_limit_days)) raise ExpectedError(msg) try: resv = Reservation.create_from_data(room, dict(args, booked_for_user=booked_for), session.user, prebook=is_prebooking) db.session.flush() except NoReportError as e: db.session.rollback() raise ExpectedError(unicode(e)) serialized_occurrences = serialize_occurrences(group_by_occurrence_date(resv.occurrences.all())) if is_prebooking: data = {'pre_bookings': serialized_occurrences} else: data = {'bookings': serialized_occurrences} return jsonify(room_id=room.id, booking=reservation_details_schema.dump(resv).data, calendar_data=data)
def _process(self, args): new_booking_data = { 'booking_reason': args['booking_reason'], 'room_usage': 'current_user' if args.get('user_id', None) is None else 'someone', 'booked_for_user': User.get(args.get('user_id', session.user.id)), 'start_dt': args['start_dt'], 'end_dt': args['end_dt'], 'repeat_frequency': args['repeat_frequency'], 'repeat_interval': args['repeat_interval'], } additional_booking_attrs = {} if not should_split_booking(self.booking, new_booking_data): has_date_changed = not has_same_dates(self.booking, new_booking_data) room = self.booking.room self.booking.modify(new_booking_data, session.user) if (has_date_changed and not room.can_book(session.user, allow_admin=False) and room.can_prebook(session.user, allow_admin=False) and self.booking.is_accepted): self.booking.reset_approval(session.user) else: new_booking = split_booking(self.booking, new_booking_data) additional_booking_attrs['new_booking_id'] = new_booking.id db.session.flush() today = date.today() calendar = get_room_calendar(args['start_dt'] or today, args['end_dt'] or today, [args['room_id']]) return jsonify( booking=dict(_serialize_booking_details(self.booking), **additional_booking_attrs), room_calendar=_serialize_availability(calendar).values())
def _process(self, args): data = { 'booking_reason': args['booking_reason'], 'room_usage': 'current_user' if args.get('user_id', None) is None else 'someone', 'booked_for_user': User.get(args.get('user_id', session.user.id)), 'start_dt': args['start_dt'], 'end_dt': args['end_dt'], 'repeat_frequency': args['repeat_frequency'], 'repeat_interval': args['repeat_interval'], } has_date_changed = not has_same_dates(self.booking, data) self.booking.modify(data, session.user) room = self.booking.room if (has_date_changed and not room.can_book(session.user, allow_admin=False) and room.can_prebook(session.user, allow_admin=False) and self.booking.is_accepted): self.booking.reset_approval(session.user) db.session.flush() start_date = args['start_dt'] end_date = args['end_dt'] calendar = get_room_calendar(start_date or date.today(), end_date or date.today(), [args['room_id']]) return jsonify( booking=_serialize_booking_details(self.booking), room_calendar=_serialize_availability(calendar).values())
def _process(self, args): room = Room.get_one(args.pop('room_id')) user_id = args.pop('user_id', None) booked_for = User.get_one(user_id) if user_id else session.user is_prebooking = args.pop('is_prebooking') # Check that the booking is not longer than allowed booking_limit_days = room.booking_limit_days or rb_settings.get('booking_limit') if not self._validate_room_booking_limit(args['start_dt'], args['end_dt'], booking_limit_days): msg = (_('Bookings for the room "{}" may not be longer than {} days') .format(room.name, booking_limit_days)) raise ExpectedError(msg) try: resv = Reservation.create_from_data(room, dict(args, booked_for_user=booked_for), session.user, prebook=is_prebooking) db.session.flush() except NoReportError as e: db.session.rollback() raise ExpectedError(unicode(e)) serialized_occurrences = serialize_occurrences(group_by_occurrence_date(resv.occurrences.all())) if is_prebooking: data = {'pre_bookings': serialized_occurrences} else: data = {'bookings': serialized_occurrences} return jsonify(room_id=room.id, **data)
def person_from_data(person_data, event): user = User.find_first(~User.is_deleted, User.all_emails.contains(person_data['email'].lower())) if user: return EventPerson.for_user(user, event) person = EventPerson.find_first(event_new=event, email=person_data['email'].lower()) if not person: person = EventPerson(event_new=event, **person_data) return person
def _process(self): is_invited = request.args.get('invited') == '1' abstract_form_class = make_abstract_form(self.event, session.user, notification_option=True, management=self.management, invited=is_invited) cloned_fields = self.clone_fields( self.abstract) if self.abstract else {} form = abstract_form_class(event=self.event, management=self.management, invited=is_invited, **cloned_fields) if is_invited: del form.submitted_contrib_type del form.attachments del form.send_notifications del form.person_links if form.validate_on_submit(): data = form.data submitter = None if is_invited: if form.users_with_no_account.data == 'existing': submitter = data['submitter'] else: submitter = User(first_name=data['first_name'], last_name=data['last_name'], email=data['email'], is_pending=True) db.session.add(submitter) db.session.flush() data.pop('first_name') data.pop('last_name') data.pop('email') data.pop('users_with_no_account') data.pop('submitter') send_notifications = data.pop('send_notifications', is_invited) abstract = create_abstract(self.event, *get_field_values(data), send_notifications=send_notifications, submitter=submitter, is_invited=is_invited) flash( _("Abstract '{}' created successfully").format(abstract.title), 'success') tpl_components = self.list_generator.render_list(abstract) if tpl_components.get('hide_abstract'): self.list_generator.flash_info_message(abstract) return jsonify_data(**tpl_components) return jsonify_form( form, back=_('Cancel'), disabled_until_change=(not self.abstract or is_invited), form_header_kwargs={'action': request.relative_url})
def _populate_blocking(blocking, room_ids, allowed_principals, reason): blocking.reason = reason principals = { 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 } # We don't use `=` here to prevent SQLAlchemy from deleting and re-adding unchanged entries blocking.allowed |= principals # add new blocking.allowed &= principals # remove deleted _update_blocked_rooms(blocking, room_ids)
def populate_db(): """Populate DB with fun stuff""" # set tileserver URL rb_settings.set( 'tileserver_url', 'https://indico-maps.web.cern.ch/styles/cern/{z}/{x}/{y}.png') location = Location(name="CERN") owner = User.get(0) for area in MAP_AREAS: map_area = MapArea(name=area[0], top_left_latitude=area[1], top_left_longitude=area[2], bottom_right_latitude=area[3], bottom_right_longitude=area[4]) db.session.add(map_area) for name in shower_names: # split name in parts building, floor, number = ROOM_RE.match(name).groups() # random number of showers, since we don't have time # to figure out what it really is num_showers = random.choice([2, 3, 4]) file_name = './photos/{}.png'.format(name.replace('/', '_')) photo_data = None # Check if there's a photo in './photos/xxxx' and use it if os.path.exists(file_name): with open(file_name, 'r') as f: photo_data = f.read() else: print cformat("%{yellow}!%{reset} Photo for {} not found!").format( name) for num_shower in range(num_showers): room = Room(building=building, floor=floor, number=number, verbose_name="Shower {}".format(num_shower + 1), location=location, division='CERN', owner=owner, capacity=1) if photo_data: room.photo = Photo(data=photo_data) if building in GEO_INFO: room.latitude, room.longitude = GEO_INFO[building] db.session.add(room) db.session.commit()
def restore(event_id, user_id, message): """Restore a deleted event.""" event = Event.get(event_id) user = User.get(user_id) if user_id else None if event is None: click.secho('This event does not exist', fg='red') sys.exit(1) elif not event.is_deleted: click.secho('This event is not deleted', fg='yellow') sys.exit(1) event.restore(message, user) signals.core.after_process.send() db.session.commit() click.secho(f'Event undeleted: "{event.title}"', fg='green')
def restore(event_id, user_id, message): """Restore a deleted event.""" event = Event.get(event_id) user = User.get(user_id) if user_id else None if event is None: click.secho('This event does not exist', fg='red') sys.exit(1) elif not event.is_deleted: click.secho('This event is not deleted', fg='yellow') sys.exit(1) event.is_deleted = False text = f'Event restored: {message}' if message else 'Event restored' event.log(EventLogRealm.event, EventLogKind.positive, 'Event', text, user=user) db.session.commit() click.secho(f'Event undeleted: "{event.title}"', fg='green')
def _process(self, args): data = { 'booking_reason': args['booking_reason'], 'room_usage': 'current_user' if args.get('user_id', None) is None else 'someone', 'booked_for_user': User.get(args.get('user_id', session.user.id)), 'start_dt': args['start_dt'], 'end_dt': args['end_dt'], 'repeat_frequency': args['repeat_frequency'], 'repeat_interval': args['repeat_interval'], } self.booking.modify(data, session.user) db.session.flush() start_date = args['start_dt'] end_date = args['end_dt'] calendar = get_room_calendar(start_date or date.today(), end_date or date.today(), [args['room_id']]) return jsonify(booking=_serialize_booking_details(self.booking), room_calendar=_serialize_availability(calendar).values())
def _get_event_person(self, data): person_type = data.get('_type') if person_type is None: if data.get('email'): email = data['email'].lower() user = User.find_first(~User.is_deleted, User.all_emails.contains(email)) if user: return self._get_event_person_for_user(user) elif self.event: person = self.event.persons.filter_by(email=email).first() if person: return person # We have no way to identify an existing event person with the provided information return self._create_event_person(data) elif person_type == 'Avatar': return self._get_event_person_for_user(self._convert_principal(data)) elif person_type == 'EventPerson': return self.event.persons.filter_by(id=data['id']).one() elif person_type == 'PersonLink': return self.event.persons.filter_by(id=data['personId']).one() else: raise ValueError(_("Unknown person type '{}'").format(person_type))
def _get_event_person(self, data): person_type = data.get('_type') if person_type is None: if data.get('email'): email = data['email'].lower() user = User.find_first(~User.is_deleted, User.all_emails.contains(email)) if user: return self._get_event_person_for_user(user) else: person = self.event.persons.filter_by(email=email).first() if person: return person # We have no way to identify an existing event person with the provided information return self._create_event_person(data) elif person_type == 'Avatar': return self._get_event_person_for_user(self._convert_principal(data)) elif person_type == 'EventPerson': return self.event.persons.filter_by(id=data['id']).one() elif person_type == 'PersonLink': return self.event.persons.filter_by(id=data['personId']).one() else: raise ValueError(_("Unknown person type '{}'").format(person_type))
def _process(self, args): data = { 'booking_reason': args['booking_reason'], 'room_usage': 'current_user' if args.get('user_id', None) is None else 'someone', 'booked_for_user': User.get(args.get('user_id', session.user.id)), 'start_dt': args['start_dt'], 'end_dt': args['end_dt'], 'repeat_frequency': args['repeat_frequency'], 'repeat_interval': args['repeat_interval'], } self.booking.modify(data, session.user) db.session.flush() start_date = args['start_dt'] end_date = args['end_dt'] calendar = get_room_calendar(start_date or date.today(), end_date or date.today(), [args['room_id']]) return jsonify( booking=_serialize_booking_details(self.booking), room_calendar=_serialize_availability(calendar).values())
def _get_users(ids): if not ids: return set() return set(User.find(User.id.in_(ids), ~User.is_deleted))
def _deserialize(self, value, attr, data, **kwargs): return User.get(value, is_deleted=False)