def buy(): if not current_user.is_authenticated: return redirect('/') try: db_sess = db_session.create_session() basket = db_sess.query(Basket).filter( Basket.user_id == current_user.id).all() if len(basket) == 0: return redirect('/basket') order = Order() order.user_id = current_user.id order.bought_at = datetime.datetime.now() db_sess.add(order) for item in basket: product = db_sess.query(Product).filter( Product.product_id == item.product_id).first() product.quantity -= item.quantity if product.quantity < 0: return redirect( url_for('basket', msg=str('Недостаточно товара: ' + product.product_name))) order_detail = OrderDetails() order_detail.order_id = order.order_id order_detail.product_id = item.product_id order_detail.price = product.price order_detail.quantity = item.quantity db_sess.add(order_detail) db_sess.delete(item) db_sess.commit() return redirect('/orders') except Exception as e: print(e) return redirect('/basket')
def add_order(order: Order): try: order.save() print(f"Added order {order.order_id}") return f"Added order: {order.json()}" except Exception as e: print("Error adding order", e) return None
def product(product_id: int): session = db_session.create_session() product = session.query(Product).get(product_id) if request.method == 'POST': req_form = dict(request.form) if req_form['act'] == 'to cart': product_id = product.id order = session.query(Order).filter( Order.client_id == current_user.id).filter( Order.status == 0).first() if not order: order = Order(client_id=current_user.id, status=0, total_cost=0) session.add(order) session.commit() if product in order: position = session.query(Position).filter( Position.order_id == order.id and Position.product_id == product_id).first() position.count += 1 position.update_point_cost() session.merge(position) session.commit() else: position = Position(order=order, product=product, count=1) position.update_point_cost() session.add(position) session.commit() return redirect('/menu') elif not current_user.is_authenticated: return redirect('/login') return render_template('product.html', product=product)
def list_orders_json(): query = Order.objects() json_string = query.to_json() dicts = json.loads(json_string) print(dicts) return json_string
def anceta(): form = QuestionaryForm() # подключение к форме с вопросами if form.validate_on_submit(): db_sess = db_session.create_session() # создаем сессию бд order = Order(name=form.name_ful.data, email=form.email.data, place=form.place.data, data_holiday=form.data_holiday.data, mobile_phone=form.mobile_phone.data, holiday=form.holiday.data, number_of_guests=form.number_of_guests.data ) # добавление заказа в бд db_sess.add(order) db_sess.commit() orders = db_sess.query(Order).all() with open('static/orders.csv', 'w', encoding='utf-8') as csvfile: writer = csv.writer(csvfile, delimiter=';', quotechar='"') for order in orders: print(order) writer.writerow([ order.name, order.place, order.email, order.data_holiday, order.mobile_phone, order.holiday, order.number_of_guests, order.created_date ]) return redirect( '/successful_order') # перенаправляем на страницу успешного заказа return render_template('anceta.html', form=form)
def post(self): req = request.get_json() valid_ids = [] invalid_ids = [] session = db_session.create_session() orders_list = req["data"] for i in orders_list: if check_order(i): order = Order(order_id=i['order_id'], weight=i['weight'], region=i['region'], delivery_hours=i['delivery_hours']) session.add(order) valid_ids.append(i["order_id"]) else: invalid_ids.append(i["order_id"]) session.commit() if not invalid_ids: response = {"orders": [{"id": i} for i in valid_ids]} response = jsonify(response) response.status_code = 201 return response response = { "validation_error": { "orders": [{ "id": i } for i in invalid_ids] } } response = jsonify(response) response.status_code = 400 return response
def basket(): session = db_session.create_session() user = session.query(User).filter(User.id == current_user.id).first() basket = session.query(Order).filter(Order.client_id == user.id, Order.status == 0).first() basket.update_total_cost() session.commit() if request.method == 'POST': req_form = dict(request.form) if req_form['act'] == 'up': position = session.query(Position).filter( Position.id == int(req_form['position_id'])).first() position.count += 1 position.update_point_cost() session.merge(position) session.commit() elif req_form['act'] == 'down': position = session.query(Position).filter( Position.id == int(req_form['position_id'])).first() position.count = max(0, position.count - 1) position.update_point_cost() session.merge(position) if position.count == 0: session.delete(position) session.commit() elif req_form['act'] == 'delete': position = session.query(Position).filter( Position.id == int(req_form['position_id'])).first() session.delete(position) session.commit() elif req_form['act'] == 'do order': basket.address_data = req_form['address'] basket.payment_way = req_form['pay_radio'] basket.commentary = req_form['comment-offer'] basket.order_date = datetime.today().date() basket.status += 1 session.merge(basket) session.commit() basket = Order(client=user) basket.update_total_cost() session.add(basket) session.commit() return redirect('/basket') return render_template('basket.html', title='Корзина', current_user=user, basket=basket)
def delete_order(order_id): query = Order.objects(order_id=order_id) json_string = query.to_json() cnt = query.count() print(f"Count: {cnt}") query.delete() return json_string
def add_orders(): req_data = request.get_json() order = Order(order_id=req_data['order_id'], table_id=req_data['table_id'], ordered_items=req_data['ordered_items'], description=req_data['description']) return orderService.add_order(order)
def client_login(): form = ClientLoginForm() if form.validate_on_submit(): session = db_session.create_session() user = session.query(User).filter(User.role == 'client').filter( User.phone_number == form.phone_number.data).first() if user: login_user(user, remember=True) return redirect('/') user = User(phone_number=form.phone_number.data, role='client') cart = Order(client=user) cart.update_total_cost() session.add(user) session.add(cart) session.commit() login_user(user, remember=True) return redirect('/') return render_template('login.html', title='Авторизация', form=form)
def add_order(product_id, user_id): form = NewOrderForm() if form.validate_on_submit(): order = Order(delivery_date=form.delivery_date.data, product=product_id, client=user_id) new_order(order) return redirect(f'/account/{user_id}') return render_template('order.html', title='Сделать заказ', form=form)
def add_order(self, total_price, status, goods, user=None, address=None): if goods is None or len(goods) == 0: raise ValueError(f"Can`t create Order with 0 goods in it: {goods}") order = Order(total_price=float(total_price)) if status is int: order.status_id = status '''''' if address: order.address_id = address if user: order.user_id = user '''''' for good in goods: good = self.db_sess.query(Good).filter( Good.id == int(good)).first() order.goods_by_order.append(good) self.db_sess.add(order) self.db_sess.commit() return order
def create_order(data) -> Order: order = Order() order.order_id = data["order_id"] order.weight = data["weight"] order.region = data["region"] order.delivery_hours = convert_to_str(data["delivery_hours"]) return order
def get(self): current_orders = Order.list_current() dicts = [] for order in current_orders: dicts.append({ 'id': order.order_id, 'restaurant_id': order.restaurant_id, 'restaurant': order.restaurant_name, 'organizer': order.organizer, 'time': order.order_time }) return dicts
def get(self, order_id): order = Order.by_id(order_id) if request.user.username == order.organizer: items = order.get_all_items() else: items = order.get_items_for_user(request.user.username) return { 'id': order.order_id, 'restaurant_id': order.restaurant_id, 'restaurant': order.restaurant_name, 'organizer': order.organizer, 'time': order.order_time, 'items': items }
def make_order(): message_role = role_user() form_role = RoleUserForm() if current_user.is_authenticated: db_sess = db_session.create_session() summ = 0 list_order = '' if 'cart' in session: if session['cart']: for good in session['cart']: for name_good in good: goods = db_sess.query(Goods).filter( Goods.name == name_good).first() summ += goods.price * int(good[name_good]) list_order += str(goods.id) + ':' + str( good[name_good]) + ';' goods.count = goods.count - int(good[name_good]) db_sess.commit() good = Order( goods=list_order, price=summ, by_who=session['_user_id'], ) db_sess.add(good) db_sess.commit() session['cart'].clear() session.modified = True return render_template('cart.html', message='Вы удачно заказали товары.', sum=0, form_role=form_role, message_role=message_role) else: return render_template('cart.html', message='У вас пустая корзина', sum=0, form_role=form_role, message_role=message_role) else: return render_template('cart.html', message='У вас пустая корзина', sum=0, form_role=form_role, message_role=message_role) else: return redirect('/')
def order(): if current_user._get_current_object().__class__.__name__ == 'Admin': form = MakeOrderForm() if request.method == "POST": if form.validate_on_submit(): if check_times(int(form.start_delivery_hour.data), int(form.finish_delivery_hour.data)): session = db_session.create_session() courier = Order(weight=form.weight.data, region=form.region.data, contact=form.contact.data, delivery_hours=[ f"{str(form.start_delivery_hour.data).rjust(2, '0')}:00-{str(form.finish_delivery_hour.data).rjust(2, '0')}:00"]) session.add(courier) session.commit() return redirect('/profile') return render_template('order.html', user=current_user, form=form, time_message='Такое время недопустимо.') return render_template('order.html', user=current_user, form=form, time_message='') elif request.method == "GET": return render_template('order.html', user=current_user, form=form, time_message='') return render_template('no_access.html', user=current_user)
def add_orders(): req_json = request.json['data'] db_sess = db_session.create_session() res = [] bad_id = [] is_ok = True already_in_base = [i.id for i in db_sess.query(Order).all()] for order_info in req_json: flag = False error_ans = [] try: OrderModel(**order_info, base=already_in_base) except pydantic.ValidationError as e: error_ans += json.loads(e.json()) flag = True if order_info['order_id'] in already_in_base: error_ans += [{ "loc": ["id"], "msg": "Invalid id: There is a order with the same id", "type": "value_error" }] if flag or order_info['order_id'] in already_in_base: is_ok = False bad_id.append({ "id": int(order_info['order_id']), 'errors': error_ans }) if not is_ok: continue order = Order() order.id = order_info['order_id'] order.weight = order_info['weight'] order.region = order_info['region'] order.orders_courier = 0 for i in list(order_info['delivery_hours']): dh = DH() dh.order_id = order.id dh.hours = i db_sess.add(dh) db_sess.add(order) res.append({"id": int(order_info['order_id'])}) if is_ok: db_sess.commit() return jsonify({"orders": res}), 201 pprint({"validation_error": bad_id}) print( '-------------------------------------------------------------------------' ) return jsonify({"validation_error": bad_id}), 400
def post(self): parser = reqparse.RequestParser() parser.add_argument( 'restaurant_id', type=int, required=True, help="From which restaurant would you like to order?") parser.add_argument('order_time', type=lambda x: date_parser.parse(x), required=True, help="When would you like to place the order?") args = parser.parse_args() order = Order.create(request.user.username, args['restaurant_id'], args['order_time']) return { 'id': order.order_id, 'restaurant_id': order.restaurant_id, 'restaurant': order.restaurant_name, 'organizer': order.organizer, 'time': order.order_time }, 201
def list_order_json(order_id): query = Order.objects(order_id=order_id) json_string = query.to_json() return json_string
def order_page(delivery): cart = session.query(Cart).filter(Cart.id == current_user.id).first() id = cart.id if delivery == 'home': delivery_price = 9.99 elif delivery == 'sdek': delivery_price = 5.99 elif delivery == 'boxberry': delivery_price = 4.99 full_price = session.query(func.sum(Cart_Product.full_price)).filter_by(cart_id=id).scalar() form = OrderForm() if form.validate_on_submit(): order_session = db_session.create_session() order = Order() order.cart_id = id order.surname = form.surname.data order.name = form.name.data order.phone = form.phone.data order.delivery = delivery order.delivery_price = delivery_price order.country = form.country.data order.town = form.town.data order.street = form.street.data order.house = form.house.data order.flat = form.flat.data order.promo = form.promo.data order_session.add(order) order_session.commit() return redirect("/thanks") return render_template("order.html", form=form, cart_id=id, full_price=full_price, delivery_price=delivery_price, delivery=delivery)
def list_orders() -> List[Order]: query = Order.objects() orders = list(query) return orders
def add_orders(): form = MakeOrderForm() if form.validate_on_submit(): req_json = [] db_sess = db_session.create_session() res = [] bad_id = [] is_ok = True already_in_base = [i.id for i in db_sess.query(Order).all()] req_json.append({ 'order_id': max(already_in_base) + 1, 'weight': form.weight.data, 'region': form.region.data, 'delivery_hours': form.dh.data.split(',') }) print(req_json[0]['delivery_hours']) for order_info in req_json: flag = False error_ans = [] try: OrderModel(**order_info, base=already_in_base) except pydantic.ValidationError as e: error_ans += json.loads(e.json()) flag = True if order_info['order_id'] in already_in_base: error_ans += [{ "loc": ["id"], "msg": "Invalid id: There is a order with the same id", "type": "value_error" }] if flag or order_info['order_id'] in already_in_base: is_ok = False bad_id.append({ "id": int(order_info['order_id']), 'errors': error_ans }) if not is_ok: continue order = Order() order.id = order_info['order_id'] order.weight = order_info['weight'] order.region = order_info['region'] order.orders_courier = 0 for i in list(order_info['delivery_hours']): dh = DH() dh.order_id = order.id dh.hours = i db_sess.add(dh) db_sess.add(order) res.append({"id": int(order_info['order_id'])}) if is_ok: db_sess.commit() return render_template('result.html', u=str({"orders": res})) # return jsonify({"orders": res}), 201 pprint({"validation_error": bad_id}) print( '-------------------------------------------------------------------------' ) return render_template('result.html', u=str({"validation_error": bad_id})) # return jsonify({"validation_error": bad_id}), 400 return render_template('new_order.html', title='Новый заказ', form=form)
name='Karl', surname='aaa', phone_number='9999', email='asdasd', birthday='11.11.11') worker_data = WorkerData(worker_id=1, passport='8017', address='Pushkina dom kalatuchkina') cook.set_password('121321') global_session.add(cook) global_session.add(worker_data) global_session.commit() order = Order( id=0, client_id=0, address_data="no", ) product = Product(id=0, back_name='aaa', front_name='Aaa', description='sadsaas', ingredients='1, 2, 3', cost=100) global_session.add(order) global_session.add(product) global_session.commit() position = Position(order=order, product=product, count=2,
def create_order(products_in_cart): global count_products if current_user.get_id(): count_products = 0 db_sess = db_session.create_session() order = Order() total_cost = sum([ db_sess.query(Product).filter(Product.id == int(i)).first().price for i in products_in_cart.split(",") ]) order.user_id = current_user.get_id() order.order = products_in_cart order.total_price = total_cost order.quantity_of_goods = len(products_in_cart.split(",")) db_sess.add(order) db_sess.query(User).filter(User.id == current_user.get_id()).update( {User.cart: ""}) db_sess.commit() db_sess.close() else: if request.method == "POST": db_sess = db_session.create_session() req = request.form address = req.get("address") phone_number = req.get("phone_number") if address != "" and phone_number != "": if phone_number.isdigit() and len(phone_number) == 11: count_products = 0 unreg_order = UnregOrder() unreg_order.user_phone_number = phone_number unreg_order.address = address unreg_order.order = products_in_cart products = [ db_sess.query(Product).filter( Product.id == int(i)).first() for i in products_in_cart.split(",") ] total_cost = sum([product.price for product in products]) unreg_order.total_price = total_cost db_sess.add(unreg_order) db_sess.commit() db_sess.close() session["cart"] = [] return redirect("/") else: return render_template( "reg.html", products_in_cart=products_in_cart, create_order=True, error_text="Ошибка при вводе данных", count_product=count_products) else: return render_template("reg.html", products_in_cart=products_in_cart, create_order=True, error_text="Нужно заполнить все поля!", count_product=count_products) return render_template("reg.html", products_in_cart=products_in_cart, create_order=True, count_product=count_products) return redirect("/")