def cart(request): if request.method == 'POST': print("request.POST AFTER ", request.POST) product_tittle = request.POST['tittle'] product_price = request.POST['price'] product_sale = request.POST['sale'] product_quantity = request.POST['quantity'] product_image = request.POST['image'] # send_mail( # 'New Order', # 'There has been an inquiry for ' + product_tittle + # '. ', "Price " + product_price + # '*****@*****.**', # ["*****@*****.**", '*****@*****.**'], # fail_silently=False # ) order = Orders(tittle=product_tittle, price=product_price, sale=product_sale, quantity=product_quantity, photo_main=product_image) order.save() orders = Orders.objects.all() context = {"orders": orders} messages.success( request, 'Your request has been submitted, a realtor will get back to you soon' ) return render(request, 'pages/dashboard.html', context) else: return render(request, 'pages/cart.html')
def order(request): context = { "pizzas": Pizza.objects.all(), "pizzasize": PizzaSize.objects.all(), "pizzatoppingsclass": PizzaToppingsClass.objects.all(), "pizzastyles": PizzaStyle.objects.all(), "toppings": PizzaTopping.objects.all(), "subs": Subs.objects.all(), "substoppings": SubsTopping.objects.all(), "salads": Salad.objects.all(), "pastas": Pasta.objects.all(), "dinnerplatters": DinnerPlatters.objects.all(), } if request.method == 'GET': return render(request, "orders.html", context) price = request.POST['price'] items = request.POST['items'] user = request.user address = request.user.address order = Orders(user=user, items=items, total=price, address=address) order.save() # context = { # "orders":Orders.objects.filter(user=user), # "address":Address.objects.filter(user=request.user), # } return render(request, "complete.html", context)
def Checkout(request): global s y = Cart.objects.filter(use_name=request.user) print(y) t = 0 for i in y: t += (i.product.price * i.quantity) items = {'items': y, 'total': t} if request.method == "POST": # items_json = JSONField() name = request.POST.get('name', '') email = request.POST.get('email', '') address1 = request.POST.get('address1', '') address2 = request.POST.get('address2', '') city = request.POST.get('city', '') state = request.POST.get('state', '') zip_code = request.POST.get('zip_code', '') phone = request.POST.get('phone', '') count = 0 for item in y: count = count + 1 z = Product.objects.filter(name=item.product.name, artisan_id=item.product.artisan_id, category=item.product.category) print(z) order = Orders(name=name, user_name=request.user.username, email=email, address=str(address1) + " " + str(address2), city=city, state=state, zip_code=zip_code, phone=phone, product=z[0], quantity=item.quantity, net_price=z[0].price * item.quantity) order.save() if count == 1: x = order.order_id m = Map(user_name=request.user, start=x, count=count, amount=t) m.save() param_dict = { 'MID': 'MQUWBT37855796215302', 'ORDER_ID': str(m.ord_id), 'TXN_AMOUNT': str(t), 'CUST_ID': email, 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL': 'http://localhost:8000/handlerequest/', } param_dict['CHECKSUMHASH'] = Checksum.generate_checksum( param_dict, MERCHANT_KEY) return render(request, 'handy/paytm.html', {'param_dict': param_dict}) # return redirect(reverse('payment_process')) return render(request, 'handy/checkout.html', items)
def update_order(order_id): order = Orders.query.get(order_id) if request.method == 'POST': barcode = request.form.getlist('item_bar[]') qua = request.form.getlist('item_quantity[]') name = request.form.getlist('item_name[]') total = request.form.getlist('total[]') price = request.form.getlist('price[]') total_amount = request.form.get('total_amount') deleteorder(order_id) for n, q in zip(barcode, qua): product = Products.query.filter_by(barcode=n).first() if product.quantity > 0: product.quantity = product.quantity - int(q) else: print("you do not have this much of quantity", n) db.session.commit() add = Orders(total_amount=total_amount, user_order=current_user) db.session.add(add) db.session.commit() for q, p, t, n, b in zip(qua, price, total, name, barcode): ord = Orders_items(barcode=b, quantity=q, name=n, price=p, total=t, Orders_items=add) db.session.add(ord) db.session.commit() return redirect(url_for('manageorder')) return render_template('update_order.html', order=order.orders, order_amount=order)
def post(self, request, *args, **kwargs): """ 微信支付回调请求 :param request: :return: """ success_message = {'return_code': 'SUCCESS', 'return_msg': 'OK'} fail_message = {'return_code': 'FAIL', 'return_msg': 'SIGN INCORRECT'} success_data = { 'payment_status': 200, 'payment_mode': 2, 'payment_time': now() } fail_data = {'payment_status': 500, 'payment_mode': 2} data_dict = main.anaysize_xml_to_dict(request.body) # 微信支付时返回通讯失败 if data_dict['return_code'] == 'FAIL': return Response(main.make_dict_to_xml(fail_message), status=status.HTTP_200_OK) if not self.is_sign_valid(data_dict): return Response(main.make_dict_to_xml(fail_message), status=status.HTTP_200_OK) return_xml = main.make_dict_to_xml(success_message, use_cdata=True) if data_dict['result_code'] == 'SUCCESS': try: orders = Orders.update_payment_status_by_pay_callback( orders_id=self._orders_id, validated_data=success_data) except: return Response(return_xml, status=status.HTTP_200_OK) else: # 钱包余额更新 (订单收入) result = WalletAction().income(None, orders, gateway='pay_callback') if isinstance(result, Exception): return result else: try: Orders.update_payment_status_by_pay_callback( orders_id=self._orders_id, validated_data=fail_data) except: return Response(return_xml, status=status.HTTP_200_OK) serializer = NativeResponseSerializer(self._wx_instance) serializer.update_wxpay_result(self._wx_instance, data_dict) return Response(return_xml, status=status.HTTP_200_OK)
def to_order(request, product_id): thing = StoreThing.objects.get(id=product_id) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): cd = form.cleaned_data order = Orders( name = cd['name'], s_name = cd['s_name'], p_name = cd['p_name'], address = cd['address'], phone = cd['phone'], email = cd['email'], product = thing, quantity = cd['quantity'], ) order.save() send_mail( u'Поступил новый заказ', get_template('mail/store_thing_add.txt').render( Context({ 's_name': cd['s_name'], 'name': cd['name'], 'p_name': cd['p_name'], 'address': cd['address'], 'phone': cd['phone'], 'email': cd['email'], 'product': thing, 'quantity': cd['quantity'] }) ), '*****@*****.**', ['*****@*****.**']) return HttpResponseRedirect('/thx/') else: form = OrderForm() return render(request, 'catalog/storething_detail.html', { 'order_form': form, 'thing': thing, })
def get_finished_list(self, request, cld): business_orders = Orders.filter_finished_orders_list(request, **cld) verify_orders = VerifyOrders.filter_finished_orders_list( request, set_payment_mode=ORDERS_PAYMENT_MODE['yspay'], **cld) orders_list = business_orders + verify_orders return sorted(orders_list, key=lambda key: key['created'], reverse=True)
def post(self, request, *args, **kwargs): """ 支付宝支付回调请求 :param request: :return: """ success_message = {'return_code': 'SUCCESS', 'return_msg': 'OK'} fail_message = {'return_code': 'FAIL', 'return_msg': 'SIGN INCORRECT'} success_data = { 'payment_status': 200, 'payment_mode': 3, 'payment_time': now() } fail_data = {'payment_status': 500, 'payment_code': 3} form = PreCreateCallbackForm(request.data) if not form.is_valid(): return Response(fail_message, status=status.HTTP_200_OK) self.request_data = _request_data = form.cleaned_data if not self.is_sign_valid(): return Response(fail_message, status=status.HTTP_200_OK) if _request_data['trade_status'] == 'TRADE_SUCCESS': try: orders = Orders.update_payment_status_by_pay_callback( orders_id=self._orders_id, validated_data=success_data) except: return Response(success_message, status=status.HTTP_200_OK) else: # 钱包余额更新 (订单收入) result = WalletAction().income(None, orders, gateway='pay_callback') if isinstance(result, Exception): return result else: try: Orders.update_payment_status_by_pay_callback( orders_id=self._orders_id, validated_data=fail_data) except: return Response(success_message, status=status.HTTP_200_OK) serializer = PreCreateResponseSerializer(self._ali_instance) serializer.update_alipay_result(self._ali_instance, _request_data) return Response(success_message, status=status.HTTP_200_OK)
def post(self, request): user_id = request.session['user_id'] goods_id = request.POST.get('goods_id') goods_num = request.POST.get('goods_num') order = Orders() order.order_id = uuid.uuid4().hex order.time = datetime.datetime.now() order.goods_num = goods_num order.goods = Goods.objects.get(id=goods_id).name order.user = User.objects.get(id=user_id).name order.price = Goods.objects.get(id=goods_id).price * goods_num
def cart(request): if request.method == 'POST': print("request.POST AFTER ", request.POST) product_tittle = request.POST['tittle'] product_price = request.POST['price'] product_sale = request.POST['sale'] product_quantity = request.POST['quantity'] # username = request.POST['username'] product_image = request.POST['image'] ''' user = auth.authenticate(username=username) if user is not None: auth.login(request, user) messages.success(request, 'User logged in') messages.error(request, 'error test') messages.warning(request, 'warning test') else: send_mail( 'New Order', 'Congratulations !! Your order has been accepted, the manager will contact you shortly.' + '\n' + 'Name: ' + username + '; ' + '\n' + 'Order: ' + product_tittle + ';' + '\n' + 'Price: ' + product_price + '. ', "E-Shoper " '*****@*****.**', ["*****@*****.**", '*****@*****.**'], fail_silently=False ) ''' order = Orders(tittle=product_tittle, price=product_price, sale=product_sale, quantity=product_quantity, photo_main=product_image) order.save() orders = Orders.objects.all() context = {"orders": orders} messages.success( request, 'Your request has been submitted, a manager will get back to you soon' ) return render(request, 'pages/dashboard.html', context) else: return render(request, 'pages/cart.html')
def save_order1(request, step=1): """Save order from template with AJAX""" if request.method != "POST": result = {"result": "ERROR", "msg": "Wrong request method"} return http.HttpResponse(json.dumps(result), content_type="application/json") try: id = int(request.POST.get("id", 0)) # Если редактруем созданный заказ except (TypeError, ValueError): id = 0 draw = request.POST.get("count", None) # количество в заказ if not draw: draw = 0 time = datetime.datetime.now() templ = OrderTemplate.objects.get(id=id) price = templ.price templ.pk = None templ.is_template = False templ.name = str(time) + " " + templ.name templ.price = None templ.save() # взяли шаблон по id, обрали признак шаблона и скопировали. order = Orders(template=templ) order.draw = draw order.cost = float(draw) * float(price) order.save() # привязали заказ к шаблону, посчитали цену, записали. Теперь нужны остальные данные и всё. step = 2 result = {"result": "OK", "id": order.id, "msg": "Changes are saved", "url": reverse("edit-templ", args=[order.pk, 3])} return HttpResponse(json.dumps(result), content_type="application/json")
def cart(request): if request.method == 'POST': print('*******************', request.POST) product_tittle = request.POST['tittle'] product_price = request.POST['price'] product_sale = request.POST['sale'] product_quantity = request.POST['quantity'] product_image = request.POST['image'] if request.user.is_authenticated: email = User.objects.filter(is_active=True).values_list('email', flat=True) print('--------------------', email, '----------') # send_mail( # 'New Order','email '+request.user.email+ # 'There has been an inquiry for ' + product_tittle + # '. ', "Price " + product_price + # '*****@*****.**', # ["*****@*****.**", '*****@*****.**'], # fail_silently=False # ) order = Orders(tittle=product_tittle, price=product_price, sale=product_sale, quantity=product_quantity, photo_main=product_image) order.save() orders = Orders.objects.all() context = {"orders": orders} messages.success( request, 'Your request has been submitted, a realtor will get back to you soon' ) return render(request, "pages/dashboard.html", context) else: return render(request, "pages/cart.html")
def insert(): barcode = request.form.getlist('item_bar[]') qua = request.form.getlist('item_quantity[]') name = request.form.getlist('item_name[]') total = request.form.getlist('total[]') price = request.form.getlist('price[]') total_amount = request.form.get('total_amount') for n, q in zip(barcode, qua): product = Products.query.filter_by(barcode=n).first() if product.quantity > 0: product.quantity = product.quantity - int(q) else: print("you do not have this much of quantity", n) db.session.commit() medicine_list = [barcode, qua, name, price] with open("MedicinesRequired.csv", "a") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(medicine_list) s3 = boto3.resource('s3', aws_access_key_id='AKIAU56YN4TZRNNHKYLU', aws_secret_access_key='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') s3.meta.client.upload_file( 'MedicinesRequired.csv', 'ramjan', 'MedicinesRequired.csv') # conn_string = "dbname='***' port='5439' user='******' password='******' host='mycluster.***.redshift.amazonaws.com'" # to_table = "" # fn = "" # AWS_ACCESS_KEY_ID = "AKIAU56YN4TZRNNHKYLU" # AWS_SECRET_ACCESS_KEY = "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" # delim = "," # quote = "" # gzip = "gzip" # # connect to Redshift (database should be open to the world) # con = psycopg2.connect(conn_string) # sql = """COPY %s FROM '%s' credentials # 'aws_access_key_id=%s; aws_secret_access_key=%s' # delimiter '%s' FORMAT CSV %s %s; commit;""" % # (to_table, fn, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, delim, quote, gzip) add = Orders(total_amount=total_amount, user_order=current_user) db.session.add(add) db.session.commit() for q, p, t, n, b in zip(qua, price, total, name, barcode): ord = Orders_items(barcode=b, quantity=q, name=n, price=p, total=t, Orders_items=add) db.session.add(ord) db.session.commit() return jsonify({'data': 'ok'})
def new_order(request): data = request.POST try: address = data['Address'] except Exception: address = '虚拟商品不写地址' # 添加订单 order = Orders( take_name=data['Name'], user_name=request.user.username, goods=data['Goods'], goods_id=data['GoodsID'], email=data['Email'], phone=data['Phone'], wechart=data['WeChart'], address=address, discount=data['Discount'], real_cost=data['Real'], image_id=int(data['Image']), tips=data['Tips'], cost=data['Cost'], status=0, ) # # 积分 消费 # cost = Cost( # user_name=request.user.username, # goods=data['Goods'], # goods_id=data['GoodsID'], # change_points=(int(data['Cost']) * -1), # tips='礼品兑换', # ) order.save() # cost.save() return redirect('/accounts/')
def seller_account_post_save_reciever(sender, instance, *args, **kwargs): user = instance.email password = instance.password data = AmzScraper(year=2018, user=user, password=password, cache_timeout=21600).run() print("Done") for each in data: order_instance = Orders(user_seller=instance, orderData=each['order-data'], orderNumber=each['order-number'], orderStatus=each['order-status'], shippingAddress=each['shipping-address'], productName=each['product-name'], productImage=each.get('product-image'), trackingID=each['trackingID'][12:]) order_instance.save() try: tStatus = each.get('tracking-status') TrackingDetails.objects.create(order_instance, tStatus) except: print("No tracking ID")
def post(self, request, *args, **kwargs): form = SyncOrdersDataForm(request.data) if not form.is_valid(): return Response({'Detail': form.errors}, status=status.HTTP_400_BAD_REQUEST) cld = form.cleaned_data is_valid, error_message = self.is_request_data_valid(**cld) if not is_valid: return Response({'Detail': error_message}, status=status.HTTP_400_BAD_REQUEST) orders_data = self.get_perfect_orders_data(cld['orders_data']) for item in orders_data: object_data = Orders.make_orders_by_dishes_ids( request, dishes_ids=item['dishes_ids'], created=item['created']) if isinstance(object_data, Exception): return Response({'Detail': object_data.args}, status=status.HTTP_400_BAD_REQUEST) serializer = OrdersSerializer(data=object_data) if not serializer.is_valid(): return Response({'Detail': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) validated_data = { 'payment_status': ORDERS_PAYMENT_STATUS['paid'], 'payment_mode': ORDERS_PAYMENT_MODE['cash'] } try: instance = serializer.save() serializer.update_payment_status(instance, validated_data) except Exception as e: return Response({'Detail': e.args}, status=status.HTTP_400_BAD_REQUEST) return Response({'Result': True}, status=status.HTTP_201_CREATED)
def get_dishes_list(self, request, **kwargs): key = self.get_dishes_list_key(request) dishes_list = self.handle.lrange(key) if not dishes_list: _dishes_list = Dishes.filter_details(request, **kwargs) # 用最近一个月的菜品销量来排序商户的菜品列表 orders_filter = { 'start_created': now() - datetime.timedelta(days=30), 'payment_status': 200 } orders_list = Orders.get_objects_list(request, **orders_filter) sale_list = self.get_dishes_list_with_sale( dishes_list=_dishes_list, orders_list=orders_list) self.set_dishes_list(request, sale_list) return sale_list if kwargs.get('classify', 0) != 0: new_list = [] for dishes in dishes_list: if dishes['classify'] == kwargs['classify']: new_list.append(dishes) return new_list return dishes_list
def insert(): barcode = request.form.getlist('item_bar[]') qua = request.form.getlist('item_quantity[]') name = request.form.getlist('item_name[]') total = request.form.getlist('total[]') price = request.form.getlist('price[]') total_amount = request.form.get('total_amount') for n,q in zip(barcode,qua): product = Products.query.filter_by(barcode=n).first() if product.quantity > 0 : product.quantity = product.quantity - int(q) else : print("you do not have this much of quantity",n) db.session.commit() add = Orders(total_amount=total_amount,user_order=current_user) db.session.add(add) db.session.commit() for q,p,t,n,b in zip(qua,price,total,name,barcode): ord = Orders_items(barcode=b,quantity=q,name=n,price=p,total=t,Orders_items=add) db.session.add(ord) db.session.commit() return jsonify({'data':'ok'})
def post(self, request, *args, **kwargs): """ :param request: :param args: :param kwargs: {'dishes_ids': [{'dishes_id': '', 'count': '', }, ... ], } :return: """ form = OrdersInputForm(request.data) if not form.is_valid(): return Response(form.errors, status=status.HTTP_400_BAD_REQUEST) cld = form.cleaned_data stream = BytesIO(cld['dishes_ids']) dishes_ids = JSONParser().parse(stream) object_data = Orders.make_orders_by_dishes_ids(request, dishes_ids=dishes_ids) if isinstance(object_data, Exception): return Response({'Detail': object_data.args}, status=status.HTTP_400_BAD_REQUEST) serializer = OrdersSerializer(data=object_data) if serializer.is_valid(): serializer.save() orders_detail = self.get_orders_detail(serializer.instance) res_serializer = OrdersDetailSerializer(data=orders_detail) if not res_serializer.is_valid(): return Response({'Detail': res_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) return Response(res_serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def handle(self, *args, **options): s = Addresess() s.autor = User.objects.get(id=1) s.city = "Montreal" s.country = "CA" s.zip_code = "2003" s.first_name = "mike" s.last_name = "thonson" s.address_line_1 = "montreal canada" s.address_line_2 = "Canada" s.address_type = "shipping" s.save() b = Addresess() b.autor = User.objects.get(id=1) b.city = "Montreal" b.country = "CA" b.zip_code = "2003" b.first_name = "mike" b.last_name = "thonson" b.address_line_1 = "montreal canada" b.address_line_2 = "Canada" b.address_type = "billing" b.save() p = PaymentMethod() p.amount = 100.00 p.currency = "USD" p.payment_method = "paypal" p.save() pf = PaymentMethodFields() pf.key = "first_name" pf.value = "mike" pf.payment = p pf.save() pf = PaymentMethodFields() pf.key = "last_name" pf.value = "thonson" pf.payment = p pf.save() pf = PaymentMethodFields() pf.key = "city" pf.value = "FL" pf.payment = p pf.save() pf = PaymentMethodFields() pf.key = "country" pf.value = "US" pf.payment = p pf.save() pf = PaymentMethodFields() pf.key = "email" pf.value = "*****@*****.**" pf.payment = p pf.save() for o in range(1, 100): orders = Orders() orders.status = "approved" orders.autor = User.objects.get(id=1) orders.billing_addresss = b orders.shipping_addresss = b orders.payment_method = p orders.save() item = OrderShippingItem() item.order = orders item.product = PostItem.objects.get(id=1) item.price = 1.00 item.qty = 15 item.save() pass
def get_orders_detail(self, instance): return Orders.make_instances_to_dict(instance)[0]
def handle(self, *args, **options): microsoft_customers = '/tmp/customers.json' migration_csvs = os.path.join(settings.BASE_DIR, 'migrations') order_csv = os.path.join(migration_csvs, 'orders.csv') microsoft_customers = '/tmp/customers.json' existing_microsoft_domains = os.path.join(migration_csvs, 'microsoft_domains.csv') m = MicrosoftBase() headers = m.getAccessHeaders() """headers = { 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6InowMzl6ZHNGdWl6cEJmQlZLMVRuMjVRSFlPMCIsImtpZCI6InowMzl6ZHNGdWl6cEJmQlZLMVRuMjVRSFlPMCJ9.eyJhdWQiOiJodHRwczovL2dyYXBoLndpbmRvd3MubmV0IiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2MyNjFhMTktM2VmZS00ZTZjLTg5ZGEtZDBlNmVhOTc0MzZkLyIsImlhdCI6MTQ5NTA2Nzc5NSwibmJmIjoxNDk1MDY3Nzk1LCJleHAiOjE0OTUwNzE2OTUsImFpbyI6IlkyWmdZT0N1MVh0NVdlS2Q0Y2RKTHNhRyszNGxBQUE9IiwiYXBwaWQiOiI5MzFhYTEzNy1mOGQ4LTQ3ZWMtYjZmNS04Y2ZlNzQ5ZWEyOGEiLCJhcHBpZGFjciI6IjEiLCJpZHAiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83YzI2MWExOS0zZWZlLTRlNmMtODlkYS1kMGU2ZWE5NzQzNmQvIiwib2lkIjoiODk5YTg4NTUtMWU0Mi00OTVkLThlOTEtOGI0ODFkYTc3M2JkIiwicm9sZXMiOlsiRGlyZWN0b3J5LlJlYWQuQWxsIiwiRGlyZWN0b3J5LlJlYWRXcml0ZS5BbGwiLCJEb21haW4uUmVhZFdyaXRlLkFsbCJdLCJzdWIiOiI4OTlhODg1NS0xZTQyLTQ5NWQtOGU5MS04YjQ4MWRhNzczYmQiLCJ0aWQiOiI3YzI2MWExOS0zZWZlLTRlNmMtODlkYS1kMGU2ZWE5NzQzNmQiLCJ1dGkiOiJLTFZHMThwNHBreTFnaGxCS1I4Q0FBIiwidmVyIjoiMS4wIn0.oW6di_XNbT_ZQWNXWvVp0UaavkGg_JEQany5jog5ETeM_xWaRhAdv2L20FIIQ0H82N4yiHKZGG0N_VuYxU6_-jB4uckv6Y3n2KJnt2tpNtdJlZgbf3mSgLyP4gkOTkMFdRBW_swYAvnU03ZyTCN-eQxoV3n5S0eQkkrm8nCIEA1wcpwo7IWwTswKxIyIq44yM1PxjeIvHBp6P7IBP4Y8rDBaz0dZOWN_J4lpDi2Kr9v0VsGeHbgfkV8Ra3pj8q3uSoGZfe5iZ5yI_mki8JELMFsoMkO02v8-WfUiy_Fq6vkJwGI-0DmgWkX0nwvMsTPjSmInWbYApxvbFnX8_hJvpw', 'Accept': 'application/json', 'Content-Type': 'application/json' }""" customers = json.load(open('/tmp/customer_map.json', 'r')) processed_orders = json.load(open('/tmp/orders.json', 'r')) with open(order_csv, 'r', encoding='latin1') as csvfile: for row in reversed(list(csv.reader(csvfile))): order_status = row[6] if order_status == 'Provision': customer = None try: customer = Customers.objects.get(pk=customers[row[1]]) except: print("Could not find Customer for %s" % (row[1], )) continue # Handle only msft for now vendor = row[11] if vendor == 'MICROSOFT' or vendor == 'Office': if not row[17]: print("Could not find order for order: %s " % (row[2], )) continue if row[17] == 'Microsoft Azure': print("Azure Order: %s" % (row[2], )) pass # Skip for now else: if row[2] in processed_orders: continue # Skip as its already processed print("Processing Order: %s" % (row[2], )) cloud_account_object = CloudAccounts.objects.filter( customer=customer, type='MS', vendor=VendorDetails.objects.get(pk=4)) if not cloud_account_object: print( "Could not find Cloud Account for order: %s" % (row[2], )) continue cloud_account = cloud_account_object.first() if 'tenant_id' not in cloud_account.details: print( "Could not find domain name for Order: %s, Check with Redington" % (row[2], )) continue tenant_id = cloud_account.details['tenant_id'] url = str.format( 'https://api.partnercenter.microsoft.com/v1/customers/{}/subscriptions', tenant_id) subscriptions_out = requests.get(url, headers=headers) if subscriptions_out.status_code == 401: # Reprocess m = MicrosoftBase() headers = m.getAccessHeaders() subscriptions_out = requests.get( url, headers=headers) if subscriptions_out.status_code == 200: subscriptions = json.loads( codecs.decode(subscriptions_out.content, 'utf-8-sig')) items = subscriptions['items'] subscription_available = False for item in items: if item['offerName'] == row[17]: # Insert into Orders, ordersItems and subscriptions subscription_available = True # Check if Order placed, then insert into items existing_order = Orders.objects.filter( order_number=row[2]) if existing_order: # Get Order Reference order_pk = existing_order[0].pk else: # Insert into Order order = Orders() order.order_number = row[2] order.pk = int(row[2][3:]) order.status = 6 order.partner = customer.partner order.customer = customer order.vendor = VendorDetails.objects.get( pk=4) order.total_cost = 0 try: dateVal = datetime.datetime.strptime( row[4], '%d/%m/%y') except: dateVal = datetime.datetime.strptime( row[4], '%d/%m/%Y') order.created_at = dateVal order.created_by = PartnerUserDetails.objects.filter( partner=customer.partner )[0].user order.billing_type = item[ 'billingCycle'] if order.billing_type == 'monthly': order.billing_completed = 0 else: order.billing_completed = 1 order.modified_by_id = PartnerUserDetails.objects.filter( partner=customer.partner )[0].user.pk order.save() order_pk = order.pk # Insert into Order Items orderItem = OrderItems() orderItem.order = Orders.objects.get( pk=order_pk) orderItem.product = Products.objects.get( pk=4) orderItem.quantity = item['quantity'] orderItem.discount = 0 # Check with Redington orderItem.price_per_unit = row[15] orderItem.cost = float( item['quantity']) * float(row[15]) try: dateVal = datetime.datetime.strptime( row[4], '%d/%m/%y') except: dateVal = datetime.datetime.strptime( row[4], '%d/%m/%Y') orderItem.created_at = dateVal orderItem.created_by = PartnerUserDetails.objects.filter( partner=customer.partner)[0].user orderItem.modified_by_id = PartnerUserDetails.objects.filter( partner=customer.partner )[0].user.pk orderItem.save() # Insert into Subscription subscription = Subscriptions() subscription.customer = customer subscription.order = Orders.objects.get( pk=order_pk) subscription.product = Products.objects.get( pk=4) subscription.subscription = item['id'] subscription.creation_date = parse_datetime( item['creationDate']) subscription.ms_order_id = item[ 'orderId'] subscription.name = item['offerName'] subscription.quantity = item[ 'quantity'] subscription.unit_type = item[ 'unitType'] subscription.effective_start_date = parse_datetime( item['effectiveStartDate']) subscription.commitment_end_date = parse_datetime( item['commitmentEndDate']) subscription.auto_renew_enabled = item[ 'autoRenewEnabled'] subscription.status = item['status'] subscription.is_trial = item['isTrial'] subscription.billing_type = item[ 'billingType'] subscription.billing_cycle = item[ 'billingCycle'] subscription.contract_type = item[ 'contractType'] subscription.save() processed_orders[row[2]] = order_pk json.dump( processed_orders, open('/tmp/orders.json', 'w') ) # Write back for further process if not subscription_available: pprint.pprint( "Couldnt find subscription: %s for: %s and order: %s" % (row[17], tenant_id, row[2])) continue else: pprint.pprint( "No subscriptions found for %s for order %s" % (tenant_id, row[2])) continue else: # Handle other vendors (Amazon) pass
def handle(self, *args, **options): migration_csvs = os.path.join(settings.BASE_DIR, 'migrations') existing_azure_accounts = os.path.join(migration_csvs, 'existing_azure_accounts.csv') customers = json.load(open('/tmp/customer_map.json', 'r')) m = MicrosoftBase() headers = m.getAccessHeaders() with open(existing_azure_accounts, 'r', encoding='latin1') as csvfile: for row in list(csv.reader(csvfile)): print("Processing: %s" % (row[5])) customer_id = row[13] reference_number = None if not customer_id: # insert into customers, cloudaccounts customer = Customers() partner = Partner.objects.filter(jba_code=row[11].strip()) if not partner: print("Cannot find partner: %s" % (row[11])) continue else: partner = partner[0] customer.partner = partner customer.company_name = row[5] customer.address = row[5] customer.save() customer_contact1 = CustomerContacts() customer_contact1.customer = customer customer_contact1.name = '' customer_contact1.save() customer_contact2 = CustomerContacts() customer_contact2.customer = customer customer_contact2.name = '' customer_contact2.save() customer_id = customer.id elif not customer_id in customers: print("Cannot find customers: %s" % (customer_id)) continue else: customer = Customers.objects.get(pk=customers[customer_id]) partner = PartnerUserDetails.objects.filter( partner=customer.partner) orders = Orders() if not row[14]: orders.order_number = generate_order_number() else: orders.order_number = row[14] orders.status = 6 orders.customer = customer orders.partner = customer.partner orders.vendor = VendorDetails.objects.get(pk=3) orders.total_cost = 0 orders.created_by = partner[0].user orders.created_at = datetime.datetime.now() orders.modified_by = partner[0].user orders.billing_type = 'annually' orders.billing_completed = 0 orders.save() reference_number = orders.id order_items = OrderItems() order_items.order = orders order_items.product = Products.objects.get( product_sku_code='MS-AZR-0145P') order_items.quantity = 1 order_items.discount = 0 order_items.price_per_unit = 0 order_items.cost = 0 order_items.created_by = partner[0].user order_items.created_at = datetime.datetime.now() order_items.modified_by = partner[0].user order_items.save() cloud_account = CloudAccounts.objects.filter( customer=customer, type='MS', vendor=VendorDetails.objects.get(pk=3)) if not cloud_account.exists(): cloud_account = CloudAccounts() cloud_account.customer = customer cloud_account.vendor = VendorDetails.objects.get(pk=3) cloud_account.type = 'MS' cloud_account.active = True partner = PartnerUserDetails.objects.filter( partner=customer.partner) cloud_account.created_by = partner[0].user cloud_account.created_at = datetime.datetime.now() cloud_account.modified_by = partner[0].user discount = 10 reference_number = orders.order_number if row[8]: discount = row[8] cloud_account.details = { 'active': True, 'tenant_id': row[16], 'domain_name': row[17], 'discount_status': 'Approved', 'standard_discount': discount, 'allow_order': 'Yes', 'reference_number': reference_number } cloud_account.save() # Insert into Subscriptions url = str.format( 'https://api.partnercenter.microsoft.com/v1/customers/{}/subscriptions/{}', row[16], row[15]) subscriptions_out = requests.get(url, headers=headers) if subscriptions_out.status_code == 401: # Reprocess m = MicrosoftBase() headers = m.getAccessHeaders() subscriptions_out = requests.get(url, headers=headers) if subscriptions_out.status_code == 200: subscriptions = json.loads( codecs.decode(subscriptions_out.content, 'utf-8-sig')) # Insert into Subscription subscription = Subscriptions() subscription.customer = customer subscription.order = orders subscription.product = Products.objects.get( product_sku_code='MS-AZR-0145P') subscription.subscription = subscriptions['id'] subscription.creation_date = parse_datetime( subscriptions['creationDate']) subscription.ms_order_id = subscriptions['orderId'] subscription.name = subscriptions['offerName'] subscription.quantity = subscriptions['quantity'] subscription.unit_type = subscriptions['unitType'] subscription.effective_start_date = parse_datetime( subscriptions['effectiveStartDate']) subscription.commitment_end_date = parse_datetime( subscriptions['commitmentEndDate']) subscription.auto_renew_enabled = subscriptions[ 'autoRenewEnabled'] subscription.status = subscriptions['status'] subscription.is_trial = subscriptions['isTrial'] subscription.billing_type = subscriptions['billingType'] subscription.billing_cycle = subscriptions['billingCycle'] subscription.contract_type = subscriptions['contractType'] subscription.save()
def process_view(self, request, view_func, view_args, view_kwargs): current_url = resolve(request.path_info) url_name = current_url.url_name if url_name == 'payment_sucesss': payer_id = request.GET.get('PayerID',None) payment_id = request.GET.get('paymentId',None) if payer_id is not None and payment_id is not None: paypalrestsdk.configure({ "mode": settings.PAYPAL_MODE, "client_id": settings.PAYPAL_CLIENT_ID, "client_secret": settings.PAYPAL_CLIENT_SECRET }) payment = paypalrestsdk.Payment.find( payment_id ) if payment.execute({"payer_id": payer_id}): print("Payment execute successfully") if len(payment.transactions) > 0: params = parse_qs(payment.transactions[0].custom) D = PaymentMethod() D.payment_method = "paypal" D.status = "Aprobbed" D.amount = payment.transactions[0].amount.total D.currency = payment.transactions[0].amount.currency D.save() pf = PaymentMethodFields() pf.payment = D pf.key = "first_name" pf.value = payment.payer.payer_info.first_name pf.save() pf = PaymentMethodFields() pf.payment = D pf.key = "last_name" pf.value = payment.payer.payer_info.last_name pf.save() pf = PaymentMethodFields() pf.payment = D pf.key = "email" pf.value = payment.payer.payer_info.email pf.save() o = Orders() o.status = "pending" o.payment_method = pf try: o.shipping_addresss = Addresess.objects.get(id=int(params['shipping_addresss_id'])) except Addresess.DoesNotExist: pass try: o.billing_addresss = Addresess.objects.get(id=int(params['billing_addresss_id'])) except Addresess.DoesNotExist: pass try: o.autor = User.objects.get(id=int(params['user_id'])) except User.DoesNotExist: pass o.save() cart = Cart(params['cart_id']) for c in cart.items(): os = OrderShippingItem() os.order = o os.product = c.product os.variant_id = c.variant_id os.price = c.unit_price os.qty = c.quantity os.save()
def save_order(data): status = data.get('syncstatus') uuid = data.get('uuid') qs = Orders.objects.filter(uuid=uuid) if not qs: order = Orders(data1=data.get('data1'), data2=data.get('data2'), data3=data.get('data3'), uuid=uuid, valid=False) if status == 1: # Получаем ноывый объект с другого сервиса order.syncstatus = 3 else: sdict = { # Таблица установки нового статуса в зависимости от статусов синхронизируемых объектов ST_NEW: {ST_NEW: ST_COLLISION, ST_OK: ST_OK, ST_COLLISION: ST_COLLISION}, ST_UPD: {ST_UPD: ST_COLLISION, ST_OK: ST_SYNC, ST_COLLISION: ST_COLLISION, ST_DEL: ST_COLLISION}, ST_OK: {ST_NEW: ST_OK, ST_UPD: ST_OK}, ST_DEL: {ST_UPD: ST_COLLISION, ST_OK: ST_DEL_SYNCED, ST_DEL: ST_COLLISION, ST_DEL_SYNCED: ST_DEL_SYNCED, ST_COLLISION: ST_COLLISION}, ST_DEL_SYNCED: {ST_DEL: ST_DEL_SYNCED}, ST_COLLISION: {ST_NEW: ST_COLLISION, ST_UPD: ST_COLLISION, ST_DEL: ST_COLLISION, ST_COLLISION: ST_COLLISION}, ST_ERROR_SYNCED: {ST_ERROR: ST_ERROR_SYNCED}, } order = qs[0] # Если пришли изменения и объект не заблокирован, обновляем данные if status == ST_OK and order.syncstatus == ST_SYNC: order.data1 = data.get('data1') order.data2 = data.get('data2') order.data3 = data.get('data3') order.version = data.get('version') # Обновляем статус объекта if status in sdict and order.syncstatus in sdict[status]: order.syncstatus = sdict[status][order.syncstatus] else: if order.syncstatus == ST_ERROR: order.syncstatus = ST_ERROR_SYNCED elif order.syncstatus == ST_ERROR_SYNCED: pass else: order.syncstatus = ST_ERROR # Если пришли изменения и объект не заблокирован, обновляем данные if order.old_status == ST_OK and order.syncstatus == ST_SYNC: order.data1 = data.get('data1') order.data2 = data.get('data2') order.data3 = data.get('data3') order.version = data.get('version') order.valid = True if order.syncstatus == ST_OK else False print() order.save() if status != order.syncstatus and order.syncstatus != ST_SYNC: send_task(order)
def put(self, request, *args, **kwargs): """ 更新订单状态 :param request: :param args: :param kwargs: 'order_id': 订单ID 'payment_status': 订单支付状态 'payment_mode': 订单支付方式 :return: Orders instance """ form = OrdersUpdateForm(request.data) if not form.is_valid(): return Response({'Detail': form.errors}, status=status.HTTP_400_BAD_REQUEST) cld = form.cleaned_data obj = Orders.get_object(**{'orders_id': cld['orders_id']}) if isinstance(obj, Exception): return Response({'Detail': obj.args}, status=status.HTTP_400_BAD_REQUEST) serializer = OrdersSerializer(obj) try: serializer.update_orders_status(obj, cld) except Exception as e: return Response({'Detail': e.args}, status=status.HTTP_400_BAD_REQUEST) payment_mode = cld['payment_mode'] if cld.get('payment_status'): # 更新支付状态为现金支付 orders_detail = self.get_orders_detail(obj) res_serializer = OrdersDetailSerializer(data=orders_detail) if not res_serializer.is_valid(): return Response({'Detail': res_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) return Response(res_serializer.data, status=status.HTTP_206_PARTIAL_CONTENT) else: if payment_mode == 'cash': # 现金支付 orders_detail = self.get_orders_detail(obj) res_serializer = OrdersDetailSerializer(data=orders_detail) if not res_serializer.is_valid(): return Response({'Detail': res_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) return Response(res_serializer.data, status=status.HTTP_206_PARTIAL_CONTENT) elif payment_mode == 'scan': # 扫码支付 _wxPay = WXPay(obj) wx_result = _wxPay.native() if isinstance(wx_result, Exception): return Response(wx_result.args, status=status.HTTP_400_BAD_REQUEST) _alipay = AliPay(obj) ali_result = _alipay.pre_create() if isinstance(ali_result, Exception): return Response(ali_result.args, status=status.HTTP_400_BAD_REQUEST) return Response( { 'ali_code_url': ali_result, 'wx_code_url': wx_result }, status=status.HTTP_206_PARTIAL_CONTENT) elif payment_mode == 'yinshi': # 吟食支付 data = self.make_yinshi_pay_initial_data(request, obj) instance = self.save_yinshi_pay_random_code(data) if isinstance(instance, Exception): return Response({'Detail': instance.args}, status=status.HTTP_400_BAD_REQUEST) return_data = self.get_yinshi_pay_response(instance) return Response(return_data, status=status.HTTP_206_PARTIAL_CONTENT) else: return Response(status=status.HTTP_204_NO_CONTENT)
def get_pay_list(self, request, cld): return Orders.filter_paying_orders_list(request, **cld)
def post(self, request): medlist = request.data.get('list') userph = request.data.get('phone') user = User.objects.get(phone=userph) user_id = user.id store_id = medlist[0]['drugstore'] if request.data.get('pay_method'): pay_method = request.data.get('pay_method') med_price = 0 count = 0 ordergoods = [] for med in medlist: price = med['price'] * med['num'] context = { 'med_name': med['name'], 'med_price': price, 'med_count': med['num'], } ordergoods.append(context) med_price += price count += med['num'] order = Orders() order.order_id = datetime.now().strftime('%Y%m%d%H%M%S') + str( store_id) + str(user_id) order.customer_id = user_id order.drugstore_id = store_id order.med_price = med_price order.transit_price = 2 order.total_price = med_price + order.transit_price order.total_count = count order.order_status = 1 order.pay_method = pay_method order.staff_id = 999 order.save() paymethod = ['现金支付', '微信支付', '支付宝'] orderstatus = ['待支付', '待配送', '已送达', '待评价', '已完成'] order_ = { 'order_id': order.order_id, 'user': User.objects.get(id=user_id).name, 'address': order.customer.addr, 'receiver': order.customer.name, 'phone': order.customer.phone, 'drugstore': order.drugstore.name, 'med_price': order.med_price, 'total_count': order.total_count, 'total_price': order.total_price, 'transit_price': order.transit_price, 'order_status': orderstatus[order.order_status], 'pay_method': paymethod[order.pay_method], } for med in medlist: price = med['price'] * med['num'] ordergood = OrderGoods() ordergood.sku_id = med['id'] ordergood.order_id = order.order_id ordergood.count = med['num'] ordergood.price = price ordergood.save() med_ = Medicine.objects.get(id=med['id']) med_.stock -= med['num'] med_.sales += med['num'] med_.save() return Response({'status': 1}) else: med_price = 0 count = 0 ordergoods = [] for med in medlist: price = med['price'] * med['num'] context = { 'med_name': med['name'], 'med_price': price, 'med_count': med['num'], } ordergoods.append(context) med_price += price count += med['num'] order = Orders() order.order_id = datetime.now().strftime('%Y%m%d%H%M%S') + str( store_id) + str(user_id) order.customer_id = user_id order.drugstore_id = store_id order.med_price = med_price order.transit_price = 2 order.total_price = med_price + order.transit_price order.total_count = count order.order_status = 1 paymethod = ['现金支付', '微信支付', '支付宝'] orderstatus = ['待支付', '待配送', '已送达', '待评价', '已完成'] order_ = { 'order_id': order.order_id, 'user': User.objects.get(id=user_id).name, 'address': order.customer.addr, 'receiver': order.customer.name, 'phone': order.customer.phone, 'drugstore': order.drugstore.name, 'med_price': order.med_price, 'total_count': order.total_count, 'total_price': order.total_price, 'transit_price': order.transit_price, 'order_status': orderstatus[order.order_status], } return Response({'ordergoods': ordergoods, 'order': order_})
def save_order(request, step=1): """Save order with AJAX""" if request.method != "POST": result = {"result": "ERROR", "msg": "Wrong request method"} return http.HttpResponse(json.dumps(result), content_type="application/json") try: id = int(request.POST.get("id", 0)) # Если редактруем созданный заказ except (TypeError, ValueError): id = 0 user = request.POST.get("user", None) phone = request.POST.get("phone", None) email = request.POST.get("email", None) maket = request.POST.get("maket", None) if id != 0: templ_id = Orders.objects.get(id=id).template.id else: templ_id = 0 templ = get_object_or_None(OrderTemplate, pk=templ_id) # Или получаем тело заказа или создаём новое (новый заказ) if templ is None: templ = OrderTemplate(name=(user if user else '')) # Создаем тело заказа. Название - имя заказчика if int(step) > 10: # print request.POST templ.color_back = None # Color(id=request.POST.get("color_back", None)) templ.color_front = Color(id=(request.POST.get("colors", None))) templ.material = Material(id=(request.POST.get("materials", None))) templ.lamination = Lamination(id=request.POST.get("lamination", None)) templ.chip = False # request.POST.get("chip", False) templ.uv = False # request.POST.get("uv", False) templ.magnet = (True if float(request.POST.get("magnet", False)) > 0 else False) templ.emboss = (True if float(request.POST.get("emboss", False)) > 0 else False) templ.scratch = (True if float(request.POST.get("scratch", False)) > 0 else False) templ.print_num = (True if float(request.POST.get("print_num", False)) > 0 else False) templ.sign = (True if float(request.POST.get("sign", False)) > 0 else False) templ.indent = (True if float(request.POST.get("indent", False)) > 0 else False) templ.barcode = (True if float(request.POST.get("barcode", False)) > 0 else False) templ.foil = (True if float(request.POST.get("foil", False)) > 0 else False) else: templ.color_back = Color(id=request.POST.get("color_back", None)) templ.color_front = Color(id=request.POST.get("color_front", None)) templ.material = Material(id=request.POST.get("materials", None)) templ.lamination = Lamination(id=request.POST.get("lamination", None)) templ.chip = (True if float(request.POST.get("chip", False)) > 0 else False) templ.uv = (True if float(request.POST.get("uv", False)) > 0 else False) templ.magnet = (True if float(request.POST.get("magnet", False)) > 0 else False) templ.emboss = (True if float(request.POST.get("emboss", False)) > 0 else False) templ.scratch = (True if float(request.POST.get("scratch", False)) > 0 else False) templ.print_num = (True if float(request.POST.get("print_num", False)) > 0 else False) templ.sign = (True if float(request.POST.get("sign", False)) > 0 else False) templ.indent = (True if float(request.POST.get("indent", False)) > 0 else False) templ.barcode = (True if float(request.POST.get("barcode", False)) > 0 else False) templ.foil = (True if float(request.POST.get("foil", False)) > 0 else False) draw = request.POST.get("count", None) # количество в заказ if not draw: draw = 0 templ.save() # Сохраняем тело заказа для того, чтобы потом создать сам заказ if templ is None: # Если тело заказа не сохранилось - возвращаем ошибку? result = {"result": "ERROR", "msg": "Please, correct the property type to get access to other tabs."} return http.HttpResponse(json.dumps(result), content_type="application/json") try: # Проверяем, это новый заказ или редактируем созданный pk = int(request.POST.get("id", 0)) except (TypeError, ValueError): pk = 0 order = None if pk not in (None, 0): # Search existed objects order = get_object_or_None(Orders, pk=pk) if order is None: # Create new object order = Orders() order.template = OrderTemplate(id=templ.id) order.FIO = user order.draw = draw # Количество order.cost = request.POST.get("sum", False) order.email = email order.phone = phone order.maket = maket order.save() if step == '1': result = {"result": "OK", "id": order.id, "msg": "Changes are saved", "url": reverse("edit-order", args=[order.id, 3])} return HttpResponse(json.dumps(result), content_type="application/json") elif step > 10: result = {"result": "OK", "id": order.id, "msg": "This case 'elif step > 10'", "url": reverse("edit-easy", args=[order.id, step])} return HttpResponse(json.dumps(result), content_type="application/json") else: result = {"result": "OK", "id": order.id, "msg": "This case 'else'", "url": reverse("edit-fast", args=[order.id, step])} return HttpResponse(json.dumps(result), content_type="application/json")
def get_detail(self, **kwargs): if kwargs['orders_id'].startswith('Z'): return VerifyOrders.get_detail(**kwargs) else: return Orders.get_detail(**kwargs)
def process_mercadopago(request): if request.method == 'POST': pk = request.query_params.get("id") mp = mercadopago.MP( settings.MERCADOPAGO_CLIENT_ID, settings.MERCADOPAGO_CLIENT_SECRET ) paymentInfo = mp.get_payment (pk) if paymentInfo["status"] == 200: data = json.dumps(paymentInfo, indent=4) D.payment_method = "mercadopago" D.status = "Aprobbed" D.amount = 0.00 D.currency = "VEF" for d in data['response']['items']: D.amount += d.unit_price D.save() pf = PaymentMethodFields() pf.payment = D pf.key = "first_name" pf.value = data['response']['payer']['first_name'] pf.save() pf = PaymentMethodFields() pf.payment = D pf.key = "last_name" pf.value = data['response']['payer']['last_name'] pf.save() pf = PaymentMethodFields() pf.payment = D pf.key = "email" pf.value = data['response']['payer']['email'] pf.save() o = Orders() o.status = "pending" o.payment_method = pf try: o.shipping_addresss = Addresess.objects.get(id=int(paymentInfo['response']['external_reference']['shipping_addresss_id'])) except Addresess.DoesNotExist: pass try: o.billing_addresss = Addresess.objects.get(id=int(paymentInfo['response']['external_reference']['billing_addresss_id'])) except Addresess.DoesNotExist: pass try: o.autor = User.objects.get(id=int(paymentInfo['response']['external_reference']['user_id'])) except User.DoesNotExist: pass o.save() cart = Cart(paymentInfo['response']['external_reference']['cart_id']) for c in cart.items(): os = OrderShippingItem() os.order =o os.product = c.product os.variant_id = c.variant_id os.price = c.unit_price os.qty = c.quantity os.save() # payment_new.send( # sender=D.__class__, # payment_method="MercadoPago", # cart_id=paymentInfo['response']['external_reference']['cart_id'], # user_id=paymentInfo['response']['external_reference']['user_id'] # ) return Response(status=status.HTTP_201_CREATED)
def staff_order_add(request): # 判断是否登录 context = { 'page': 'staff_order_add', } if request.session.get('is_login', None): username = request.session.get('username') store = request.session.get('storeid') context['username'] = username if request.session.get('identity') == 'shopkeeper': context['page'] = 'find_staff' context['errmsg'] = '请以员工账号登录,用以生成订单' shopkeeper = True return render(request, 'staff/find_staff.html', context=context) else: shopkeeper = False else: return login(request) store_id = request.session.get('storeid') staff_id = request.session.get('staffid') if request.POST.get('pay_method'): pay_method = request.POST.get('pay_method') carts = Cart.objects.filter(C_store=request.session.get('storeid')) med_price = 0 count = 0 ordergoods = [] for med in carts: price = med.C_goods.price * med.C_goods_num context1 = { 'med_name': med.C_goods.name, 'med_price': price, 'med_count': med.C_goods_num, } ordergoods.append(context1) med_price += price count += med.C_goods_num order = Orders() order.order_id = datetime.now().strftime('%Y%m%d%H%M%S') + \ str(store_id) + str(staff_id) order.staff_id = staff_id order.drugstore_id = store_id order.med_price = med_price order.transit_price = 0 order.total_price = med_price order.total_count = count order.order_status = 4 order.pay_method = int(pay_method) order.sale_method = 0 # 默认线下销售 order.save() paymethod = ['现金支付', '微信支付', '支付宝'] orderstatus = ['待支付', '待配送', '已送达', '待评价', '已完成'] order_ = { 'order_id': order.order_id, 'staff': order.staff.name, # 'address': Order.addr, # 'receiver': address_.receiver, # 'phone': address_.phone, # 'drugstore': drug_store.name, 'pay_method': paymethod[order.pay_method], 'med_price': order.med_price, 'total_count': order.total_count, 'total_price': order.total_price, 'transit_price': order.transit_price, 'order_status': orderstatus[order.order_status], } for med in carts: price = med.C_goods.price * med.C_goods_num ordergood = OrderGoods() ordergood.sku_id = med.C_goods_id ordergood.order_id = order.order_id ordergood.count = med.C_goods_num ordergood.price = price ordergood.save() med_ = Medicine.objects.get(id=med.C_goods_id) med_.stock -= med.C_goods_num med_.sales += med.C_goods_num med_.save() med.delete() return redirect('orders:order_list') else: carts = Cart.objects.filter(C_store=request.session.get('storeid')) med_price = 0 count = 0 ordergoods = [] for med in carts: price = med.C_goods.price * med.C_goods_num context1 = { 'med_name': med.C_goods.name, 'med_price': price, 'med_count': med.C_goods_num, } ordergoods.append(context1) med_price += price count += med.C_goods_num order = Orders() order.order_id = datetime.now().strftime('%Y%m%d%H%M%S') + \ str(store_id) + str(staff_id) order.staff_id = staff_id order.drugstore_id = store_id order.med_price = med_price order.transit_price = 0 order.total_price = med_price order.total_count = count order.order_status = 4 paymethod = ['现金支付', '微信支付', '支付宝'] orderstatus = ['待支付', '待配送', '已送达', '待评价', '已完成'] staffname = Staff.objects.get(id=staff_id).name order_ = { 'order_id': order.order_id, 'staff': staffname, # 'address': Order.addr, # 'receiver': address_.receiver, # 'phone': address_.phone, # 'drugstore': drug_store.name, 'med_price': order.med_price, 'total_count': order.total_count, 'total_price': order.total_price, 'transit_price': order.transit_price, 'order_status': orderstatus[order.order_status], } context['ordergoods'] = ordergoods context['order'] = order_ return render(request, "orders/staff_order_add.html", context=context)