Пример #1
0
    def testGetVerboseEquipment(self):
        e1 = RoomEquipment(name='eq1')
        e2 = RoomEquipment(name='eq2')

        room = Room.get(5)
        room.equipments.extend([e1, e2])
        db.session.add(room)
        db.session.commit()

        assert ','.join(['eq1', 'eq2']) == Room.get(5).getVerboseEquipment()
Пример #2
0
    def _getParams(self):
        super(BookRoomHook, self)._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        if not self._fromDT or not self._toDT or self._fromDT.date() != self._toDT.date():
            raise HTTPAPIError('from/to must be on the same day')
        elif self._fromDT >= self._toDT:
            raise HTTPAPIError('to must be after from')
        elif self._fromDT < datetime.now():
            raise HTTPAPIError('You cannot make bookings in the past')

        username = get_query_parameter(self._queryParams, 'username')
        if not username:
            raise HTTPAPIError('No username provided')
        users = User.query.join(User.identities).filter(~User.is_deleted, Identity.identifier == username).all()
        if not users:
            raise HTTPAPIError('Username does not exist')
        elif len(users) != 1:
            raise HTTPAPIError('Ambiguous username ({} users found)'.format(len(users)))
        user = users[0]

        self._params = {
            'room_id': get_query_parameter(self._queryParams, 'roomid'),
            'reason': get_query_parameter(self._queryParams, 'reason'),
            'booked_for': user,
            'from': self._fromDT,
            'to': self._toDT
        }
        missing = [key for key, val in self._params.iteritems() if not val]
        if missing:
            raise HTTPAPIError('Required params missing: {}'.format(', '.join(missing)))
        self._room = Room.get(self._params['room_id'])
        if not self._room:
            raise HTTPAPIError('A room with this ID does not exist')
Пример #3
0
    def _getParams(self):
        super(BookRoomHook, self)._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        if not self._fromDT or not self._toDT or self._fromDT.date() != self._toDT.date():
            raise HTTPAPIError('from/to must be on the same day')
        elif self._fromDT >= self._toDT:
            raise HTTPAPIError('to must be after from')
        elif self._fromDT < datetime.now():
            raise HTTPAPIError('You cannot make bookings in the past')

        username = get_query_parameter(self._queryParams, 'username')
        avatars = username and filter(None, AuthenticatorMgr().getAvatarByLogin(username).itervalues())
        if not avatars:
            raise HTTPAPIError('Username does not exist')
        elif len(avatars) != 1:
            raise HTTPAPIError('Ambiguous username ({} users found)'.format(len(avatars)))
        avatar = avatars[0]

        self._params = {
            'room_id': get_query_parameter(self._queryParams, 'roomid'),
            'reason': get_query_parameter(self._queryParams, 'reason'),
            'booked_for': avatar,
            'from': self._fromDT,
            'to': self._toDT
        }
        missing = [key for key, val in self._params.iteritems() if not val]
        if missing:
            raise HTTPAPIError('Required params missing: {}'.format(', '.join(missing)))
        self._room = Room.get(self._params['room_id'])
        if not self._room:
            raise HTTPAPIError('A room with this ID does not exist')
Пример #4
0
 def _process_args(self):
     self._room = Room.get(request.view_args['roomID'])
     self._occupancy_period = request.args.get('period', 'pastmonth')
     self._end = date.today()
     if self._occupancy_period == 'pastmonth':
         self._end = self._end - relativedelta(days=1)
         self._start = self._end - relativedelta(days=29)
     elif self._occupancy_period == 'thisyear':
         self._start = date(self._end.year, 1, 1)
     elif self._occupancy_period == 'sinceever':
         oldest = db.session.query(func.min(Reservation.start_dt)).filter_by(room_id=self._room.id).scalar()
         self._start = oldest.date() if oldest else self._end
     else:
         match = re.match(r'(\d{4})(?:-(\d{2}))?', self._occupancy_period)
         if match is None:
             raise IndicoError(u'Invalid period specified')
         year = int(match.group(1))
         month = int(match.group(2)) if match.group(2) else None
         if month:
             try:
                 self._start = date(year, month, 1)
             except ValueError:
                 raise IndicoError(u'Invalid year or month specified')
             self._end = self._start + relativedelta(months=1)
             self._occupancy_period = '{:d}-{:02d}'.format(year, month)
         else:
             try:
                 self._start = date(year, 1, 1)
             except ValueError:
                 raise IndicoError(u'Invalid year specified')
             self._end = self._start + relativedelta(years=1)
             self._occupancy_period = str(year)
Пример #5
0
 def process_formdata(self, valuelist):
     super(IndicoLocationField, self).process_formdata(valuelist)
     self.data['room'] = Room.get(int(self.data['room_id'])) if self.data.get('room_id') else None
     self.data['venue'] = (Location.get(int(self.data['venue_id']), is_deleted=False)
                           if self.data.get('venue_id')
                           else None)
     self.data['source'] = self.object_data.get('source') if self.object_data else None
Пример #6
0
 def _process_args(self):
     self._room = Room.get(request.view_args['roomID'])
     self._occupancy_period = request.args.get('period', 'pastmonth')
     self._end = date.today()
     if self._occupancy_period == 'pastmonth':
         self._end = self._end - relativedelta(days=1)
         self._start = self._end - relativedelta(days=29)
     elif self._occupancy_period == 'thisyear':
         self._start = date(self._end.year, 1, 1)
     elif self._occupancy_period == 'sinceever':
         oldest = db.session.query(func.min(
             Reservation.start_dt)).filter_by(
                 room_id=self._room.id).scalar()
         self._start = oldest.date() if oldest else self._end
     else:
         match = re.match(r'(\d{4})(?:-(\d{2}))?', self._occupancy_period)
         if match is None:
             raise IndicoError(u'Invalid period specified')
         year = int(match.group(1))
         month = int(match.group(2)) if match.group(2) else None
         if month:
             try:
                 self._start = date(year, month, 1)
             except ValueError:
                 raise IndicoError(u'Invalid year or month specified')
             self._end = self._start + relativedelta(months=1)
             self._occupancy_period = '{:d}-{:02d}'.format(year, month)
         else:
             try:
                 self._start = date(year, 1, 1)
             except ValueError:
                 raise IndicoError(u'Invalid year specified')
             self._end = self._start + relativedelta(years=1)
             self._occupancy_period = str(year)
Пример #7
0
    def _getParams(self):
        super(BookRoomHook, self)._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        if not self._fromDT or not self._toDT or self._fromDT.date() != self._toDT.date():
            raise HTTPAPIError('from/to must be on the same day')
        elif self._fromDT >= self._toDT:
            raise HTTPAPIError('to must be after from')
        elif self._fromDT < datetime.now():
            raise HTTPAPIError('You cannot make bookings in the past')

        username = get_query_parameter(self._queryParams, 'username')
        if not username:
            raise HTTPAPIError('No username provided')
        users = User.find_all(~User.is_deleted, Identity.identifier == username)
        if not users:
            raise HTTPAPIError('Username does not exist')
        elif len(users) != 1:
            raise HTTPAPIError('Ambiguous username ({} users found)'.format(len(users)))
        user = users[0]

        self._params = {
            'room_id': get_query_parameter(self._queryParams, 'roomid'),
            'reason': get_query_parameter(self._queryParams, 'reason'),
            'booked_for': user,
            'from': self._fromDT,
            'to': self._toDT
        }
        missing = [key for key, val in self._params.iteritems() if not val]
        if missing:
            raise HTTPAPIError('Required params missing: {}'.format(', '.join(missing)))
        self._room = Room.get(self._params['room_id'])
        if not self._room:
            raise HTTPAPIError('A room with this ID does not exist')
Пример #8
0
 def process_formdata(self, valuelist):
     from indico.modules.rb.models.locations import Location
     from indico.modules.rb.models.rooms import Room
     super().process_formdata(valuelist)
     self.data['room'] = Room.get(int(self.data['room_id'])) if self.data.get('room_id') else None
     self.data['venue'] = (Location.get(int(self.data['venue_id']), is_deleted=False)
                           if self.data.get('venue_id')
                           else None)
     self.data['source'] = self.object_data.get('source') if self.object_data else None
Пример #9
0
 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 IndicoError('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)
Пример #10
0
 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 IndicoError('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)
Пример #11
0
def get_room_blockings_conflicts(room_id, candidates, occurrences):
    conflicts = []
    for candidate in candidates:
        for occurrence in occurrences:
            blocking = occurrence.blocking
            if blocking.start_date <= candidate.start_dt.date() <= blocking.end_date:
                if blocking.can_be_overridden(session.user, room=Room.get(room_id)):
                    continue
                obj = TempReservationOccurrence(candidate.start_dt, candidate.end_dt, None)
                conflicts.append(obj)
    return conflicts
Пример #12
0
 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
Пример #13
0
def get_room_blockings_conflicts(room_id, candidates, occurrences):
    conflicts = []
    for candidate in candidates:
        for occurrence in occurrences:
            blocking = occurrence.blocking
            if blocking.start_date <= candidate.start_dt.date() <= blocking.end_date:
                if blocking.can_be_overridden(session.user, room=Room.get(room_id)):
                    continue
                obj = TempReservationOccurrence(candidate.start_dt, candidate.end_dt, None)
                conflicts.append(obj)
    return conflicts
Пример #14
0
 def _checkParams(self):
     self._room = Room.get(request.view_args["roomID"])
     self._occupancy_period = request.args.get("period", "pastmonth")
     self._end = date.today()
     if self._occupancy_period == "pastmonth":
         self._start = self._end - relativedelta(months=1)
     elif self._occupancy_period == "thisyear":
         self._start = date(self._end.year, 1, 1)
     elif self._occupancy_period == "sinceever":
         self._start = Reservation.query.with_entities(func.min(Reservation.start_dt)).one()[0].date()
     else:
         raise IndicoError("Invalid period specified")
Пример #15
0
 def _checkParams(self):
     self._room = Room.get(request.view_args['roomID'])
     self._occupancy_period = request.args.get('period', 'pastmonth')
     self._end = date.today()
     if self._occupancy_period == 'pastmonth':
         self._start = self._end - relativedelta(months=1)
     elif self._occupancy_period == 'thisyear':
         self._start = date(self._end.year, 1, 1)
     elif self._occupancy_period == 'sinceever':
         self._start = Reservation.query.with_entities(func.min(Reservation.start_dt)).one()[0].date()
     else:
         raise IndicoError('Invalid period specified')
Пример #16
0
def get_room_blockings_conflicts(room_id, candidates, occurrences, allow_admin):
    conflicts = set()
    conflicting_candidates = set()
    for candidate in candidates:
        for occurrence in occurrences:
            blocking = occurrence.blocking
            if blocking.start_date <= candidate.start_dt.date() <= blocking.end_date:
                if blocking.can_override(session.user, room=Room.get(room_id), allow_admin=allow_admin):
                    continue
                conflicting_candidates.add(candidate)
                obj = TempReservationOccurrence(candidate.start_dt, candidate.end_dt, None)
                conflicts.add(obj)
    return conflicts, conflicting_candidates
Пример #17
0
 def _checkParams(self):
     self._room = Room.get(request.view_args['roomID'])
     self._occupancy_period = request.args.get('period', 'pastmonth')
     self._end = date.today()
     if self._occupancy_period == 'pastmonth':
         self._start = self._end - relativedelta(months=1)
     elif self._occupancy_period == 'thisyear':
         self._start = date(self._end.year, 1, 1)
     elif self._occupancy_period == 'sinceever':
         self._start = Reservation.query.with_entities(
             func.min(Reservation.start_dt)).one()[0].date()
     else:
         raise IndicoError('Invalid period specified')
Пример #18
0
    def _checkParams(self):
        RHRoomBookingBookingMixin._checkParams(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 NotFoundError('This room does not exist')
Пример #19
0
    def _checkParams(self):
        RHRoomBookingBookingMixin._checkParams(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 NotFoundError('This room does not exist')
Пример #20
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()
Пример #21
0
 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
Пример #22
0
 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 IndicoError('<br>'.join(form.error_list))
         room = Room.get(form.room_id.data)
         if not room:
             raise IndicoError('Invalid room')
         # Show step 3 page
         confirm_form_defaults = FormDefaults(form.data)
         return self._show_confirm(room, form, self._step, confirm_form_defaults)
Пример #23
0
 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 IndicoError(u'<br>'.join(form.error_list))
         room = Room.get(form.room_id.data)
         if not room:
             raise IndicoError(u'Invalid room')
         # Show step 3 page
         confirm_form_defaults = FormDefaults(form.data)
         return self._show_confirm(room, form, self._step, confirm_form_defaults)
Пример #24
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()
def migrate_blockings(rb_root, avatar_id_map):
    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 rb_root['RoomBlocking']['Blockings'].iteritems():
        b = Blocking(
            id=old_blocking.id,
            created_by_id=avatar_id_map.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 = avatar_id_map.get(old_principal._id, old_principal._id)
            bp = BlockingPrincipal(
                entity_type=old_principal._type,
                entity_id=principal_id
            )
            b.allowed.append(bp)
            print cformat(u'  %{blue!}Allowed:%{reset} {}({})').format(bp.entity_type, bp.entity_id)
        db.session.add(b)
    db.session.commit()
Пример #26
0
def updatePluginSettingsNewRB(dbi, prevVersion):
    """Migrate plugin settings to be compatible with the new RB module"""
    ph = PluginsHolder()
    # Custom attributes are now loercase-with-dashes internally
    opt = ph.getPluginType('Collaboration').getPlugin('CERNMCU').getOption('H323_IP_att_name')
    if opt.getValue() == 'H323 IP':
        opt.setValue('h323-ip')
    # Replace room GUIDs with plain room IDs
    for plugin_name, rooms_opt in [('WebcastRequest', 'webcastCapableRooms'),
                                   ('RecordingRequest', 'recordingCapableRooms')]:
        opt = ph.getPluginType('Collaboration').getPlugin(plugin_name).getOption(rooms_opt)
        room_ids = []
        for room_id in opt.getValue():
            if isinstance(room_id, basestring):
                room_id = int(room_id.split('|')[1].strip())
            if Room.get(room_id):
                room_ids.append(room_id)
        opt.setValue(room_ids)

    dbi.commit()
Пример #27
0
 def process_formdata(self, valuelist):
     super(IndicoLocationField, self).process_formdata(valuelist)
     self.data['room'] = Room.get(int(self.data['room_id'])) if self.data.get('room_id') else None
     self.data['venue'] = Location.get(int(self.data['venue_id'])) if self.data.get('venue_id') else None
Пример #28
0
 def _process_args(self):
     self._room = Room.get(int(request.view_args['roomID']))
     if self._room is None:
         raise NotFound(u'This room does not exist')
Пример #29
0
 def _checkParams(self):
     self._room = Room.get(int(request.view_args['roomID']))
     if self._room is None:
         raise NotFoundError('This room does not exist')
Пример #30
0
 def process_formdata(self, valuelist):
     super(IndicoLocationField, self).process_formdata(valuelist)
     self.data['room'] = Room.get(int(
         self.data['room_id'])) if self.data.get('room_id') else None
     self.data['venue'] = Location.get(int(
         self.data['venue_id'])) if self.data.get('venue_id') else None
Пример #31
0
def get_room(room_id):
    room = Room.get(room_id)
    if not room:
        print(cformat("%{yellow}! Desk with ID {} not found.").format(room_id))
    return room
Пример #32
0
 def _checkParams(self):
     self._room = Room.get(request.view_args['roomID'])
     self._target = self._room
Пример #33
0
 def _checkParams(self):
     self._room = Room.get(int(request.view_args['roomID']))
     if self._room is None:
         raise NotFoundError('This room does not exist')
Пример #34
0
    def migrate_reservations(self):
        print cformat("%{white!}migrating reservations")
        i = 1
        for rid, v in self.rb_root["Reservations"].iteritems():
            room = Room.get(v.room.id)
            if room is None:
                print cformat("  %{red!}skipping resv for dead room {0.room.id}: {0.id} ({0._utcCreatedDT})").format(v)
                continue

            repeat_frequency, repeat_interval = RepeatMapping.convert_legacy_repeatability(v.repeatability)
            booked_for_id = getattr(v, "bookedForId", None)

            r = Reservation(
                id=v.id,
                created_dt=as_utc(v._utcCreatedDT),
                start_dt=utc_to_local(v._utcStartDT),
                end_dt=utc_to_local(v._utcEndDT),
                booked_for_id=self.merged_avatars.get(booked_for_id, booked_for_id) or None,
                booked_for_name=convert_to_unicode(v.bookedForName),
                contact_email=convert_to_unicode(v.contactEmail),
                contact_phone=convert_to_unicode(getattr(v, "contactPhone", None)),
                created_by_id=self.merged_avatars.get(v.createdBy, v.createdBy) or None,
                is_cancelled=v.isCancelled,
                is_accepted=v.isConfirmed,
                is_rejected=v.isRejected,
                booking_reason=convert_to_unicode(v.reason),
                rejection_reason=convert_to_unicode(getattr(v, "rejectionReason", None)),
                repeat_frequency=repeat_frequency,
                repeat_interval=repeat_interval,
                uses_vc=getattr(v, "usesAVC", False),
                needs_vc_assistance=getattr(v, "needsAVCSupport", False),
                needs_assistance=getattr(v, "needsAssistance", False),
            )

            for eq_name in getattr(v, "useVC", []):
                eq = room.location.get_equipment_by_name(eq_name)
                if eq:
                    r.used_equipment.append(eq)

            occurrence_rejection_reasons = {}
            if getattr(v, "resvHistory", None):
                for h in reversed(v.resvHistory._entries):
                    ts = as_utc(parse_dt_string(h._timestamp))

                    if len(h._info) == 2:
                        possible_rejection_date, possible_rejection_reason = h._info
                        m = re.match(
                            r"Booking occurrence of the (\d{1,2} \w{3} \d{4}) rejected", possible_rejection_reason
                        )
                        if m:
                            d = datetime.strptime(m.group(1), "%d %b %Y")
                            occurrence_rejection_reasons[d] = possible_rejection_reason[9:].strip("'")

                    el = ReservationEditLog(
                        timestamp=ts, user_name=h._responsibleUser, info=map(convert_to_unicode, h._info)
                    )
                    r.edit_logs.append(el)

            notifications = getattr(v, "startEndNotification", []) or []
            excluded_days = getattr(v, "_excludedDays", []) or []
            ReservationOccurrence.create_series_for_reservation(r)
            for occ in r.occurrences:
                occ.notification_sent = occ.date in notifications
                occ.is_rejected = r.is_rejected
                occ.is_cancelled = r.is_cancelled or occ.date in excluded_days
                occ.rejection_reason = (
                    convert_to_unicode(occurrence_rejection_reasons[occ.date])
                    if occ.date in occurrence_rejection_reasons
                    else None
                )

            event_id = getattr(v, "_ReservationBase__owner", None)
            if hasattr(event_id, "_Impersistant__obj"):  # Impersistant object
                event_id = event_id._Impersistant__obj
            if event_id is not None:
                event = self.zodb_root["conferences"].get(event_id)
                if event:
                    # For some stupid reason there are bookings in the database which have a completely unrelated parent
                    guids = getattr(event, "_Conference__roomBookingGuids", [])
                    if any(int(x.id) == v.id for x in guids if x.id is not None):
                        r.event_id = int(event_id)
                    else:
                        print cformat("  %{red}event {} does not contain booking {}").format(event_id, v.id)

            print cformat("- [%{cyan}{}%{reset}/%{green!}{}%{reset}]  %{grey!}{}%{reset}  {}").format(
                room.location_name, room.name, r.id, r.created_dt.date()
            )

            room.reservations.append(r)
            db.session.add(room)
            i = (i + 1) % 1000
            if not i:
                db.session.commit()
        db.session.commit()
Пример #35
0
 def _process_args(self):
     self._room = Room.get(int(request.view_args['roomID']))
     if self._room is None:
         raise NotFound(u'This room does not exist')
Пример #36
0
 def _checkParams(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
Пример #37
0
 def _checkParams(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
Пример #38
0
    def migrate_reservations(self):
        print cformat('%{white!}migrating reservations')
        i = 1
        for rid, v in self.rb_root['Reservations'].iteritems():
            room = Room.get(v.room.id)
            if room is None:
                print cformat(
                    '  %{red!}skipping resv for dead room {0.room.id}: {0.id} ({0._utcCreatedDT})'
                ).format(v)
                continue

            repeat_frequency, repeat_interval = RepeatMapping.convert_legacy_repeatability(
                v.repeatability)
            booked_for_id = getattr(v, 'bookedForId', None)

            r = Reservation(
                id=v.id,
                created_dt=as_utc(v._utcCreatedDT),
                start_dt=utc_to_local(v._utcStartDT),
                end_dt=utc_to_local(v._utcEndDT),
                booked_for_id=self.merged_avatars.get(booked_for_id,
                                                      booked_for_id) or None,
                booked_for_name=convert_to_unicode(v.bookedForName),
                contact_email=convert_to_unicode(v.contactEmail),
                contact_phone=convert_to_unicode(
                    getattr(v, 'contactPhone', None)),
                created_by_id=self.merged_avatars.get(v.createdBy, v.createdBy)
                or None,
                is_cancelled=v.isCancelled,
                is_accepted=v.isConfirmed,
                is_rejected=v.isRejected,
                booking_reason=convert_to_unicode(v.reason),
                rejection_reason=convert_to_unicode(
                    getattr(v, 'rejectionReason', None)),
                repeat_frequency=repeat_frequency,
                repeat_interval=repeat_interval,
                uses_vc=getattr(v, 'usesAVC', False),
                needs_vc_assistance=getattr(v, 'needsAVCSupport', False),
                needs_assistance=getattr(v, 'needsAssistance', False))

            for eq_name in getattr(v, 'useVC', []):
                eq = room.location.get_equipment_by_name(eq_name)
                if eq:
                    r.used_equipment.append(eq)

            occurrence_rejection_reasons = {}
            if getattr(v, 'resvHistory', None):
                for h in reversed(v.resvHistory._entries):
                    ts = as_utc(parse_dt_string(h._timestamp))

                    if len(h._info) == 2:
                        possible_rejection_date, possible_rejection_reason = h._info
                        m = re.match(
                            r'Booking occurrence of the (\d{1,2} \w{3} \d{4}) rejected',
                            possible_rejection_reason)
                        if m:
                            d = datetime.strptime(m.group(1), '%d %b %Y')
                            occurrence_rejection_reasons[
                                d] = possible_rejection_reason[9:].strip('\'')

                    el = ReservationEditLog(timestamp=ts,
                                            user_name=h._responsibleUser,
                                            info=map(convert_to_unicode,
                                                     h._info))
                    r.edit_logs.append(el)

            notifications = getattr(v, 'startEndNotification', []) or []
            excluded_days = getattr(v, '_excludedDays', []) or []
            ReservationOccurrence.create_series_for_reservation(r)
            for occ in r.occurrences:
                occ.notification_sent = occ.date in notifications
                occ.is_rejected = r.is_rejected
                occ.is_cancelled = r.is_cancelled or occ.date in excluded_days
                occ.rejection_reason = (
                    convert_to_unicode(occurrence_rejection_reasons[occ.date])
                    if occ.date in occurrence_rejection_reasons else None)

            event_id = getattr(v, '_ReservationBase__owner', None)
            if hasattr(event_id, '_Impersistant__obj'):  # Impersistant object
                event_id = event_id._Impersistant__obj
            if event_id is not None:
                event = self.zodb_root['conferences'].get(event_id)
                if event:
                    # For some stupid reason there are bookings in the database which have a completely unrelated parent
                    guids = getattr(event, '_Conference__roomBookingGuids', [])
                    if any(
                            int(x.id) == v.id for x in guids
                            if x.id is not None):
                        r.event_id = int(event_id)
                    else:
                        print cformat(
                            '  %{red}event {} does not contain booking {}'
                        ).format(event_id, v.id)

            print cformat(
                '- [%{cyan}{}%{reset}/%{green!}{}%{reset}]  %{grey!}{}%{reset}  {}'
            ).format(room.location_name, room.name, r.id, r.created_dt.date())

            room.reservations.append(r)
            db.session.add(room)
            i = (i + 1) % 1000
            if not i:
                db.session.commit()
        db.session.commit()
Пример #39
0
 def _process_args(self):
     self._room = Room.get(request.view_args['roomID'])
Пример #40
0
 def _process_args(self):
     self._room = Room.get(request.view_args['roomID'])