def add_many(): data = request.get_json() item_input = data['item'] amount_input = data['amount'] user_id = User.get_by_id(get_jwt_identity()) cart = Cart(user=user_id, item=item_input, amount=amount_input) cart_check = Cart.get_or_none(Cart.user == user_id, Cart.item == item_input, Cart.payment_status == False) if item_input == "": return jsonify({ 'message': 'All fields required', 'status': 'failed' }), 400 elif cart_check: cart_check.update(amount=Cart.amount + amount_input, updated_at=datetime.datetime.now()).where( Cart.user_id == user_id, Cart.item_id == item_input, Cart.payment_status == False).execute() return jsonify({ 'message': 'Item already exists, added to amount', 'status': 'success' }), 200 elif cart.save(): return jsonify({ 'message': 'Item added successfully', 'status': 'success' }), 200 else: return jsonify({"message": "Uncaught error", "status": "Failed"}), 400
def post(odata): curr_session = db_session() tobj = CrudObj(**odata) curr_session.add(tobj) curr_session.commit() tobjstr = tobj.dump() return tobjstr, 201 #note: tobj.dump() here causes {} return, not sure why?!?
def edit(): productid = request.form.get('pid') cartid = request.cookies.get('cart') quantity = request.form.get('qty') cart = Cart() ret = cart.edit((quantity, cartid, productid)) return str(ret)
def close(paydesk_id=None, cart_id=None): try: dbs = db_session() oldCart = dbs.query(Cart).filter(Cart.paydesk_id == paydesk_id, Cart.status == "OPEN").one_or_none() oldCart.status = "CLOSED" msg = { "msgtype": "INFO", "msgid": 0, "text": "Cart closed", "info": "Cart %d closed" % (oldCart.id) } newCart = Cart(paydesk_id=paydesk_id, status="OPEN") ret = dbs.add(newCart) dbs.commit() articles = dbs.query(Article).filter( Article.paydesk_id == paydesk_id, Article.cart_id == newCart.id).order_by( Article.scantime.desc()).all() return { "Msg": msg, "Cart": newCart.dump(), "Articles": [p.dump() for p in articles] }, 200 except Exception as ex: msg = { "msgtype": "INFO", "msgid": 0, "text": "Cart closed", "info": "Cart %d closed" % (oldCart.id) } return {"Msg": msg}, 400
def checkout(): current_id = User.get_by_id(get_jwt_identity()) not_enough_items = Cart.select().join(Item).where( Cart.user == current_id, Cart.payment_status == False, Cart.amount > Item.stock) if len(not_enough_items) > 0: return jsonify("Message: There are not enough of these items in stock", [{ "item": { "id": item.item.id, "stock": item.item.stock, "color": item.item.color, "name": item.item.name, "product_type": item.item.product_type, "image": item.item.image_url, "price": item.item.price, "size": item.item.size } } for item in not_enough_items], "Please reduce amount", {"Status": "Failed"}), 400 else: print(request.form.get('paymentMethodNonce')) data = request.get_json() amount_input = data['amount'] pmNonce_input = data['paymentMethod'] result = gateway.transaction.sale({ "amount": amount_input, "payment_method_nonce": pmNonce_input, "options": { "submit_for_settlement": True } }) Payment(user=current_id, Braintree_Transaction_id=result.transaction.id, Total_amount=result.transaction.amount).save() cart_amount = Cart.select(Cart.amount).where(Cart.item_id == Item.id) item = (Item.update(stock=Item.stock - cart_amount).where( Item.id.in_( Cart.select( Cart.item_id).where((Cart.user == current_id) & (Cart.payment_status == False))))) item.execute() Cart.update(payment_status=True).where( Cart.user == current_id, Cart.payment_status == False).execute() print(result.transaction) print(result.transaction.id) print(result.transaction.amount) send_after_payment(current_id.email) return jsonify({'message': 'Success', 'status': 'success'}), 200
def delete_by_name(): data = request.get_json() item_name = data['name'] name = Item.select().where(Item.name == item_name) cart_unpaid = Cart.delete().where((Cart.item.in_(name)) & (Cart.payment_status == False)) cart_paid = Cart.update(item_id=None).where((Cart.item.in_(name)) & (Cart.payment_status == True)) cart_paid.execute() cart_unpaid.execute() item = Item.get_or_none(Item.name == item_name) item.delete().where(Item.name == item_name).execute() return jsonify({"name": item.name, "message": ["item is deleted"]})
def add(): cart = Cart() id = request.cookies.get('cart') if id == None: id = randomString(16) response = make_response(redirect('/cart')) response.set_cookie('cart', id, max_age= 3600 * 24 * 30) else: response = redirect('/cart') productid = request.form.get('productid') quantity = request.form.get('quantity') cart.add((id, productid, quantity)) return response
def create_cart(item, user): new_cart = Cart(user_id=item['user_id'], item_id=item['id'], date_created=datetime.utcnow(), last_modified=datetime.utcnow()) try: new_cart.save() message = 'Cart saved successfully' return message, 200 except Exception as e: return str(e), 400 return 'Cart created and items added' # Test code - remove later
def add_to_cart(self, request): if request.method == 'POST': product_id = request.form['product_id'] amount = request.form['quantity'] product_to_cart = Product.query.filter( Product.id == product_id).first() if product_to_cart is not None: try: self.cart_main.add(product_id, amount) except KeyError: self.cart_main = Cart() self.cart_main.add(product_id, amount) return self.cart()
def index(): id = request.cookies.get('cart') if id != None: cart = Cart() a = cart.getCarts(id) sum = 0 b = [] for i in a: b.append(i[2]*i[4]) for u in b: sum += u return render_template('cart/index.html', arr = a, sum = sum) return redirect("/")
def new_cart(): current_user = User.get_by_id(get_jwt_identity()) if current_user: name = request.form.get("name") ingredient = Ingredient.get(name=name) quantity = request.form.get("quantity") amount = int(quantity)*ingredient.price cart = Cart(quantity=quantity, amount=amount, user_id = current_user.id, ingredient_id = ingredient.id) if cart.save(): return jsonify({"message" : "Ingredient has been successfully added into cart!"}) else: return jsonify({"message": "Ingredient exists in cart already!"}) else: return error
def order(self, request): if request.method == 'POST': print(request.form) delivery_type = request.form['delivery-type'] try: orders = self.cart_main.getUnique() ordered_products = [] for order in orders: db_product = Product.query.filter( Product.id == order).first() order_amount = self.cart_main.countProduct(order) ordered_products.append( Prod(db_product.name, order_amount, db_product.price)) sum = 0 for product in ordered_products: db_product = Product.query.filter( Product.name == product.name).first() sum = sum + db_product.price * product.amount if product.amount > db_product.amount: raise Exception("Przekroczyłeś produkty w magazynie") for product in ordered_products: db_product = Product.query.filter( Product.name == product.name).first() db_product.amount = db_product.amount - product.amount print(db_product.amount) db_session.add(db_product) db_session.commit() self.cart_main = Cart() return render_template('order_result.html', price=sum, avg_rating=self.avg_rating) except KeyError: print('error1') except Exception as e: self.cart_main = Cart() return render_template( 'template.html', title= "Nie można stworzyć zamówienia, przekroczyłeś liczbę produktów w magazynie", avg_rating=self.avg_rating) return render_template('order_form.html', title='Formularz zamówienia', avg_rating=self.avg_rating)
def test_total_voucher(self): product_a = Product(sku='prod-a', name='Producto A') product_a.set_pricing(country_code='ES', price=50., discount=0.1) product_b = Product(sku='prod-b', name='Producto B') product_b.set_pricing(country_code='ES', price=20., discount=0.) cart = Cart() cart.apply_voucher(code='promo5', amount=5., min_amount=90.) cart.add_item(product=product_a, quantity=1) cart.add_item(product=product_b, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 65.0) cart.add_item(product=product_a, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 105.0)
def opencart(paydesk_id=None): try: msg = { "msgtype": "ERROR", "msgid": 2, "text": "Attempt to open cart", "info": "unexpected error" } if paydesk_id is None: raise Exception_InvalidPaydesk() dbs = db_session() cart = dbs.query(Cart).filter(Cart.paydesk_id == paydesk_id, Cart.status == "OPEN").one_or_none() if cart == None: cart = Cart(paydesk_id=paydesk_id, status="OPEN") ret = dbs.add(cart) dbs.commit() msg = { "msgtype": "INFO", "msgid": 0, "text": "Cart created", "info": "Cart %d created" % (cart.id) } else: msg = { "msgtype": "INFO", "msgid": 1, "text": "Cart re-opend", "info": "Cart %d reopend" % (cart.id) } articles = dbs.query(Article).filter( Article.paydesk_id == paydesk_id, Article.cart_id == cart.id).order_by( Article.scantime.desc()).all() return { "Msg": msg, "Cart": cart.dump(), "Articles": [p.dump() for p in articles] }, 200 except Exception as ex: msg = { "msgtype": "ERROR", "msgid": 0, "text": "Severe Error", "info": "" } return msg, 400
def paid_item(): current_id = User.get_by_id(get_jwt_identity()) carts = Cart.select().where(Cart.user == current_id, Cart.payment_status == True) return jsonify([{ "user": { "id": cart.user.id, "username": cart.user.username }, "cart": { "id": cart.id, "amount": cart.amount }, "item": { "id": cart.item.id, "color": cart.item.color, "name": cart.item.name, "product_type": cart.item.product_type, "image": cart.item.image_url, "price": cart.item.price, "size": cart.item.size }, "payment": { "id": cart.payment.id, "Braintree_id": cart.payment.Braintree_Transaction_id, "Total paid": cart.payment.Total_amount } } for cart in carts])
def delete_users_cart(cart_id): try: cart = Cart.get(id=cart_id) # throws an exception if the user is not the user of the queried cart try: if not cart.user_is_owner(current_user.id): raise ResourceAccessDenied() except ResourceAccessDenied as e: return e.get_json_response() # deletes the cart the user is verified as the carts user cart.delete_instance() return jsonify(data={}, status={ 'code': 204, 'message': 'Resource deleted successfully.' }) except DoesNotExist: return jsonify(data={}, status={ 'code': 404, 'message': 'Resource does not exist.' })
def show_users_cart(cart_id): try: cart = Cart.get(id=cart_id) print(cart.food_items) # throws an exception if the user is not the user of the cart try: if not cart.user_is_owner(current_user.id): raise ResourceAccessDenied() except ResourceAccessDenied as e: return e.get_json_response() cart_dict = model_to_dict(cart) del cart_dict['user']['password'] return jsonify(data=cart_dict, status={ 'code': 200, 'message': 'Successfully found resource.' }) except DoesNotExist: return jsonify(data={}, status={ 'code': 404, 'message': 'Resource does not exist.' })
def get_total_price_of_items(cart_id): try: # get instance of the specific cart that the user is user_cart_instances = (Cart.select().where( Cart.user_id == current_user.id)) # convert them into dictionaries user_cart_instances_dicts = [ model_to_dict(carts) for carts in user_cart_instances ] # get the prices price_list = [] for cart in user_cart_instances_dicts: price_list.append(cart['product_id']['price']) # return success return jsonify(data=price_list, status={ "code": 200, "message": "Success getting all the carts" }), 200 except models.DoesNotExist: # return the error return jsonify(data={}, status={ "code": 401, "messsage": "Error getting this resource" }), 401
def create_food_item(): data = request.get_json() # tries to get the users cart, exception thrown if users cart doesnt exist try: cart = Cart.get(user=current_user.id) except DoesNotExist: return jsonify( data={}, status={ 'code': 404, 'message': 'Resource does not exist.' } ) # adds the users cart to the dictionary because FoodItem needs a cart id to be created data['cart'] = cart.id food_item = FoodItem.create(**data) food_item_dict = model_to_dict(food_item) return jsonify( data=food_item_dict, status={ 'code': 201, 'message': 'Successfully created resource.' } )
def add_to_cart(product_id, quantity): cart = Cart.get_current() cart.add_product(product_id, quantity) response = make_response() response.set_cookie('cart', cart.jsonified_data) flash("Add succeeded!", 'success') return response
def _fetchComplementingCarts(self, cart_ids): """ Fetches complementing carts to given cart_ids related to all carts in DB. """ carts = [self._fetchCart(cart_id) for cart_id in cart_ids] all_carts = Cart.objects() return [cart for cart in all_carts if cart not in carts]
def post() -> Response: """ POST response method for creating user. :return: JSON object """ data = request.get_json() usercart = Cart().save() output = {'id': str(usercart.id)} y = {"cartId": str(usercart.id)} print('usercart') print(usercart.id) print(usercart.products) print('data') print(data) data.update(y) print('data') print(data) post_user = Users(**data) try: post_user.save() except NotUniqueError as exc: return {'message': "Email Id already exits!!"}, 400 output = {'id': str(post_user.id)} return jsonify({'result': output})
def _fetchCart(self, cart_id): """ Fetches cart by given ID. """ try: return Cart.objects(cart_id=cart_id).get() except: return None
def _fetchCart(self, cart_id): """ Fetches cart by given ID. """ try: return Cart.objects(cart_id=str(cart_id)).get() except: return None
def delete_by_id(): data = request.get_json() item_id = data['id'] item = Item.get_or_none(Item.id == item_id) cart = Cart.delete().where(Cart.item_id == item_id, Cart.payment_status == False) cart.execute() item.delete_instance() return jsonify({"id": item.id, "message": ["item is deleted"]})
def remove_from_cart(product_id): cart = Cart.get_current() cart.remove_product(product_id) response = make_response() response.set_cookie('cart', cart.jsonified_data) flash("Remove succeeded!", 'success') return response
def match(): current_id = User.get_by_id(get_jwt_identity()) # carts = Cart.select().where( # Cart.user == current_id, Cart.payment_status == False) # Cart.update({Cart.item_id.stock: '20'}).where(Cart.select(Item.id).join(Item).where( # Cart.user == current_id, Cart.payment_status == False)).execute() # Item.update(stock=20).where(Item.select().join(Cart).where( # (Cart.user == current_id) & (Cart.payment_status == False))).execute() cart = Cart.select(Cart.amount).where(Cart.item_id == Item.id) item = (Item.update(stock=Item.stock - cart).where( Item.id.in_( Cart.select( Cart.item_id).where((Cart.user == current_id) & (Cart.payment_status == False))))) item.execute() return jsonify({"hello": "hello"})
def delete_cart(): current_user = User.get_by_id(get_jwt_identity()) if current_user: delete = Cart.delete().where(Cart.user_id==current_user.id) delete.execute() return jsonify({"data":"Ingredient has been removed from cart!"}) else: return error
def show_cart(): # if request.session.user is None: # return redirect(url_for('home.login', next=request.url)) cart = Cart.get_current() products = cart.products if request.method == 'POST': pass return render_template('sites/shop/cart.html', products=products, cart=cart)
def checkout(): cart = Cart.get_current() oi = cart oi.data['total'] = cart.sum_value oi = oi.jsonified_data merchant_publickey = get_key(CertificateOwner.MERCHANT, CertificateType.MERCHANT)['public_key'] paymentgateway_publickey = get_key(CertificateOwner.GATEWAY, CertificateType.GATEWAY)['public_key'] products = cart.products return render_template('sites/shop/checkout.html', products=products, cart=cart, oi=oi, kum=merchant_publickey, kupg=paymentgateway_publickey)
def create_users_cart(): new_cart = Cart.create(user=current_user.id) new_cart_dict = model_to_dict(new_cart) del new_cart_dict['user']['password'] return jsonify(data=new_cart_dict, status={ 'code': 201, 'message': 'Successfully created resource.' })
def approve(self): carts = Cart() c = carts.find_one(_id=self.cart_id) c.owner = self.name c.save() self.collection.remove(cart_id=self.cart_id)
def current_state_of_carts(): carts = Cart.objects() return jsonify(title='As of {}'.format(datetime.now()), msg=[cart.toMinimalJson() for cart in carts])