コード例 #1
0
ファイル: test_orders.py プロジェクト: garrettmk/colander2
def orders(session, vendors):
    orders = (Order(source_id=vendors[0].id, dest_id=vendors[1].id),
              Order(source_id=vendors[1].id, dest_id=vendors[2].id),
              Order(source_id=vendors[2].id, dest_id=vendors[0].id))

    session.add_all(orders)
    session.commit()
    return orders
コード例 #2
0
def order(service_id):
    if user not in session:
        return redirect(url_for('login'))
    else:
        service_id = Service.objects.with_id(service_id)
        user_id = session["user.id"]
        time = str(datetime.now())
        status = False

        new_order = Order(service_id=service_id,
                          user_id=user_id,
                          time=time,
                          status=status)
        new_order.save()
        return "Da gui Yeu Cau"
コード例 #3
0
def cancel_order():
    client = get_client()

    if (client):
        orderId = get_header_int("orderId")

        if (orderId):
            order = Order.get_from_id(orderId)

            if (order):
                if (order.status != 2 and order.status != -1):
                    if (order.client_id == client.id):
                        order.status = -1
                        get_session().commit()

                        return "true"
                    else:
                        abort(401)
                else:
                    abort(401)
            else:
                abort(404)
        else:
            abort(400)
    else:
        abort(401)
コード例 #4
0
def get_data():
    client = get_client()

    if (client):
        response = {}

        if (get_header("orders")):
            clientOrders = Order.get_from_client(client)
            response["orders"] = []

            for clientOrder in clientOrders:
                response["orders"].append(get_order_data(clientOrder))

            response["orders"].reverse()

        if (get_header("restaurants")):
            restaurants = Restaurant.get_all()
            response["restaurants"] = []

            for restaurant in restaurants:
                response["restaurants"].append(get_restaurant_data(restaurant))

        return jsonify(response)
    else:
        abort(401)
コード例 #5
0
def get_orders():
    user = get_user()
    filters = get_header_json("orderType")

    if (user and filters):
        restaurant = Restaurant.get_from_id(user.restaurant_id)

        if (restaurant):
            response = {}
            response["orders"] = []
            restaurantOrders = Order.get_from_restaurant(restaurant)

            for restaurantOrder in restaurantOrders:
                if (restaurantOrder.status in filters):
                    response["orders"].append(get_order_data(restaurantOrder))

            response["orders"].reverse()

            response["restaurant"] = get_restaurant_data(restaurant)

            return jsonify(response)
        else:
            abort(404)
    else:
        abort(400)
コード例 #6
0
ファイル: test_orders.py プロジェクト: garrettmk/colander2
def test_order_dest_non_null(session, vendors):
    """Ensure that we can't have an Order without a destination."""
    v1 = vendors[0]
    o1 = Order(source_id=v1.id)
    session.add(o1)

    with pytest.raises(IntegrityError):
        session.commit()
コード例 #7
0
def get_order_restaurant(user):
    orderId = get_header_int("orderId")

    if (is_int(orderId)):
        order = Order.get_from_id(orderId)

        if (order):
            if (order.restaurant_id == user.restaurant_id):
                return order
コード例 #8
0
def get_messages(orderId):
    client = get_client()
    user = get_user()

    if ((client or user) and isinstance(orderId, int)):
        order = Order.get_from_id(orderId)

        if (order and ((client and order.client_id == client.id) or (user and order.restaurant_id == user.restaurant_id))):
            socketio.emit("push_messages", {"messages":order.get_chat(), "orderId":order.id}, room=request.sid)
コード例 #9
0
ファイル: test_orders.py プロジェクト: garrettmk/colander2
def test_order_order_number_unique(session, orders):
    """Ensure that we can't have duplicate orders from the same source."""
    o1, o2 = orders[0], Order()
    o2.source_id = o1.source_id
    o1.order_number, o2.order_number = 'same', 'same'
    session.add(o2)

    with pytest.raises(IntegrityError):
        session.commit()
コード例 #10
0
def restaurant_get_stats():
    user = get_user()

    if (user):
        restaurant = Restaurant.get_from_id(user.restaurant_id)

        if (restaurant):
            orders = Order.get_from_restaurant(restaurant)
            date = datetime.date.today()
            resp = {
                "stats": {
                    "paidFees": restaurant.paid_fees,
                    "month": {
                        'orderCount': 0,
                        'grossIncome': 0,
                        'fee': 0,
                        'netIncome': 0,
                    },
                    "all": {
                        'orderCount': 0,
                        'grossIncome': 0,
                        'fee': 0,
                        'netIncome': 0,
                    },
                }
            }

            for order in orders:
                if (order.status == 2):
                    orderDate = datetime.date.fromtimestamp(order.date)

                    resp["stats"]["all"]["orderCount"] += 1
                    resp["stats"]["all"]["grossIncome"] += order.price
                    resp["stats"]["all"]["fee"] += order.fee
                    resp["stats"]["all"]["netIncome"] += (order.price -
                                                          order.fee)

                    if (orderDate.month == date.month
                            and orderDate.year == date.year):
                        resp["stats"]["month"]["orderCount"] += 1
                        resp["stats"]["month"]["grossIncome"] += order.price
                        resp["stats"]["month"]["fee"] += order.fee
                        resp["stats"]["month"]["netIncome"] += (order.price -
                                                                order.fee)

            return jsonify(resp)
        else:
            abort(404)
    else:
        abort(401)
コード例 #11
0
def save_order():
    user_data = session.get('user_data', None)
    user=json.loads(user_data)
    username = user['username']
    prods = []
    if request.method == "POST":
        total  = request.form.get('total')
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 
        print(now)
        if Order.insert_order(connection,Order(0,username,now,total)):
            cart_products = session['mycart'][username]
            if cart_products:
                for k, v in cart_products.items():
                    prods.append(Cart(k,v['name'],v['quantity'],v['price'],v['total']))
                for prod in prods:
                    OrderDetails.insert_order_details(connection,OrderDetails(0,0,prod.id_product,prod.quantity,prod.total))
                    UserProductRating.insert_product_notrated(connection,UserProductRating(username,prod.id_product,0,0))
                flash('Order Saved Successfully!')
                session.modified = True
                session['mycart'].pop(username)
                return redirect(url_for(".my_cart"))
        else:
            flash("Error saving order, try again later.")
            return redirect(request.referrer)
コード例 #12
0
def get_messages(data):
    client = get_client()
    user = get_user()
    orderId = data["orderId"]
    message = data["message"]

    if ((client or user) and isinstance(orderId, int) and message and len(message) <= 100):
        order = Order.get_from_id(orderId)

        if (order and ((client and order.client_id == client.id) or (user and order.restaurant_id == user.restaurant_id))):
            restaurant = Restaurant.get_from_id(order.restaurant_id)

            if (restaurant):
                if (order.status != 2 and order.status != -1):
                    order.add_chat(message, True if client else False)
                    pushMessages(client, restaurant, order)
def view_dashboard():
    bar_labels, bar_values = Product.select_ten_best_selled_products(
        connection)
    line_labels, line_values = Order.select_ten_last_days(connection)
    user_data_admin = session.get('user_data_admin', None)

    return render_template(
        'module_admin/dashboard.html',
        bar_max=max(bar_values),
        bar_labels=bar_labels,
        bar_values=bar_values,
        line_max=max(line_values),
        line_labels=line_labels,
        line_values=line_values,
        logged_in=True,
        user=json.loads(user_data_admin) if user_data_admin else None)
コード例 #14
0
def create_order():
    client = get_client()

    if (client):
        restaurantId = get_header_int("restaurantId")
        address = get_header("address")
        comments = get_header("comments")
        coords = json.loads(get_header("coords"))
        products = json.loads(get_header("products"))

        if (restaurantId and address and products):
            if (len(products) > 0):
                price = 0

                for productData in products:
                    product = Product.get_from_id(productData["id"])

                    if (product):
                        price = price + (product.price * productData["count"])
                    else:
                        abort(402)

                restaurant = Restaurant.get_from_id(restaurantId)

                if (restaurant):
                    order = Order.add(address, price, comments, products,
                                      coords, client, restaurant)

                    if (order):
                        return "true"
                    else:
                        abort(402)
                else:
                    abort(404)
            else:
                abort(401)
        else:
            abort(400)
    else:
        abort(401)
コード例 #15
0
def first_run():
    from models.client import Client
    from models.category import Category
    from models.orders import Order
    from models.product import Product
    from models.restaurants import Restaurant
    from models.user import User
    meta = sqlalchemy.MetaData(engine)
    meta.reflect()
    #meta.drop_all()

    print("First run, please wait while the db is being populated...")

    # Create tables
    Base.metadata.create_all(engine)

    testClient = Client.add("6977988551")
    testClient2 = Client.add("8891155521")

    restaurant = Restaurant.add(
        "Restaurant 1",
        "The best food you'll find in the city\nWe make sandwiches, salads and burgers"
    )

    sandwichesCategory = Category.add("Sandwiches", restaurant)
    Product.add("Pulled Pork", "With tangy barbecue sauce on an onion knot",
                9.50, restaurant, sandwichesCategory)
    Product.add(
        "Turkey Club",
        "Roasted turkey breast, bacon, lettuce, avocado and tomato on baguette",
        8, restaurant, sandwichesCategory)
    Product.add(
        "Reuben",
        "Corned beef, melted swiss, sauerkraut and thousand island on marbled rye",
        8, restaurant, sandwichesCategory)
    Product.add(
        "Shrimp Cilantro Wrap",
        "Shrimp, avocado, mixed greens, salsa, cilantro and may on a tomato tortilla",
        8.5, restaurant, sandwichesCategory)

    burgerCategory = Category.add("Burgers", restaurant)
    Product.add(
        "Grass-fed Beef Burger",
        "With sharp cheddar, heirloom tomatoes and caramelized onions", 9.5,
        restaurant, burgerCategory)
    Product.add(
        "Mushroom Swiss Burger",
        "With sautéed mushrooms and melted swiss on a home-baked roll", 10,
        restaurant, burgerCategory)
    Product.add(
        "Hickory Burger",
        "Topped with cheddar, hickory smoked bacon and smoked barbecue sauce",
        10, restaurant, burgerCategory)
    Product.add(
        "Chicken Burger",
        "Grilled chicken breast with heirloom tomatoes, avocado and sprouts on a home-baked roll",
        9, restaurant, burgerCategory)

    saladCategory = Category.add("Salads", restaurant)
    Product.add(
        "Caesar Salad",
        "Romaine, fresh parmesan, seasoned croutons and black pepper with garlic anchovy dressing",
        6.75, restaurant, saladCategory)
    Product.add("Red Iceberg Salad",
                "With sweet corn, blackberries, goat cheese and fresh basil",
                9.25, restaurant, saladCategory)
    Product.add(
        "House Salad",
        "With green olives, green peppers, onions, cucumbers, and tomato",
        6.75, restaurant, saladCategory)
    Product.add(
        "Blue Chicken Salad",
        "Mesclun greens, apple, grilled chicken, gorgonzola, chesse and balsamic vinagrette",
        9.25, restaurant, saladCategory)

    # Add an user for the restaurant we just created
    User.add("restaurant1", "restaurant1", 0, restaurant)

    streets = [
        "Oak Street", "Madison Avenue", "Bridle Lane", "Jefferson Street",
        "Lafayette Avenue", "Grove Street", "Chestnut Avenue"
    ]

    # Simulate some orders on a different client
    originalDate = time.time() - 57600000
    for i in range(87):
        productCount = randint(1, 2)
        used = {}
        products = []
        price = 0

        originalDate += randint(376000, 576000)

        for y in range(productCount):
            id = randint(0, 11)
            while (id in used):
                id = randint(0, 11)

            used[id] = True
            amount = randint(1, 2)
            products.append({"id": id + 1, "count": amount})
            product = Product.get_from_id(id + 1)
            price += amount * product.price

        order = Order.add(
            random.choice(streets) + " " + str(randint(1, 5000)), price, "",
            products, [-34.601874, -58.432611], testClient2, restaurant)
        order.date = originalDate
        order.status = 2
        get_session().commit()

    Order.add("Bridle Lane 1775", 9.50, "", [{
        'id': 1,
        'count': 1
    }], [-34.601874, -58.432611], testClient, restaurant)
コード例 #16
0
ファイル: main.py プロジェクト: mattiasbarth/DBProject
def main():
    Base.metadata.create_all(engine)
    store = Store()
    employee = Employee()
    order = Order()
    ordereredproduct = Orderered_product()
コード例 #17
0
ファイル: server.py プロジェクト: MakersLab/nacenovac
def order():
    data = loads(request.form['data'])
    files = data['files']
    filesDb = []
    orderDb = Order(data['email'],
                    data['phone'],
                    delivery=data['delivery'],
                    details=data['details'])
    orderPrice = 0
    for file in files:
        fileDb = File.query.filter_by(id=file['id']).first()
        orderDb.files.append(fileDb)
        fileDb.filament = file['filament']
        fileDb.amount = file['amount']
        filesDb.append(fileDb)
        filament = FILAMENTS[file['filament']]
        individualItemPrice = price(fileDb.printTime, fileDb.filamentUsed,
                                    filament)
        individualPrice = individualItemPrice * file['amount']
        orderPrice += individualPrice
        file['color'] = filament['color-name']
        file['material'] = filament['material']
        file['price'] = individualPrice
        file['priceItem'] = individualItemPrice
        file['name'] = fileDb.name
        file['content'] = loadFromFile(os.path.join(
            CONFIG['stl-upload-directory'], fileDb.fileName),
                                       bytes=True)
    deliveryPrice = 0
    if data['delivery'] == 'express':
        deliveryPrice = round(orderPrice * CONFIG['express-delivery'])
    orderPrice = orderPrice + deliveryPrice
    orderPriceWithTax = round(orderPrice * CONFIG['tax'])

    orderDb.price = orderPrice
    dbSession.add(orderDb)
    dbSession.commit()
    orderId = orderDb.id

    @execute
    def sendMail():
        filesDb = []
        for file in files:
            fileDb = File.query.filter_by(id=file['id']).first()
            filesDb.append(fileDb)

        orderDb = Order.query.filter_by(id=orderId).first()

        email = Email(EMAIL_CONFIG['server'], EMAIL_CONFIG['port'],
                      EMAIL_CONFIG['email'], EMAIL_CONFIG['password'])
        details = data['details'].replace('\n', '<br>')
        try:
            template = env.get_template('client.jinja2')
            content = template.render(
                files=files,
                price=orderPrice,
                priceWithTax=orderPriceWithTax,
                orderId=orderId,
                email=data['email'],
                delivery=additionalDeliveryInfo(data['delivery']),
                details=details,
                phone=data['phone'],
                deliveryPrice=deliveryPrice,
            )
            messageForClient = email.createMessage(
                EMAIL_CONFIG['email'], data['email'],
                '3D továrna - objednávka č. S{orderId}'.format(
                    orderId=orderId), content)
            email.send(messageForClient)
            orderDb.emailSentToClient = True
            dbSession.commit()
        except Exception as e:
            pass

        try:
            template = env.get_template('company.jinja2')
            content = template.render(
                files=files,
                price=orderPrice,
                priceWithTax=orderPriceWithTax,
                orderId=orderId,
                email=data['email'],
                delivery=additionalDeliveryInfo(data['delivery']),
                details=details,
                phone=data['phone'],
                deliveryPrice=deliveryPrice,
            )
            messageForCompany = email.createMessage(
                EMAIL_CONFIG['email'],
                EMAIL_CONFIG['order-to'],
                '3D továrna - objednávka č. S{orderId}'.format(
                    orderId=orderId),
                content,
                files,
            )
            email.send(messageForCompany)
            orderDb.emailSentToCompany = True
            dbSession.commit()
        except Exception as e:
            pass

    return dumps({
        'message': 'new order was created',
        'order': {
            'orderId': orderId
        },
        'successful': True
    })