예제 #1
0
def orderNew(request):
	code=judge(request)
	if code=="success":
		jsons=jsonFromRequest(request)
		#jsons={"username":"******","password":"******","shop_cart":[{"product_id":1,"number":3},{"product_id":2,"number":4}]}
		username=jsons['username']
		password=jsons['password']
		code=getuser(username,password)
		if code==0:
			prcart=jsons['shop_cart']
			times=getLocaltime()
			order_no=getOrder_no()
			total=0
			lists=[]
			for x in range(len(prcart)):
				products=product.objects.filter(id=prcart[x]['product_id'])
				datas=getProductdict(products[0])
				datas['price']=getprice(username,products[0].id)
				orders=order(product_id=datas['id'],original_url=datas['img_url'],original_name=datas['name'],
					original_price=datas['price'],original_info=datas['info'],status=1,username=username,number=prcart[x]['number'],
					order_no=order_no,time=times)
				orders.save()
				datas['number']=prcart[x]['number']
				lists.append(datas)
				total=total+datas['price']*prcart[x]['number']
			return responseWithJsonObject({"result":0,"order_no":order_no,"status":1,"time":times,"total":total,"product":lists})

		else:
			return getBackdata(code)
	else:
		return code
예제 #2
0
def saveOrderInDatabase(o):
    print 'Saving Order: %s' % o['increment_id']
    databaseOrder = models.order.objects.filter(increment_id=o['increment_id'])
    if len(databaseOrder) > 0:
        print('Order in database: %s' % databaseOrder[0].increment_id)
        return databaseOrder[0]
    else:
        if len(o['payment']['additional_information']) > 0:
            payment_method = o['payment']['additional_information']['PaymentMethod']
        else:
            payment_method = 'Sem Informacao'
        pesoPedido = 0
        for item in o['items']:
            pesoPedido += float(item['weight'].replace(',', '.'))
        shipping_amount_simulate = correios_frete_simples(FRETE_ORIGEM, o['billing_address']['postcode'], 30, 30, 30, pesoPedido)
        if o['shipping_method']:
            if o['shipping_method'].split('_')[2] == '41112':
                shipping_amount_centralfit = float(shipping_amount_simulate['sedex']['valor'].replace(',', '.'))
            else:
                shipping_amount_centralfit = float(shipping_amount_simulate['pac']['valor'].replace(',', '.'))
        else:
            shipping_amount_centralfit = 10
            o['shipping_method'] = 'Envio Especial'

        if float(o['grand_total']) == 0.0:
            o['grand_total'] = o['subtotal']
            o['base_grand_total'] = o['subtotal']

        databaseOrder = models.order(
                                            increment_id=o['increment_id'],
                                            created_at= datetime.strptime(o['created_at'], '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc),
                                            updated_at=datetime.strptime(o['updated_at'], '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc),
                                            is_active=True,
                                            customer_id=o['customer_id'],
                                            grand_total=o['base_grand_total'],
                                            subtotal=o['base_subtotal'],
                                            status=o['status'],
                                            customer_email=o['customer_email'],
                                            order_id=o['order_id'],
                                            shipping_amount=o['shipping_amount'],
                                            shipping_method=o['shipping_method'],
                                            discount_amount=o['discount_amount'],
                                            payment_method=payment_method,
                                            shipping_address_postcode = o['shipping_address']['postcode'],
                                            shipping_address_region = o['shipping_address']['region'],
                                            shipping_address_street = o['shipping_address']['street'],
                                            weight=o['weight'],
                                            shipping_amount_centralfit=shipping_amount_centralfit
                                            )
        for itemInOrder in o['items']:
            saveOrderItemInDatabase(databaseOrder, itemInOrder)

        #Salvar o historico de iteracoes do pedido
        for iteration in o['status_history']:
            saveOrderStatusHistory(iteration, databaseOrder)
        databaseOrder.save()

        return databaseOrder
예제 #3
0
 def form_valid(self, form):
     o = order()
     o.or_delivery = form.cleaned_data['or_delivery']
     o.or_receive = form.cleaned_data['or_receive']
     o.or_lineCh = form.cleaned_data['or_lineCh']
     o.or_pieces = form.cleaned_data['or_pieces']
     o.or_status = form.cleaned_data['or_status']
     o.save()
     return super(re_order, self).form_valid(form)
예제 #4
0
 def post(self):
     orders = order()
     product = flask.request.form["product"]
     quantity = flask.request.form["quantity"]
     price = flask.request.form["price"]
     if product == "" or quantity == "" or price == "":
         return {"Error": "Sorry your order is incomplete please try again"}
     else:
         newOrder = {
             "product": product,
             "quantity": quantity,
             "price": price
         }
         return orders.makeOrder(newOrder)
예제 #5
0
def add_order():
    info = order(name=request.data['name'],
                 resName=request.data['resName'],
                 amount=request.data['amount'],
                 restaurant=request.data['restaurant'],
                 user=request.data['user'],
                 city=request.data['city'])
    session.add(info)
    try:
        session.commit()
    except:
        session.rollback()
        flash(config.UNEXPECTED_ERROR)
    finally:
        session.close()
    return {'status': 'success'}
예제 #6
0
def db_load_order():
    name_index = randint(0, len(name) - 1)
    amount_index = randint(0, len(amount) - 1)
    res_name_index = randint(0, len(res_name) - 1)
    cityName_index = randint(0, len(cityName) - 1)
    user_index = randint(0, len(myuser) - 1)
    info = order(name=name[name_index],
                 resName=res_name[res_name_index],
                 amount=amount[amount_index],
                 restaurant=randint(0, 12),
                 city=cityName[cityName_index],
                 user=myuser[user_index])
    session.add(info)
    try:
        session.commit()
    except:
        session.rollback()
        flash(config.UNEXPECTED_ERROR)
    finally:
        session.close()
    return {'status': 'OK'}
예제 #7
0
def orderlab(request):
    if request.method == "POST":
        order_type = request.POST['labtype']
        order_day = request.POST['labdays']
        register_date = datetime.now()
        end_date = register_date + timedelta(days=int(order_day))
        myorder = order(user_id=_get_current_userid(request),
                        account_id='1',
                        lab_id=order_type,
                        start_time=register_date,
                        end_time=end_date,
                        status='active',
                        mail_to_user='******')
        myorder.save()
        # judge if a valid order is created, if so, provision lab
        os.system("python /tmp/ssh.py")
        context = RequestContext(request)
        return render_to_response('ordersuccess.htm', context)
    else:
        # 渲染页面
        context = RequestContext(request)
        return render_to_response('option.htm', context)
예제 #8
0
def submitordertodb():
    global cart
    global ordertotal
    login_id = session['user_id']
    shipping_id = session['shipping_id']
    billing_address_id = session['billing_id']
    order_total = ordertotal

    print("right above if statement ", shipping_id)
    if shipping_id == None:
        flash("Please choose a shipping address.")
        return redirect("/proceedtocheckout")
    if billing_address_id == None:
        flash("Please choose a billing address.")
        return redirect("/proceedtocheckout")
    else:
        add_order = order(customer_id=login_id,
                          s_address_id=shipping_id,
                          b_address_id=billing_address_id,
                          order_total=order_total)
        db.session.add(add_order)
        db.session.commit()
        submitordertodb2()
        return redirect("/aftercheckout")
예제 #9
0
    def post(req):
        form = orderForm(req.POST)
        if form.is_valid():
            orders = order()
            orders.userName_id = form.cleaned_data['userName']
            orders.busniessId = form.cleaned_data['busniessId']
            orders.carId = form.cleaned_data['carId']
            orders.payMoney = form.cleaned_data['payMoney']
            orders.useraddr = form.cleaned_data['useraddr']
            # orders.ordersTime = datetime.strftime("%H:%M:%S", datetime.now())
            orders.ordersTime = datetime.now().strftime("%H:%M:%S")
            orders.orderId = random.randint(10000, 99999)
            time1 = datetime.now()
            orders.save()
            list = req.POST.getlist('foods')
            msg = []
            goodlist = []
            for food in list:
                print(food)
                goods1 = goods.objects.get(goodsId=food)
                goods1.quantity = goods1.quantity - 1
                if goods1.quantity < 0:
                    transaction.rollback()
                    orders.delete()
                    msg.append('商品' + goods1.name + '已售完')
                    return render(req, 'first/order.html', {'msg': msg})
                goods1.sales_volume = goods1.sales_volume + 1
                try:
                    goods1.save()
                except:
                    transaction.rollback()
                    orders.delete()
                    msg.append('商品选择失败')
                    return render(req, 'first/order.html', {'msg': msg})
                else:
                    transaction.commit()
                orderGoods = order_goods(orderId_id=orders.orderId,
                                         goodsId_id=food)
                try:
                    orderGoods.save()
                except:
                    transaction.rollback()
                    orders.delete()
                    msg.append('下单失败')
                    return render(req, 'first/order.html', {'msg': msg})
                else:
                    transaction.commit()

                goodlist.append(goods1.name)
            time1 = time1.strftime('%Y-%m-%d %H:%M:%S')
            push = [{
                'orderId': orders.orderId,
                'carId': req.POST.get("carId", ""),
                'userName': req.POST.get("userName", ""),
                'payMoney': req.POST.get("payMoney", ""),
                'orderTime': time1,
                'useraddr': req.POST.get("useraddr", ""),
                'goods': goodlist
            }]
            conn = redis.Redis(host='127.0.0.1', port=6379)
            json_str = json.dumps(push)

            conn.publish('order', json_str)

            return render(req, 'first/success.html')
        else:
            return render(req, 'first/order.html', {'form': form})
예제 #10
0
 def put(self, id):
     orders = order()
     orderStatus = flask.request.form["status"]
     return orders.updateOrder(id, orderStatus)
예제 #11
0
 def get(self, id):
     orders = order()
     orderid = int(id)
     return orders.specificOrder(orderid)
예제 #12
0
    def get(self):
        orders = order()

        return orders.listOrders()
예제 #13
0
def orderData(request):
    res = json.loads(DEFAULT_RESPONSE)
    polygon = request.GET.get('polygon', None)
    data = request.GET.get('data', None)
    month = request.GET.get('month', None)
    # from_date = request.GET.get('from_date', (datetime(day=1, month=9, year=2017)-timedelta(days=7)).isoformat())
    # to_date = request.GET.get('to_date', (datetime(day=1, month=9, year=2017)+timedelta(days=7)).isoformat())

    user = request.user
    email = user.email if user else None
    #organization = request.GET.get('organization', None)

    try:
        polygon = json.loads(polygon)
        # from_date = dateutil.parser.parse(from_date)
        # to_date = dateutil.parser.parse(to_date)

        if email and polygon and data in [
                'waveheight', 'wavedirection', 'waveperiod', 'bathymetry',
                'tide', 'current', 'currentdirection'
        ]:
            o = order(oid=str(uuid.uuid4()))
            o.email = user.email
            o.data = data
            o.polygon = polygon
            o.month = month
            # o.from_date = from_date
            # o.to_date = to_date
            price, datapoints = getPrice(data, polygon, month)
            if datapoints > 0:
                o.price = price
                o.datapoints = datapoints
                o.save()

                res['status'] = True
                res['msg'] = 'order placed.'

                # email
                # if 'test' not in o.email:
                # 	sub = 'Received Order #'+str(o.oid)
                # 	email_msg = 'Hi, \n We are processing your download request. You will receive the download link within 1 hr. \n\nThank You,\nSamudra Team.'
                # 	from_email = '*****@*****.**'
                # 	to_email = [o.email]
                # 	cc = ['*****@*****.**']
                # 	msg = EmailMultiAlternatives(sub, email_msg, from_email, to_email, cc=cc)
                # 	msg.send()
                if 'test' not in o.email:
                    email_msg = 'Hi, \n We are processing your download request. You will receive the download link within 1 hr. \n\nThank You,\nSamudra Team.'
                    email = {
                        'Source': '*****@*****.**',
                        'Destination': {
                            'ToAddresses': [o.email],
                            'BccAddresses': ['*****@*****.**']
                        },
                        'Message': {
                            'Subject': {
                                'Data': 'Received Order #' + str(o.oid)
                            },
                            'Body': {
                                'Text': {
                                    'Data': email_msg
                                }
                            },
                        },
                    }
                    ses.send_email(**email)
    except Exception, e:
        print e
        res['status'] = False
        res['msg'] = 'Someting went wrong.'
예제 #14
0
def saveOrderInDatabase(o):
    print 'Saving Order: %s' % o['increment_id']
    databaseOrder = models.order.objects.filter(increment_id=o['increment_id'])
    if len(databaseOrder) > 0:
        print('Order in database: %s' % databaseOrder[0].increment_id)
        return databaseOrder[0]
    else:
        if len(o['payment']['additional_information']) > 0:
            payment_method = o['payment']['additional_information'][
                'PaymentMethod']
        else:
            payment_method = 'Sem Informacao'
        pesoPedido = 0
        for item in o['items']:
            pesoPedido += float(item['weight'].replace(',', '.'))
        shipping_amount_simulate = correios_frete_simples(
            FRETE_ORIGEM, o['billing_address']['postcode'], 30, 30, 30,
            pesoPedido)
        if o['shipping_method']:
            if o['shipping_method'].split('_')[2] == '41112':
                shipping_amount_centralfit = float(
                    shipping_amount_simulate['sedex']['valor'].replace(
                        ',', '.'))
            else:
                shipping_amount_centralfit = float(
                    shipping_amount_simulate['pac']['valor'].replace(',', '.'))
        else:
            shipping_amount_centralfit = 10
            o['shipping_method'] = 'Envio Especial'

        if float(o['grand_total']) == 0.0:
            o['grand_total'] = o['subtotal']
            o['base_grand_total'] = o['subtotal']

        databaseOrder = models.order(
            increment_id=o['increment_id'],
            created_at=datetime.strptime(
                o['created_at'],
                '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc),
            updated_at=datetime.strptime(
                o['updated_at'],
                '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc),
            is_active=True,
            customer_id=o['customer_id'],
            grand_total=o['base_grand_total'],
            subtotal=o['base_subtotal'],
            status=o['status'],
            customer_email=o['customer_email'],
            order_id=o['order_id'],
            shipping_amount=o['shipping_amount'],
            shipping_method=o['shipping_method'],
            discount_amount=o['discount_amount'],
            payment_method=payment_method,
            shipping_address_postcode=o['shipping_address']['postcode'],
            shipping_address_region=o['shipping_address']['region'],
            shipping_address_street=o['shipping_address']['street'],
            weight=o['weight'],
            shipping_amount_centralfit=shipping_amount_centralfit)
        for itemInOrder in o['items']:
            saveOrderItemInDatabase(databaseOrder, itemInOrder)

        #Salvar o historico de iteracoes do pedido
        for iteration in o['status_history']:
            saveOrderStatusHistory(iteration, databaseOrder)
        databaseOrder.save()

        return databaseOrder