def removeAmount(request, productArticle, amount): try: userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] thisCart = thisCustomer.getCart() if thisCart == -1: raise("There is no cart belonging to this user or the user is not registered!") currentData = json.loads(thisCart.json) if productArticle not in currentData: raise("There is no such product in this cart!") newAmount = currentData[productArticle] - amount if newAmount < 0: raise("Not enough items!") elif newAmount == 0: currentData.__delitem__(productArticle) else: currentData[productArticle] = newAmount thisCart.json = json.dumps(currentData) thisCart.save() unreserve(productArticle, amount) except Exception as exc: print(exc) return -1
def make_order_view(request, *args, **kwargs): userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] thisCart = thisCustomer.getCart() thisCartJSON = json.loads(thisCart.json) # productsRows, categories = getProductsCatrows() cartProducts = Product.objects.filter(isAvailable=True, article__in=thisCartJSON) repr_cartProducts = [] totalPrice = 0 for cpr in cartProducts: repr_cartProducts.append(repr_product_dct(cpr, request=request)) totalPrice += calcPrice.calc_final_price(cpr, thisCartJSON) myContext = { 'title': 'Оформление заказа', "cartProducts": repr_cartProducts, "thisCart": thisCartJSON, "totalPrice": float(totalPrice), "cartID": request.session._session_key, "isEmpty": len(repr_cartProducts) == 0, "user": thisCustomer.getRepr() } reponseStr = json.dumps(myContext, ensure_ascii=False) return HttpResponse(reponseStr)
def products_view(request, *args, **kwargs): userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({"ok": False, "msg": userData["msg"]})) thisCustomer = userData["user"] queryDict = request.GET filters = {} if 'cat' in queryDict: filters['category'] = queryDict['cat'].lower() productsRows, categories = repr_producstCatrows(filters=filters) myContext = { "title": "Товары", "categories": categories, "products": productsRows, "ok": len(productsRows) > 0, "user": thisCustomer.getRepr() } responseData = json.dumps(myContext, ensure_ascii=False) return HttpResponse(responseData)
def user_cart_view(request, *args, **kwargs): userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] thisCartObj = thisCustomer.getCart() thisCart = json.loads(thisCartObj.json) productsRows, categories = getProductsCatrows() cartProducts = Product.objects.filter(isAvailable=True, article__in=thisCart) repr_cartProducts = [] totalPrice = 0 for cpr in cartProducts: repr_cartProducts.append(repr_product_dct(cpr, request=request)) totalPrice += calcPrice.calc_final_price(cpr, thisCart) print(thisCart, repr_cartProducts) myContext = { "title": "Корзина", "cartProducts": repr_cartProducts, "thisCart": thisCart, "totalPrice": float(totalPrice), "isEmpty": len(repr_cartProducts) == 0, "user": thisCustomer.getRepr() } responseStr = json.dumps(myContext, ensure_ascii=False) return HttpResponse(responseStr)
def process_feedback_view(request, *args, **kwargs): if request.method == "GET": userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse( json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] if True: response = HttpResponse("0") name = request.GET['name'] topic = request.GET['topic'] body = request.GET['body'] email = request.GET['email'] send_fb(name, topic, body, email) thisCustomer.name = f"{name}" thisCustomer.save() return response errorResponse = HttpResponse("-1") errorResponse.status_code = 400 return errorResponse
def clearCart(request): userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] thisCart = thisCustomer.getCart() thisCart.json = "{}" thisCart.save()
def removeFromCart(request, article): userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] thisCart = thisCustomer.getCart() currentData = json.loads(thisCart.json) unreserve(article, currentData[str(article)]) currentData.pop(str(article)) thisCart.json = json.dumps(currentData) thisCart.save() return thisCart.json
def addToCart(request, productArticle, amount): userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] thisCart = thisCustomer.getCart() currentData = json.loads(thisCart.json) productArticle = str(productArticle) # print(productArticle in currentData) newAmount = amount if productArticle in currentData: newAmount += currentData[productArticle] try: pr = Product.objects.get(article=productArticle) except Exception as exc: return -1 print("CCCCC", pr.amount - getReservation(pr.article)) if amount > pr.amount - getReservation(pr.article): print("oh shit") return -1 currentData[productArticle] = newAmount thisCart.json = json.dumps(currentData) thisCart.save() reserve(productArticle, amount) return thisCart.json
def repr_product_dct(product, **kwargs): ''' Only ''' from customers.get import getCustomerForRequest try: request = kwargs['request'] userData = getCustomerForRequest(request) thisCustomer = userData["user"] thisCart = thisCustomer.getCart() cart = json.loads(thisCart.json) print(cart) if product.article in cart: cartPrice = calc_final_price(product, cart) else: cartPrice = -1 except Exception as exc: print("Could not calculate the cartPrice", exc) cartPrice = -1 data = { 'title': str(product.title), 'description': str(product.description), 'category': str(product.category), 'price': str(product.price), 'finalPrice': str(calc_price(product)), "cartPrice": str(cartPrice), 'discount': str(product.discount), 'producer': str(product.producer), 'icon': str(product.icon), 'article': str(product.article), 'totalAmount': product.amount, 'availableAmount': product.amount - getReservation(product.article), 'isAvailable': product.isAvailable } return data
def product_detail_view(request, *args, **kwargs): userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({"ok": False, "msg": userData["msg"]})) thisCustomer = userData["user"] # thisCart = thisCustomer.getCart() queryDict = request.GET requestedArticle = int(request.GET['article']) requestedObject = Product.objects.get(article=requestedArticle) # requestedObject.amount -= getReservation(requestedArticle) # TODO: remove and deal with availableAmount on frontend myContext = { "title": f"Купить {requestedObject.title}", "pr": repr_product_dct(requestedObject), "user": thisCustomer.getRepr() } # requests.get(f"https://api.telegram.org/bot1225466990:AAHeSxZ66mt1sOD_0ojhUf4EpbxoVK06TAY/sendMessage?chat_id=@dchadm&text=Кто-то%20заказал:%20{requestedObject.title}") responseStr = json.dumps(myContext, ensure_ascii=False) # return render(request, "product_details.html", myContext) return HttpResponse(responseStr)
def complete_order(request, *args, **kwargs): print(request.get_host()) queryDict = request.POST if not request.method == "POST": return HttpResponse(f"Wrong request method '{request.method}'! Expected 'POST'") try: userData = getCustomerForRequest(request) if not userData["ok"]: return HttpResponse(json.dumps({ "ok": False, "msg": userData["msg"] })) thisCustomer = userData["user"] thisCart = thisCustomer.getCart() cartJSON = thisCart.json cartData = json.loads(cartJSON) if len(cartData) < 1: return HttpResponse(f"Вы пытаетесь оформить пустой заказ. Так нельзя :)") name = queryDict['name'] phone = queryDict['phone'] email = queryDict['email'] except Exception as exc: print(exc) return HttpResponse(f"Not enough request data!\n\n{exc}") try: comment = queryDict['comment'] except: comment = "—" print("No comment! =)") # Create OrderObject: OrderObject = Order(json=cartJSON, name=name, email=email) # Clear the user's cart: try: clearCart(request) except Exception as exc: return HttpResponse(f"Can not clear your cart because of the above exception:\n{exc}") OrderObject.save() request.session['name'] = f"{name}" print(f"{request.get_host()}/remove_order?oid={OrderObject.id}") sendOrderNotification(name, cartData, OrderObject.id, phone, email, comment, f"{request.get_host()}/remove_order?oid={OrderObject.id}", f"{request.get_host()}/recieve_order?oid={OrderObject.id}") sendThanksForOrderEmail(OrderObject) # return HttpResponseRedirect(f'/thankyou/?oid={OrderObject.id}') responseData = { "ok": True, "user": thisCustomer.getRepr() } responseStr = json.dumps(responseData, ensure_ascii=False) return HttpResponse(responseStr)