예제 #1
0
파일: backend.py 프로젝트: jazzi/indico
    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)
예제 #2
0
    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)
예제 #3
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]
예제 #4
0
파일: bookings.py 프로젝트: pferreir/indico
    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)
예제 #5
0
    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())
예제 #6
0
    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())
예제 #7
0
    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)
예제 #8
0
파일: legacy.py 프로젝트: wtakase/indico
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
예제 #9
0
    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})
예제 #10
0
파일: legacy.py 프로젝트: pilgrim2go/indico
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
예제 #11
0
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)
예제 #12
0
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()
예제 #13
0
파일: event.py 프로젝트: javfg/indico
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')
예제 #14
0
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')
예제 #15
0
파일: bookings.py 프로젝트: pferreir/indico
    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())
예제 #16
0
 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))
예제 #17
0
파일: fields.py 프로젝트: florv/indico
 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))
예제 #18
0
    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())
예제 #19
0
파일: fields.py 프로젝트: uxmaster/indico
def _get_users(ids):
    if not ids:
        return set()
    return set(User.find(User.id.in_(ids), ~User.is_deleted))
예제 #20
0
파일: fields.py 프로젝트: OmeGak/indico
def _get_users(ids):
    if not ids:
        return set()
    return set(User.find(User.id.in_(ids), ~User.is_deleted))
예제 #21
0
파일: admin.py 프로젝트: l1kw1d/indico
 def _deserialize(self, value, attr, data, **kwargs):
     return User.get(value, is_deleted=False)