Ejemplo n.º 1
0
def create_order(user_id, copies, book_id):
    book = Book.objects(id=book_id).first()
    customer = Customer.objects(id=user_id).first()
    books = []
    total = 0.0
    while copies > 0:
        books.append(book)
        total = round(total + Book.objects.with_id(book_id).price, 2)
        copies -= 1
    """checking to see if there's a order id already stored in session"""
    if session.get("order_id"):
        order = Order.objects(id=session.get("order_id")).first()
        order.total_price = round(order.total_price + total, 2)
        for book in books:
            order.books.append(book)
        order.save()
    else:
        order = Order(customer_name="{} {}".format(customer.first_name,
                                                   customer.last_name),
                      books=books,
                      shipping_address=customer.address,
                      total_price=total,
                      order_status="processing",
                      order_date=datetime.datetime.now).save()
        session["order_id"] = str(order.id)

    return order
Ejemplo n.º 2
0
 def add_order(self,
               ot,
               bt,
               seller,
               buyer,
               price,
               method='offline',
               addr='',
               phone=''):
     if Order.objects(book_timestamp=bt, buyer=buyer):
         return False
     offline = True
     mail = False
     if method == 'mail':
         offline = False
         mail = True
     book = Order(order_timestamp=ot,
                  book_timestamp=bt,
                  seller=seller,
                  buyer=buyer,
                  agreePrice=price,
                  offLine=offline,
                  mail=mail,
                  address=addr,
                  phone=phone)
     book.save()
     return True
Ejemplo n.º 3
0
def login():
    """Log in a registered user by adding the user id to the session."""
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        error = None
        user = Customer.objects(email=email).first()

        if user is None:
            error = "Incorrect Email."
        elif not check_password_hash(user["password"], password):
            error = "Incorrect password."

        if error is None:
            # store the user id in a new session and return to the index
            if session.get('order_id'):
                order = Order.objects(id=session.get('order_id')).first()
                order.delete()
            session.clear()
            session["user_id"] = str(user["id"])
            return redirect(url_for("bookstore.index"))

        flash(error)

    return render_template("auth/login.html")
Ejemplo n.º 4
0
def logout():
    """Clear the current session, including the stored user id."""
    if session.get('order_id'):
        order = Order.objects(id=session.get('order_id')).first()
        order.delete()
    session.clear()
    return redirect(url_for("bookstore.index"))
Ejemplo n.º 5
0
def at_checkout():
    if request.form['submit_btn'] == 'Keep Browsing':
        return redirect(url_for('bookstore.index'))
    elif request.form['submit_btn'] == 'Checkout':
        order = Order.objects(id=session.get("order_id")).first()

        if len(order.books) < 1:
            flash("You can't check out with empty cart")
            return redirect(url_for('bookstore.index'))
        else:
            return purchase_books()
    elif request.form['submit_btn'] == 'Clear Cart':
        order = Order.objects(id=session.get("order_id")).first()
        order.delete()
        session['order_id'] = None
        flash("Shopping cart cleared")
        return redirect(url_for('bookstore.index'))
Ejemplo n.º 6
0
def create():
    request_json = request.get_json()
    books = []
    # add only the books that is in stock
    for book in request_json['books']:
        inventory = Inventory.objects(book=book).get()
        if inventory.stock > 0:
            books.append(book)
    if len(books) > 0:
        order = Order(customer_name=request_json['customer_name'],
                      books=books,
                      shipping_address=request_json['shipping_address'],
                      total_price=request_json['total_price'],
                      order_status="processing",
                      order_date=datetime.datetime.now).save()
        return order.to_json()
    else:
        return "no order has been created. book out of stock"
Ejemplo n.º 7
0
def mongo_db_seed(db_name):
    """
    This is a sample mongodb test for populating sample data into mongodb
    :return: the db connection
    """
    mongoengine.connect(db_name, host='localhost', port=27017)
    fake = Faker()

    for x in range(10):
        Book(title=fake.sentence(nb_words=10,
                                 variable_nb_words=True,
                                 ext_word_list=None),
             isbn=fake.isbn13(separator="-"),
             author=fake.name(),
             price=round(random.uniform(0, 100), 2),
             published=datetime.datetime.utcnow(),
             publisher=fake.company()).save()

    for book in Book.objects:
        Inventory(
            book=book.id,
            stock=random.randint(1, 100),
        ).save()

    for x in range(10):
        Customer(first_name=fake.first_name(),
                 last_name=fake.last_name(),
                 address=fake.address(),
                 email=fake.email(),
                 password='******',
                 phone=fake.phone_number(),
                 customer_since=datetime.datetime.utcnow(),
                 orders=[]).save()

    for customer in Customer.objects:
        for x in range(random.randint(1, 5)):
            # the Book.objects.aggregate returns a dict. which is weird...was expecting an obj
            books = [
                book['_id'] for book in Book.objects.aggregate(*[{
                    "$sample": {
                        "size": random.randint(1, 3)
                    }
                }])
            ]
            total = 0.0
            for book in books:
                total = round(total + Book.objects.with_id(book).price)
            order = Order(customer_name="{} {}".format(customer.first_name,
                                                       customer.last_name),
                          books=books,
                          shipping_address=customer.address,
                          total_price=total,
                          order_status="processing",
                          order_date=datetime.datetime.utcnow()).save()
            customer.orders.append(order.id)
            customer.save()
Ejemplo n.º 8
0
def update():
    request_json = request.get_json()
    if 'id' in request_json and 'order_status' in request_json:
        order = Order.objects(id=request_json['id']).get()
        if request_json[
                'order_status'] == "fulfilled" and order.order_status == "processing":
            for book in order.books:
                inventory = Inventory.objects(book=book).get()
                inventory.stock -= 1
                inventory.save()
            order.order_status = "fulfilled"
            order.save()
        return order.to_json()
Ejemplo n.º 9
0
    def get_user_order(self, username):
        buy_order = Order.objects(buyer=username)
        sell_order = Order.objects(seller=username)

        # form response
        buy_order_info = []
        for order in buy_order:
            book = Books.objects.get(timestamp=order.book_timestamp)
            buy_order_info.append({
                'book_name': book.book_name,
                'book_class': book.book_class,
                'order_timestamp': order.order_timestamp,
                'book_timestamp': order.book_timestamp,
                'seller': order.seller,
                'buyer': order.buyer,
                'price': order.agreePrice,
                'isFinish': order.isFinish
            })

        sell_order_info = []
        for order in sell_order:
            book = Books.objects.get(timestamp=order.book_timestamp)
            sell_order_info.append({
                'book_name': book.book_name,
                'book_class': book.book_class,
                'order_timestamp': order.order_timestamp,
                'book_timestamp': order.book_timestamp,
                'seller': order.seller,
                'buyer': order.buyer,
                'price': order.agreePrice,
                'isFinish': order.isFinish
            })

        return jsonify({
            'sell_order': [sell_order_info],
            'buy_order': [buy_order_info]
        })
Ejemplo n.º 10
0
def purchase_books():
    customer = Customer.objects(id=session.get("user_id")).first()
    if session['order_id']:
        order = Order.objects(id=session.get("order_id")).first()
        if len(order.books) < 1:
            flash("Please add some book to cart first")
            return redirect(url_for('bookstore.index'))
    else:
        flash("Please add some book to cart first")
        return redirect(url_for('bookstore.index'))
    customer.orders.append(order)
    customer.save()
    flash("Order complete. The order ID is {}".format(order.id))
    session['order_id'] = None
    return redirect(url_for('bookstore.index'))
Ejemplo n.º 11
0
def test_valid_data_entry(app):
    book_input = Book(title="Test book title",
                      isbn="Test12345",
                      author="Test author",
                      price="123",
                      published=datetime.datetime.utcnow(),
                      publisher="Test company")
    book_input.save()

    # verify book is successfully saved and able to be retrieved and their values match
    book_saved = Book.objects(title=book_input.title).first()
    assert book_saved.title == book_input.title
    assert book_saved.isbn == book_input.isbn
    assert book_saved.author == book_input.author
    assert book_saved.price == book_input.price
    assert book_saved.published.strftime(
        "%m/%d/%Y, %H:%M:%S") == book_input.published.strftime(
            "%m/%d/%Y, %H:%M:%S")
    assert book_saved.publisher == book_input.publisher

    # verify book can be retrieved by isbn
    book_saved = Book.objects(isbn=book_input.isbn).first()
    assert book_saved.title == book_input.title
    assert book_saved.isbn == book_input.isbn
    assert book_saved.author == book_input.author
    assert book_saved.price == book_input.price
    assert book_saved.published.strftime(
        "%m/%d/%Y, %H:%M:%S") == book_input.published.strftime(
            "%m/%d/%Y, %H:%M:%S")
    assert book_saved.publisher == book_input.publisher

    # verify the book can be ordered by a customer
    sample_customer = Customer.objects.first()

    order = Order(customer_name="{} {}".format(sample_customer.first_name,
                                               sample_customer.last_name),
                  books=[book_saved.id],
                  shipping_address=sample_customer.address,
                  total_price=book_saved.price,
                  order_status="processing",
                  order_date=datetime.datetime.utcnow()).save()
    sample_customer.orders.append(order.id)
    sample_customer.save()

    # Look for customer by order. Customer ID should match
    order_customer = Customer.objects(orders=order.id).first()
    assert order_customer.id == sample_customer.id