Пример #1
0
def remove_from_wishlist(isbn: str) -> Response:
    res = CustomResponse()
    if current_user is None:
        logout_user()
        return res.get_response()
    try:
        if isbn not in list(
                map(lambda item: item.book_isbn, current_user.wishlist_items)):
            raise RecordNotFoundException(isbn)
        db.session.delete(
            list(
                filter(lambda item: item.book_isbn == isbn,
                       current_user.wishlist_items))[0])
        db.session.commit()
        res.set_data(
            list(
                map(lambda item: item.get_relaxed_view(),
                    current_user.wishlist_items)))
    except RecordNotFoundException as e:
        db.session.rollback()
        res.set_error(e.message)
    except:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #2
0
def translate_password(password: str) -> Response:
    res = CustomResponse()
    hash = Customer.translate_password(password)
    res.set_data({
        'password': password,
        'hash': hash.decode("utf-8"),
    })
    return res.get_response()
Пример #3
0
def find_customer(isbn: str) -> Response:
    res = CustomResponse(data=[])
    try:
        _books = db.session.query(Book).filter(Book.isbn.like(f"{isbn}%")).limit(10).all()
        res.set_data(list(map(lambda book: book.get_search_view(), _books)))
    except IntegrityError as e:
        print(str(e))
    return res.get_response()
Пример #4
0
def start_loan() -> Response:
    res = CustomResponse()
    try:
        if request.json['ssn'] is None or request.json['isbn'] is None:
            raise InvalidRequestException
        request.json['issued_by'] = current_user.ssn
        request.json['loaned_at'] = datetime.now()
        request.json['returned_at'] = None
        statement = text(f"""
            exec insertLoan
            @book_isbn = :isbn,
            @customer_ssn = :ssn,
            @issued_by = :issued_by,
            @loaned_at = :loaned_at,
            @returned_at = :returned_at
        """)
        db.session.execute(statement, request.json)
        db.session.commit()

        book = db.session.query(Book).get(request.json['isbn'])
        res.set_data(book.get_relaxed_view())
    except RecordNotFoundException or InvalidRequestException as e:
        db.session.rollback()
        res.set_error(e.message)
    except IntegrityError:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #5
0
def fetch_library_reservations() -> Response:
    res = CustomResponse()
    library_reservations = db.session.query(CustomerWishlistItem) \
        .filter(CustomerWishlistItem.requested_at is not None,
                CustomerWishlistItem.requested_at > (datetime.now() - timedelta(days=30)),
                CustomerWishlistItem.picked_up == 0).all()
    res.set_data(
        list(
            map(lambda item: item.get_librarian_relaxed_view(),
                library_reservations)))
    return res.get_response()
Пример #6
0
def create_book() -> Response:
    res = CustomResponse()
    try:
        book = Book(**request.json)
        db.session.add(book)
        db.session.commit()
        res.set_data(book.get_relaxed_view())
        return res.get_response(201)
    except IntegrityError:
        db.session.rollback()
        res.set_error(f"Item you are trying to add already exists!")
    except InvalidRequestException as e:
        db.session.rollback()
        res.set_error(e.message)
    return res.get_response()
Пример #7
0
def login() -> Response:
    res = CustomResponse()
    if current_user.is_authenticated:
        res.set_data(current_user.get_relaxed_view())
        return res.get_response()
    user = db.session.query(Customer).filter(
        Customer.email == request.json.get('email')).first()
    if user and bcrypt.check_password_hash(user.password,
                                           request.json.get('password')):
        login_user(user)
        session['login_type'] = 'customer'
        res.set_data(user.get_relaxed_view())
    else:
        res.set_error('Wrong email or password!')
    return res.get_response()
Пример #8
0
def login() -> Response:
    res = CustomResponse()
    if current_user.is_authenticated:
        res.set_data(current_user.get_relaxed_view())
        return res.get_response()
    librarian = db.session.query(Librarian).filter(
        Librarian.email == request.json.get('email')).first()
    if librarian and bcrypt.check_password_hash(librarian.password,
                                                request.json.get('password')):
        login_user(librarian)
        session['login_type'] = 'librarian'
        res.set_data(librarian.get_relaxed_view())
    else:
        res.set_error('Wrong email or password!')
    return res.get_response()
Пример #9
0
def logout() -> Response:
    res = CustomResponse(librarian_level=True)
    try:
        logout_user()
    except UnauthorizedAccessException as e:
        res.set_error(e.message)
        return res.get_response(status=401)
    except:
        res.set_error('Failed to log out user!')
    return res.get_response()
Пример #10
0
def search_in_catalog() -> Response:
    res = CustomResponse(data=[])
    try:
        req = SearchRequest(**request.json)
        if not req.is_valid():
            raise InvalidRequestException
        with db.engine.connect() as con:
            statement = text(f"""
                exec find_book
                @order_by = 'title',
                @offset = :offset,
                @limit = :limit,
                @search_group = :group,
                @title = {"'" + req.phrase + "'" if 'TITLE' in req.columns else 'null'},
                @author = {"'" + req.phrase + "'" if 'AUTHOR' in req.columns else 'null'},
                @area = {"'" + req.phrase + "'" if 'AREA' in req.columns else 'null'};
            """)
            rs = con.execute(statement, req.__dict__)
            data = []
            for row in rs:
                next = Book(**row)
                data.append(next.get_relaxed_view())
            res.set_data(data)
    except InvalidRequestException as e:
        res.set_error(e.message)
    return res.get_response()
Пример #11
0
def add_item_to_library_wishlist() -> Response:
    res = CustomResponse()
    try:
        item = LibrarianWishlistItem(**request.json)
        db.session.add(item)
        db.session.commit()
        res.set_data(item.get_relaxed_view())
    except InvalidRequestException as e:
        db.session.rollback()
        res.set_error(e.message)
    except IntegrityError as e:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #12
0
def disable_book(isbn: str) -> Response:
    res = CustomResponse()
    try:
        book = db.session.query(Book).get(isbn)
        if book is None or book.deleted:
            raise RecordNotFoundException(isbn)
        book.disable_record()
        db.session.commit()
        res.set_data(book.get_relaxed_view())
    except RecordNotFoundException as e:
        db.session.rollback()
        res.set_error(e.message)
    except IntegrityError:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #13
0
def remove_item_from_library_wishlist(id: str) -> Response:
    res = CustomResponse()
    try:
        item = db.session.query(LibrarianWishlistItem).get(id)
        if item is None:
            raise RecordNotFoundException(id)
        db.session.delete(item)
        db.session.commit()
        res.set_data({'id': id})
    except RecordNotFoundException as e:
        db.session.rollback()
        res.set_error(e.message)
    except IntegrityError as e:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #14
0
def fetch_overdue_loans(page: int) -> Response:
    res = CustomResponse()
    with db.engine.connect() as con:
        statement = text(f"""
        select * 
        from not_returned_loans
        where grace_period_end < getdate()
        order by grace_period_end desc
        OFFSET :page * 25 ROWS
        FETCH NEXT 25 ROW ONLY;
         """)
        rs = con.execute(statement, {'page': page})
        data = []
        for row in rs:
            row_val = dict()
            for column, value in row.items():
                row_val[column] = value
            data.append(row_val)
    res.set_data(data)
    return res.get_response()
Пример #15
0
def get_book(isbn: str) -> Response:
    res = CustomResponse(data=[])
    try:
        book = db.session.query(Book).get(isbn)
        if book is None:
            raise RecordNotFoundException(isbn)
        res.set_data(book.get_relaxed_view())
    except RecordNotFoundException as e:
        res.set_error(e.message)
    return res.get_response()
Пример #16
0
def fetch_wishlist() -> Response:
    res = CustomResponse()
    if current_user is None:
        logout_user()
        return res.get_response()
    try:
        res.set_data(
            list(
                map(lambda item: item.get_relaxed_view(),
                    current_user.wishlist_items)))
    except:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #17
0
def get_average_loan_time_in_days():
    res = CustomResponse()
    try:
        with db.engine.connect() as con:
            rs = con.execute("exec get_average_loan_time_in_days;")
            data = []
            for row in rs:
                data.append({'days': row['average_loan_length_in_days']})
            res.set_data(data)
    except:
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #18
0
def add_to_wishlist(isbn: str) -> Response:
    res = CustomResponse()
    if current_user is None:
        logout_user()
        return res.get_response()
    try:
        if isbn in list(
                map(lambda item: item.book_isbn, current_user.wishlist_items)):
            raise RecordAlreadyExistsException(isbn)
        current_user.wishlist_items.append(
            CustomerWishlistItem(book_isbn=isbn,
                                 customer_ssn=current_user.ssn))
        db.session.commit()
        res.set_data(
            list(
                map(lambda item: item.get_relaxed_view(),
                    current_user.wishlist_items)))
    except RecordAlreadyExistsException as e:
        db.session.rollback()
        res.set_error(e.message)
    except:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #19
0
def fetch_history() -> Response:
    res = CustomResponse()
    if current_user is None or current_user.ssn is None:
        logout_user()
        return res.get_response()
    loans = db.session.query(Loan).filter(
        Loan.customer_ssn == current_user.ssn).order_by(
            Loan.loaned_at.desc()).all()
    res.set_data(list(map(lambda loan: loan.get_relaxed_view(), loans)))
    return res.get_response()
Пример #20
0
def accept_library_reservation(id: str) -> Response:
    res = CustomResponse()
    try:
        item = db.session.query(CustomerWishlistItem).get(id)
        if item is None or item.id not in list(
                map(lambda it: it['id'],
                    fetch_library_reservations().json['data'])):
            raise RecordNotFoundException(id)
        # TODO: mark item as accepted
        db.session.commit()
        res.set_data(item.get_librarian_relaxed_view())
    except RecordNotFoundException as e:
        db.session.rollback()
        res.set_error(e.message)
    return res.get_response()
Пример #21
0
def fetch_top_x_popular_books(count: int):
    res = CustomResponse()
    try:
        with db.engine.connect() as con:
            statement = text(
                f"""exec fetch_top_x_popular_books @limit = :count;""")
            rs = con.execute(statement, {'count': count})
            data = []
            for row in rs:
                data.append(dict(row))
            res.set_data(data)
    except Exception as e:
        print(str(e))
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #22
0
def close_loan(id: str) -> Response:
    res = CustomResponse()
    try:
        loan = db.session.query(Loan).get(id)
        if loan is None:
            raise RecordNotFoundException(id)
        loan.close()
        db.session.commit()
    except RecordNotFoundException as e:
        db.session.rollback()
        res.set_error(e.message)
    except IntegrityError:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #23
0
def register_professor():
    res = CustomResponse()
    try:
        password = Customer.generate_password()
        pw_hash = bcrypt.generate_password_hash(password=password)
        phone_numbers = request.json.get('phone_numbers')
        phone_numbers = list(
            map(
                lambda number: PhoneNumber(
                    customer_ssn=request.json.get('ssn'), **number),
                phone_numbers))
        address = request.json.get('address')
        address = Address(**address)
        request.json['type'] = 'PROFESSOR'
        if phone_numbers is not None and address is not None:
            del request.json['phone_numbers']
            del request.json['address']
        else:
            raise InvalidRequestException(
                'Address and phone numbers must not be empty!')
        cards = [
            Card(customer_ssn=request.json.get('ssn'),
                 expiration_date=datetime.now() + timedelta(days=100000))
        ]
        customer = Customer(**request.json,
                            cards=cards,
                            address=address,
                            phone_numbers=phone_numbers,
                            pw_hash=pw_hash)
        db.session.add(customer)
        db.session.commit()

        result = customer.get_relaxed_v1_view()
        result['password'] = password
        res.set_data(result)
        return res.get_response(201)
    except InvalidRequestException as e:
        db.session.rollback()
        res.set_error(e.message)
    except IntegrityError as e:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    except:
        db.session.rollback()
        res.set_error(Config.UNHANDLED_EXCEPTION_MESSAGE)
    return res.get_response()
Пример #24
0
def logout() -> Response:
    res = CustomResponse()
    logout_user()
    return res.get_response()
Пример #25
0
def fetch_campuses() -> Response:
    res = CustomResponse()
    campuses = db.session.query(Campus).all()
    res.set_data(list(map(lambda campus: campus.get_relaxed_view(), campuses)))
    return res.get_response()
Пример #26
0
def fetch_library_wishlist() -> Response:
    res = CustomResponse()
    library_wishlist = db.session.query(LibrarianWishlistItem).all()
    res.set_data(
        list(map(lambda item: item.get_relaxed_view(), library_wishlist)))
    return res.get_response()