Пример #1
0
def checkout(request, first_name, last_name, email, address, zipcode, place,
             country, phone):
    order = Order(first_name=first_name,
                  last_name=last_name,
                  email=email,
                  address=address,
                  zipcode=zipcode,
                  place=place,
                  country=country,
                  phone=phone)

    if request.user.is_authenticated:
        order.user = request.user

    order.save()

    cart = Cart(request)

    for item in cart:
        OrderItem.objects.create(order=order,
                                 product=item['product'],
                                 price=item['price'],
                                 quantity=item['quantity'])

    return order.id
Пример #2
0
def create_order(request):
    address = request.POST.get('address')
    pay_code = request.POST.getlist('rd')
    # 生成订单号
    try:
        with transaction.atomic():
            uid = request.user.userprofile.uid
            order_code = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(0, 10))
            order = Order(order_code=order_code,
                          address='湖北武汉市高新区金融港', receiver='小玲',
                          user_message='请送货的时候给我带包辣条',
                          mobile='110',
                          user_id=uid)
            order.save()
            #  用户下面购物车的数据清空
            # 1 表示正常  0表示删除
            ShopCar.objects.filter(user_id=uid, status=1).update(status=-1, order=order)
        if pay_code == 1:
            pass
            # 微信支付
        else:
            # 支付宝支付
            pass
    except:
        pass
Пример #3
0
def checkout(request, first_name, last_name, email, address, zipcode, place, phone):
    """
    Params:
        -first_name:[String] Customer's first name
        -last_name:[String] Customer's last name
        -email:[String] Customer's E-mail
        -address:[String] Customer's Address
        -zipcode:[String] Customer's zipcode
        -phone:[String] Customer's phone
    Return:
        -order.id : [String] The generated id from the order that just saved into the Database
    """
    order = Order(first_name=first_name, last_name=last_name, \
        email=email, address=address, zipcode=zipcode, place=place, phone=phone)
    # If the user is authenticated then save the already saved user's info in the order's info
    if request.user.is_authenticated:
        order.user = request.user
        
    order.save()

    cart = Cart(request)
    # Create the order 
    for item in cart:
        OrderItem.objects.create(order=order, product=item['product'], \
            price=item['price'], quantity=item['quantity'])

    return order.id
Пример #4
0
def placeorder(request):
    cart=Cart(request)
    if request.method == 'POST':
        form = CheckoutForm(request.POST)
        if form.is_valid():
            try:
                first_name = request.POST['first_name']
                last_name = request.POST['last_name']
                email = request.POST['email']
                phone = request.POST['phone']
                address = request.POST['address']
                zipcode = request.POST['zipcode']
                place = request.POST['place']
                amount=12
                order=Order(first_name=first_name,last_name=last_name, email=email, address=address, zipcode=zipcode, place=place, phone=phone, paid_amount=amount)
                order.save()
                for item in Cart(request):
                    ordr=OrderItem.objects.create( order=order,product=item['product'], vendor=item['product'].vendor, price=item['product'].price, quantity=item['quantity'])
                    order.vendors.add(item['product'].vendor)
                notify_customer(order)
                notify_vendor(order)
                cart.clear()
                return redirect('success')
                
            except Exception:
                messages.error(request, 'There was something wrong with the payment')
    else:
        form = CheckoutForm()
    return render(request,'cart/placeorder.html',{'form': form})
Пример #5
0
    def post(self, request):
        if request.user.role == 0:
            # 获取空闲的回收人员
            scrap_users = UserProfile.objects.filter(role=1,
                                                     deleted=0,
                                                     work_status=0)
            if scrap_users:
                scrap_user = scrap_users[0]
                # 修改回收人员的状态
                scrap_user.work_status = 1
                scrap_user.save()

                # 创建订单
                order = Order(generate_order_number(), request.user.phone,
                              request.user.address, request.user.username,
                              scrap_user.phone)
                order.save()

                # 给废品回收人员发送订单通知
                send_sms_notify(scrap_user.phone, order.order_number)
                # 保存短信发送记录
                SMSMsg(scrap_user.username, scrap_user.phone).save()
                return JsonResponse({'status': 'success', 'msg': '下单成功'})
            else:
                return JsonResponse({
                    'status': 'failure',
                    'msg': '回收人员繁忙,请稍后再试'
                })
        else:
            return JsonResponse({'status': 'failure', 'msg': '你没有该操作的权限'})
Пример #6
0
 def save(self, request):
     package_id = request.POST['package_id']
     package = Package.objects.get(id=package_id)
     qq = ''
     if not isinstance(request.user, AnonymousUser):
         customer = request.user.customer
         qq = customer.qq
     else:
         customer = None
     if self.cleaned_data['qq']:
         qq = self.cleaned_data['qq']
     hotel_id = request.POST['hotel_id']
     hotel = Hotel.objects.get(id=hotel_id)
     flight_id = request.POST['flight_id']
     flight = Flight.objects.get(id=flight_id)
     order = Order(package=package,
                   hotel=hotel,
                   flight=flight,
                   customer=customer,
                   customer_name=self.cleaned_data['customer_name'],
                   phone=self.cleaned_data['phone'],
                   start_address=self.cleaned_data['start_address'],
                   start_date=self.cleaned_data['start_date'],
                   qq=qq
                   )
     order.save()
     return order
Пример #7
0
def orders_view():
    orders = Order.query(Order.status == ORDER_STATUS['now'])
    booked_orders = Order.query(Order.status == ORDER_STATUS['booked'])
    incorrect_orders = Order.query(Order.status == ORDER_STATUS['incorrect'])
    return render_template('admin/order/orders.html',
                           orders=orders,
                           booked_orders=booked_orders,
                           incorrect_orders=incorrect_orders)
Пример #8
0
def orders_view():
    orders = Order.query(Order.status==ORDER_STATUS['now'])
    booked_orders = Order.query(Order.status==ORDER_STATUS['booked'])
    incorrect_orders = Order.query(Order.status==ORDER_STATUS['incorrect'])
    return render_template(
        'admin/order/orders.html',
        orders=orders,
        booked_orders=booked_orders,
        incorrect_orders=incorrect_orders
    )
Пример #9
0
def new_order(request):
    client_json = simplejson.loads(request.data)
    name = client_json.get('name', '')
    telephone = client_json.get('telephone', '')
    email = client_json.get('email', '')
    if not client_json \
    or not name \
    or not telephone:
        return render_json_response({
            'api_success': False,
            'api_msg': \
            u'Заказ не сформирован, т.к. не заполнена контактная информация.'},
            status=401)
    cart = request.session.get('cart', {})
    order_items = get_cart_items(cart)
    total_price = 0.0
    for item in order_items:
        total_price += item.get('price', 0.0) * item.get('count', 0)
        pass
    if not order_items or not total_price:
        return render_json_response({
        'api_success': False,
        'api_msg': u'Корзина пуста или при передаче данных произошла ошибка.\n\
Поробуйте еще раз. %s' % order_items}, status=409)

    client = Client(
        name=name,
        telephone=telephone,
        email=email,
        address=client_json.get('address'),
        is_delivery=client_json.get('delivery', False),
        ip=request.remote_addr)
    order = Order(client=client, total_price=total_price)
    for item in order_items:
        oi = OrderItem(
            item_id=item.get('id', ''),
            item_title=item.get('title', ''),
            item_url=item.get('url', ''),
            item_img_url=item.get('img_url', ''),
            item_price=item.get('price', 0.0),
            item_count=item.get('count', 0)
            )
        order.items.append(oi)
    order.put()
    def txn():
        taskqueue.add(url=url_for('order/send_to_manager',
                            order_id=str(order.key.id())),
                            transactional=True)
    db.run_in_transaction(txn)
    request.session['cart'] = {}
    return render_json_response({
        'api_success': True,
        'api_msg': u'Заказ успешно сформирован!\n\
В ближайшее время с вами свяжется наш менеджер и уточнит детали заказа.'
        })
Пример #10
0
def checkout(request, first_name, last_name, email, address, zipcode, place):
    order = Order(first_name=first_name, last_name=last_name, email=email, address=address, zipcode=zipcode,
                  place=place)
    order.save()

    cart = Cart(request)

    for item in cart:
        OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity'])

    return order.id
Пример #11
0
def send_to_manager(request, order_id):
    order = Order.get_by_id(order_id)
    if not order:
        return render_to_response({
            'api':{
                'success': False,
                'msg': 'Order %s not found' % order_id
            }
        }, status=404)
    managers = Manager.query()
    if not managers.count():
        return render_json_response({
            'api':{
                'success': False,
                'msg': 'Managers not found.'
            }
        }, status=404)
    subject = render_to_string('order/msg/subject.html', {'order':order})
    msg = render_to_string('order/msg/body.html', {'order': order})

    email = mail.EmailMessage()
    email.subject = subject
    email.html = msg
    email.sender = settings.DEFAULT_MAIL_FROM
    for manager in managers:
       if manager.communication.email:
           email.to = manager.communication.email
           email.send()
    return render_json_response({
        'api':{
            'success': True,
            'msg': 'Order notifications were sent'
        }
    })
Пример #12
0
def order_view(key_id):
    order = Order.retrieve_by_id(key_id)
    if not order:
        return redirect(url_for('admin.order.orders_view'))
    return render_template(
        'admin/order/order.html',
        order=order
    )
Пример #13
0
def cart_view():
    if request.method == 'POST' and 'order_delete' in request.form:
        clear_cart()
        return redirect(url_for('order.cart_view'))
    cart = session.get('cart', {})
    price = cart.get('price', 0)
    products_count = cart.get('products_count', 0)
    un_products_count = cart.get('un_products_count', 0)
    cart_products = cart.get('products', {})
    products = []
    for product_key in cart_products.keys():
        cart_product = cart_products.get(product_key, {})
        product = Product.retrieve_by_id(product_key)
        if product:
            product.order = cart_product.get('count', 0)
            product.order_price = cart_product.get('price', 0)
        products.append(product)
    if request.method == 'POST' and 'order_accept':
        order = Order(customer=current_user.user_db.key)
        price = 0
        for product in products:
            order_product = OrderProduct(
                name=product.name,
                img_url='%s=s100' % product.images[0] if product.images else '',
                product_key=product.key,
                count=product.order,
                price=product.order_price,
            )
            price += product.order_price
            order.products.append(order_product)
        order.price = price
        order.put()
        clear_cart()
        return render_template(
            'order/order_success.html',
            title=u'Предзаказ оформлен',
            order=order
        )
    return render_template(
        'order/cart.html',
        title=u'Оформление предзаказа',
        price=price,
        products_count=products_count,
        un_products_count=un_products_count,
        products=products
    )
Пример #14
0
def get_order(request, id):
    order = Order.get_by_id(id)
    if request.method == 'PUT':
        model = simplejson.loads(request.data)
        status = model.get('status', 0)
        if order.status != status:
            order.status = status
            order.put()
    return render_json_response(order.to_json())
Пример #15
0
def add(request, pk):
    product = get_object_or_404(Product, pk=pk)
    referer = request.META.get('HTTP_REFERER')
    redirect = HttpResponseRedirect(reverse('product:view', args=[product.category.pk, pk]))
    if referer and 'login' in referer:
        return redirect
    order = Order.objects.filter(user=request.user, status=Order.CART).first()
    if not order:
        order = Order(user=request.user)
        order.save()
    current = order.positions.filter(product=product)
    if current:
        current[0].quantity += 1
        current[0].save()
    else:
        position = Position(product=product)
        position.quantity = 1
        position.save()
        order.positions.add(position)
    return HttpResponseRedirect(referer) if referer else redirect
Пример #16
0
def checkout(request, first_name, last_name, email, phone, address, zipcode,
             place):
    order = Order(first_name=first_name,
                  last_name=last_name,
                  email=email,
                  phone=phone,
                  address=address,
                  zipcode=zipcode,
                  place=place)
    # something happens if user is authenticated
    if request.user.is_authenticated:
        order.user = request.user
    # ----
    order.save()
    cart = Cart(request)
    # Add items to OrderItems
    for item in cart:
        OrderItem.objects.create(order=order,
                                 product=item['product'],
                                 price=item['price'],
                                 quantity=item['quantity'])
    return order.id
Пример #17
0
def checkout(request, first_name, last_name, email, address, zipcode, city,
             country):
    order = Order(first_name=first_name,
                  last_name=last_name,
                  email=email,
                  address=address,
                  zipcode=zipcode,
                  city=city,
                  country=country)
    order.save()

    # Create a cart instance
    cart = Cart(request)

    # For each item in cart, create one of the order items for each product
    for item in cart:
        OrderItem.objects.create(order=order,
                                 product=item['product'],
                                 price=item['price'],
                                 quantity=item['quantity'])

    # Update order id
    return order.id
Пример #18
0
    def post(self):
        args = self.parser.parse_args()
        uid = args.get('uid')
        movie_id = args.get('movie_id')
        hs_id = args.get('hs_id')
        seat_ids = args.get('seat_ids')
        ss_id = args.get('ss_id')

        try:
            # db.session.begin()
            # 查询座位是否可选
            seats = Seats.query.filter(Seats.sid.in_(seat_ids)).all()
            if is_choose(seats):
                # 锁定座位
                for seat in seats:
                    seat.is_choose = False
                db.session.add_all(seats)

                # 生成订单号
                no = product_code()
                # 查询票价
                hs = HallScheduling.query.get(hs_id)
                # 计算总金额
                total = hs.current_price * 2
                # 生成订单
                order = Order(no=no,
                              number=2,
                              total=total,
                              status=1,
                              movie_id=movie_id,
                              hs_id=hs_id,
                              cinema_id=1,
                              ss_id=1,
                              seat_id=1)

                # 提交订单
                db.session.add(order)
                db.session.commit()
                return to_response_success(
                    data=no, fields=OrderSuccessFields.result_fields)
            else:
                return to_response_error(status='-1', msg='座位已经被选了')
        except:
            db.session.rollback()
            return '失败'
Пример #19
0
    def post(self, request, *args, **kwargs):
        client_data = cookie_parser(request.COOKIES.get('client_data'))
        order = Order()
        order.shipping_address = client_data.get('shipping_address')
        order.phone = client_data.get('phone')
        order.client_name = client_data.get('client_name')
        if request.user.is_authenticated:
            order.customer = request.user
        order.save()
        cart_items = self.get_cart_items(self.request)
        total_price = 0

        json_data = []
        for cart_item in cart_items:
            cart_item.order = order
            total_price += cart_item.total_price
            cart_item.save()

            title = "{} {}".format(cart_item.variation.product.name,
                                   cart_item.variation.name)
            if cart_item.variation.color:
                title = "{} {}".format(title, cart_item.variation.color.name)
            json_data.append({
                'title': title,
                'price': float(cart_item.variation.price),
                'count': cart_item.count,
                'total_price': float(cart_item.total_price)
            })
        order.products = json_data
        order.total_price = Decimal(total_price)
        order.order_unique_id = uuid.uuid4()
        order.save()

        order_detail_url = reverse_lazy(
            'orders:order_detail', args=[order.phone, order.order_unique_id])
        data = {
            'message': _('Order successful placed'),
            'status': 'success',
            'redirect_url': order_detail_url
        }
        return JsonResponse(data=data, safe=False)
Пример #20
0
def match_install(install,install1,amount,t):

    install_res=Order()

    install_res.trantype=install.trantype
    install_res.subtrantype=install.subtrantype
    install_res.amount=amount
    install_res.userid=install.userid
    install_res.username=install.username
    install_res.userid_to=install1.userid
    install_res.username_to=install1.username
    install_res.ordercode_to=install1.ordercode
    install_res.status=1
    install_res.confirmtime=install.confirmtime
    install_res.matchtime = t
    install_res.createtime = install.createtime
    install_res.img = install.img
    install_res.umark = install.umark
    install_res.save()
    return install_res
Пример #21
0
    def post(self,request):

        data_dict = json.loads(request.body.decode())
        house_id = data_dict.get('house_id')
        start_date = data_dict.get('start_date')
        end_date = data_dict.get('end_date')
        user = request.user

        #判断完整
        if not all([house_id,start_date,end_date]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数'})
        #是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({"errno": 400, "errmsg": "房屋不存在"})
        #是否房主
        if user.id == house.user.id:
            return JsonResponse({"errno": 400, "errmsg": "是房主无法预定"})

        #跳转页面

        #判断是否传入错误数据
        try:
            d1 = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            d2 = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            assert d1 < d2, Exception('开始日期大于结束日期')
            days = (d2 - d1).days
            if days < 0:
                return JsonResponse({'errno': 400, 'errmsg': '日期有误'})
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '参数有误'})

        #开启事务
        # with transaction.atomic():
        #
        #      save_id = transaction.savepoint()

         # try:
        amount = days * house.price

        if days < house.min_days:
            return JsonResponse({'errno': 400, 'errmsg': '住的时间太短'})

        if days > house.max_days:
            return JsonResponse({'errno': 400, 'errmsg': '住的时间太长'})
        order = Order()
        order.user_id = user.id
        order.house_id = house.id
        order.begin_date = d1
        order.end_date = d2
        order.days = days
        order.amount = amount
        order.house_price = house.price
        order.status = Order.ORDER_STATUS['WAIT_ACCEPT']

        order.save()

        # order = Order.objects.create(user_id=user.id,
        #                              house_id=house_id,
        #                              begin_date=d1,
        #                              end_date=d2,
        #                              days=days,
        #                              amount=amount,
        #                              # # status=Order.ORDER_STATUS['PAID'],
        #                              price=house.price,
        #                              )
        # 判断用户下单的时间段是否有别的订单

        count = Order.objects.filter(house_id=house_id,
                                         begin_date__lte=end_date,
                                         end_date__gte=start_date).count()
        if count > 0:
            # 说明房子被别人预定
            # transaction.savepoint_rollback(save_id)
            return JsonResponse({'errno': 400, 'errmsg': '房子已被预定'})

             # except Exception as e:
             #     transaction.savepoint_rollback(save_id)
             #     return JsonResponse({'errno': 400, 'errmsg': '下单失败'})

            #提交事务

             # transaction.savepoint_commit(save_id)
        return JsonResponse({'errno': 0, 'errmsg': '添加订单成功',  "data": {"order_id": order.pk}})
Пример #22
0
def checkout(request):
    # import pdb; pdb.set_trace()
    cart=Cart(request)
    if cart.count() == 0:
        return HttpResponseRedirect('/my-cart')

    profile = Profile.objects.get(user__username=request.user)
    form = DeliveryAddress(request.POST or None, instance=profile)
    delivery_form = DeliveryServiceForm(request.POST or None)
    tot_weight = request.session['total_weight']

    if form.is_valid() and delivery_form.is_valid():        
        delivery_cost = delivery_form.cleaned_data['service']
        tot_vat = request.POST.get('tot_vat')
        # import pdb; pdb.set_trace()
        # order data
        order = Order()
        order.user = request.user
        order.amount = float(cart.summary()) + float(delivery_cost.cost) + float(tot_vat)
        order.vat = float(tot_vat)
        order.status = 'NEW'
        order.order_notes = request.POST.get('notes')
        order.save()
        # order detail data
        for ca in cart:
            orderdetail = OrderDetail()
            orderdetail.order = order
            orderdetail.product = ca.product
            orderdetail.weight = ca.product.weight
            orderdetail.surcharge = ca.product.surcharge
            orderdetail.price = ca.unit_price
            orderdetail.qty = ca.quantity
            orderdetail.amount = ca.total_price
            orderdetail.save()
        # order delivery data
        orderdelivery = OrderDelivery ()
        orderdelivery.order = order
        orderdelivery.first_name = form.cleaned_data['first_name']
        orderdelivery.last_name = form.cleaned_data['last_name']
        orderdelivery.business_name = form.cleaned_data['business_name']
        orderdelivery.address_line1 = form.cleaned_data['address_line1']
        orderdelivery.address_line2 = form.cleaned_data['address_line2']
        orderdelivery.city = form.cleaned_data['city']
        orderdelivery.state = form.cleaned_data['state']
        orderdelivery.postcode = form.cleaned_data['postcode']
        orderdelivery.country = form.cleaned_data['country']
        orderdelivery.telephone = form.cleaned_data['telephone']
        orderdelivery.service = delivery_cost.title
        orderdelivery.cost = delivery_cost.cost
        orderdelivery.weight = tot_weight
        orderdelivery.save()
        cart.clear()
        messages.success(request, "Your order was complete.")
        return HttpResponseRedirect('/orderreview/'+ order.order_no)

    try:        
        check_band = PostageCountry.objects.get(country=profile.country)        
        band = check_band.band        
        request.session['vat'] = check_band.vat
    except:
        band = ''    
        
    delivery_form.fields['service'] = forms.ModelChoiceField(required=True, queryset=PostageRate.objects.all().filter(band=band,active=True,weight_start__lte=tot_weight,weight_to__gte=tot_weight), widget=forms.Select(attrs={'class': 'form-control'}))

    data = {'form':form,'delivery_form':delivery_form}
    return render_to_response('order/checkout.html', data, context_instance=RequestContext(request, processors=[custom_proc]))
Пример #23
0
def add(request):
    data = {}
    order = None
    num = [0, 1, 2, 3, 4]
    data['num'] = num
    steels = Steel.objects.all()
    data['steels'] = steels
    clients = Client.objects.all()
    data['clients'] = clients
    order_day = date.today()
    data['order_day'] = order_day
    oid = datetime.now().strftime('%Y%m%d%H%M%S')
    data['oid'] = str(oid) + '_3'
    today = date.today()
    if request.method == 'POST':
        post = request.POST.copy()
        is_youpiao = post.get('is_youpiao', 0)  # check if not youpiao=1, wupiao=0
        if is_youpiao:
            is_youpiao = int(is_youpiao)
        client_id = post.get('client_id', None)

        i = 0
        oid = post.get('oid', None)
        if oid:
            pass
        else:
            return False

        order_item_list = []
        order_total_price = 0.0
        if not client_id:
            form = OrderForm(instance=order)
            data['form'] = form
            return render_to_response(
                'order/add.html',
                data,
                context_instance=RequestContext(request)
            )
        create_time = datetime.now()
        modify_time = create_time
        total_profit = 0.0  # order total profit

        while i < 5:
            temp_order_item = OrderItem()
            sid = 'sid_' + str(i)
            unit_price = 'unit_price_' + str(i)
            number = 'number_' + str(i)
            total_price = 'total_price_' + str(i)
            temp_sid = post.get(sid, None)

            if not temp_sid:
                break

            temp_number = post.get(number, None)

            if temp_number:
                temp_number = int(temp_number)
            else:
                form = OrderForm(instance=order)
                data['form'] = form
                return render_to_response(
                    'order/add.html',
                    data,
                    context_instance=RequestContext(request)
                )

            temp_unit_price = post.get(unit_price, None)
            #print temp_unit_price
            if temp_unit_price:
                temp_unit_price = float(temp_unit_price)
            else:
                form = OrderForm(instance=order)
                data['form'] = form
                return render_to_response(
                    'order/add.html',
                    data,
                    context_instance=RequestContext(request)
                )

            temp_total_price = post.get(total_price, None)
            if temp_total_price:
                temp_total_price = float(temp_total_price)
            else:
                form = OrderForm(instance=order)
                data['form'] = form
                return render_to_response(
                    'order/add.html',
                    data,
                    context_instance=RequestContext(request)
                )

            temp_steel = None
            if temp_sid:
                #print temp_sid
                temp_steels = steels.filter(id=int(temp_sid))
                if temp_steels.exists():
                    temp_steel = temp_steels[0]
                    storage_number = int(temp_steel.number) + int(temp_steel.retail_number)
                    if storage_number < int(temp_number):
                        form = OrderForm(instance=order)
                        data['form'] = form
                        return render_to_response(
                            'order/add.html',
                            data,
                            context_instance=RequestContext(request)
                        )
                else:
                    form = OrderForm(instance=order)
                    data['form'] = form
                    return render_to_response(
                        'order/add.html',
                        data,
                        context_instance=RequestContext(request)
                    )
            else:
                break

            temp_profit = 0.0  # each order item profit
            # 获取来源订单号
            temp_from_oid = ''
            need_number = int(temp_number)  # 需要的数量
            if temp_steel.retail_number > 0:
                inexhausted_retails = Retail.objects.filter(sid=temp_sid).filter(status=2).order_by('id')
                if inexhausted_retails.exists():
                    total_used_retail_num = 0   # 之前用了多少数量
                    inexhausted_retail = inexhausted_retails[0]
                    same_retail_orders = OrderItem.objects.filter(from_oid__contains=inexhausted_retail.oid)
                    excess_retail_num = int(inexhausted_retail.number)
                    if same_retail_orders.exists():
                        for item in same_retail_orders:
                            temp_from_oid_str = item.from_oid
                            temp_from_oid_list = temp_from_oid_str.split(',')
                            for term in temp_from_oid_list:
                                if inexhausted_retail.oid in term:
                                    total_used_retail_num += int(term.split('|')[1])
                        excess_retail_num = excess_retail_num - total_used_retail_num

                    if excess_retail_num < need_number or excess_retail_num == need_number:
                        need_number = need_number - excess_retail_num
                        temp_from_oid += inexhausted_retail.oid + '|' + str(excess_retail_num) + ','
                        temp_profit = temp_profit + float(excess_retail_num) * float(inexhausted_retail.unit_price)
                        inexhausted_retail.status = 3
                        inexhausted_retail.save()
                    else:
                        temp_from_oid += inexhausted_retail.oid + '|' + str(need_number) + ','
                        temp_profit = temp_profit + float(need_number) * float(inexhausted_retail.unit_price)
                        need_number = 0
                        inexhausted_retail.status = 2
                        inexhausted_retail.save()

                if need_number > 0:
                    unexhausted_retails = Retail.objects.filter(sid=temp_sid).filter(status=1).order_by('id')
                    if unexhausted_retails.exists():
                        for item in unexhausted_retails:
                            if need_number == 0:
                                break

                            if int(item.number) < need_number or int(item.number) == need_number:
                                need_number = need_number - int(item.number)
                                temp_from_oid += item.oid + '|' + str(item.number) + ','
                                temp_profit = temp_profit + float(item.number) * float(item.unit_price)
                                item.status = 3
                                item.save()
                            else:
                                temp_from_oid += item.oid + '|' + str(need_number) + ','
                                temp_profit = temp_profit + float(need_number) * float(item.unit_price)
                                need_number = 0
                                item.status = 2
                                item.save()

            if need_number > 0:
                inexhausted_batches = Batch.objects.filter(sid=temp_sid).filter(status=2).order_by('id')
                if inexhausted_batches.exists():
                    total_used_batch_num = 0   # 之前用了多少数量
                    inexhausted_batch = inexhausted_batches[0]
                    same_batch_orders = OrderItem.objects.filter(from_oid__contains=inexhausted_batch.oid)
                    excess_batch_num = int(inexhausted_batch.number)
                    if same_batch_orders.exists():
                        for item in same_batch_orders:
                            temp_from_oid_str = item.from_oid
                            temp_from_oid_list = temp_from_oid_str.split(',')
                            for term in temp_from_oid_list:
                                if inexhausted_batch.oid in term:
                                    total_used_batch_num += int(term.split('|')[1])
                        excess_batch_num = excess_batch_num - total_used_batch_num

                    #print excess_batch_num
                    if excess_batch_num < need_number or excess_batch_num == need_number:
                        need_number = need_number - excess_batch_num
                        temp_from_oid += inexhausted_batch.oid + '|' + str(excess_batch_num) + ','
                        if is_youpiao == 1:
                            temp_profit = temp_profit + float(excess_batch_num) * float(inexhausted_batch.cost_a)
                        elif is_youpiao == 0:
                            temp_profit = temp_profit + float(excess_batch_num) * float(inexhausted_batch.cost_b)
                        inexhausted_batch.status = 3
                        inexhausted_batch.save()
                    else:
                        temp_from_oid += inexhausted_batch.oid + '|' + str(need_number) + ','
                        if is_youpiao == 1:
                            temp_profit = temp_profit + float(need_number) * float(inexhausted_batch.cost_a)
                        elif is_youpiao == 0:
                            temp_profit = temp_profit + float(need_number) * float(inexhausted_batch.cost_b)
                        need_number = 0
                        inexhausted_batch.status = 2
                        inexhausted_batch.save()

            if need_number > 0:
                unexhausted_batches = Batch.objects.filter(sid=temp_sid).filter(status=1).order_by('id')
                if unexhausted_batches.exists():
                    for item in unexhausted_batches:
                        if need_number == 0:
                            break

                        if int(item.number) < need_number or int(item.number) == need_number:
                            need_number = need_number - int(item.number)
                            temp_from_oid += item.oid + '|' + str(item.number) + ','
                            if is_youpiao == 1:
                                temp_profit = temp_profit + float(item.number) * float(item.cost_a)
                            elif is_youpiao == 0:
                                temp_profit = temp_profit + float(item.number) * float(item.cost_b)
                            item.status = 3
                            item.save()
                        else:
                            temp_from_oid += item.oid + '|' + str(need_number) + ','
                            if is_youpiao == 1:
                                temp_profit = temp_profit + float(need_number) * float(item.cost_a)
                            elif is_youpiao == 0:
                                temp_profit = temp_profit + float(need_number) * float(item.cost_b)
                            need_number = 0
                            item.status = 2
                            item.save()

            #print need_number
            if need_number > 0:
                return False

            temp_order_item.oid = oid
            temp_order_item.from_oid = temp_from_oid
            temp_order_item.status = 1
            temp_order_item.sid = temp_sid
            temp_order_item.number = temp_number
            round(temp_profit, 2)
            temp_order_item.profit = temp_profit
            round(temp_unit_price, 2)
            temp_order_item.unit_price = temp_unit_price
            check_total_price = float(temp_number) * float(temp_unit_price)
            if check_total_price == float(temp_total_price):
                temp_order_item.total_price = temp_total_price
            else:
                round(check_total_price, 2)
                temp_order_item.total_price = check_total_price

            temp_order_item.create_time = create_time
            temp_order_item.modify_time = modify_time
            temp_order_item.order_day = today
            order_item_list.append(temp_order_item)
            i = i + 1
            order_total_price = order_total_price + float(temp_total_price)
            total_profit = total_profit + float(temp_profit)

        check = None
        check = OrderItem.objects.bulk_create(order_item_list)

        if check:
            pass
        else:
            form = OrderForm(instance=order)
            data['form'] = form
            return render_to_response(
                'order/add.html',
                data,
                context_instance=RequestContext(request)
            )

        if order_total_price > 0.0:
            order = Order()
            order.client_id = client_id
            order.oid = oid
            order.is_youpiao = int(is_youpiao)
            order.order_day = date.today()
            order.total_price = order_total_price
            round(total_profit, 2)
            order.profit = total_profit
            order.create_time = timezone.now()
            order.modify_time = timezone.now()
            order.save()
            current_order_items = OrderItem.objects.filter(oid=order.oid)
            if current_order_items.exists():
                for item in current_order_items:
                    temp_steel = get_object_or_404(Steel, id=item.sid)
                    total_number = int(temp_steel.retail_number) + int(temp_steel.number)
                    retail_number = int(temp_steel.retail_number)
                    if total_number > item.number or total_number == item.number:
                        if temp_steel.retail_number > 0:
                            if int(temp_steel.retail_number) > int(item.number) or int(temp_steel.retail_number) == int(item.number):
                                temp_steel.retail_number = int(temp_steel.retail_number) - int(item.number)
                            else:
                                temp_steel.number = int(temp_steel.number) - (int(item.number) - int(temp_steel.retail_number))
                                temp_steel.retail_number = 0
                        else:
                            temp_steel.number = int(temp_steel.number) - int(item.number)
                        temp_steel.save()
                    else:
                        return False
            return HttpResponseRedirect('/order/?id=%d' % int(order.id))
        else:
            form = OrderForm(post, instance=order)
            data['form'] = form
            return render_to_response(
                'order/add.html',
                data,
                context_instance=RequestContext(request)
            )
    else:
        form = OrderForm(instance=order)
        data['form'] = form
        return render_to_response(
            'order/add.html',
            data,
            context_instance=RequestContext(request)
        )
Пример #24
0
def post_order(data):
    user_id = data["user_id"]
    notes = data['notes']
    order_time = data['order_time']
    items = data['items']
    deliver_to = data['deliver_to']
    order_loc = data['order_loc']

    food_items = []

    user = User.query.filter_by(id=user_id).first()
    if not user:
        return {"message": "user id is not found"}, 400

    if not items:
        return {"message": "items must be not null"}, 400

    if list(order_loc.keys()) != ['latitude', 'longitude', 'accuracy']:
        return {"message": "order_loc object is not valid key"}, 400

    if type(order_loc['latitude']) != float and type(order_loc['latitude']) != int:
        return {"message": "latitude of order_loc object is not valid type"}, 400

    if type(order_loc['longitude']) != float and type(order_loc['longitude']) != int:
        return {"message": "longitude of order_loc object is not valid type"}, 400

    if type(order_loc['accuracy']) != float and type(order_loc['accuracy']) != int:
        return {"message": "accuracy of order_loc object is not valid type"}, 400

    if list(deliver_to.keys()) != ['latitude', 'longitude', 'accuracy', 'is_pinned']:
        return {"message": "deliver_to object is not valid key"}, 400

    if type(deliver_to['latitude']) != float and type(deliver_to['latitude']) != int:
        return {"message": "latitude of deliver_to object is not valid type"}, 400

    if type(deliver_to['longitude']) != float and type(deliver_to['longitude']) != int:
        return {"message": "longitude of deliver_to object is not valid type"}, 400

    if type(deliver_to['accuracy']) != float and type(deliver_to['accuracy']) != int:
        return {"message": "accuracy of deliver_to object is not valid type"}, 400

    if type(deliver_to['is_pinned']) != bool:
        return {"message": "is_pinned of deliver_to object is not valid type"}, 400

    for item in items:
        if "id" and "qty" not in item.keys():
            return {"message": "item must have id and qty"}, 400
        if int != type(item["id"]):
            return {"message": "id of item should be integer"}, 400
        if int != type(item["qty"]):
            return {"message": "qty of item should be integer"}, 400
        food = Food.query.get(item["id"])
        if not food:
            return {"message": "food id={} is not found".format(item["id"])}, 400
        if food.stock < item["qty"]:
            return {"message": "stock not enough for {}, avalaible {} ".format(food.name, food.stock)}, 400
        item = CartItem(
            qty=item["qty"],
            food_id=item["id"]
        )
        food_items.append(item)

    order_loc = OrderLocationTracked(
        latitude=order_loc['latitude'],
        longitude=order_loc['longitude'],
        accuracy=order_loc['accuracy']
    )

    deliver_to = OrderLocationTracked(
        latitude=deliver_to['latitude'],
        longitude=deliver_to['longitude'],
        accuracy=deliver_to['accuracy'],
        is_pinned=deliver_to['is_pinned']
    )

    order = Order(
        order_time=order_time,
        order_loc=order_loc,
        deliver_to=deliver_to,
        notes=notes,
        cart=Cart()
    )
    order.cart.cart_items = food_items
    user.user_detail.orders.append(order)
    try:
        user.commit()
    except:
        return {"message": "can't save, tell you engineer"}, 500
    return {"message": "success", "data": order.get(detail=True)}
Пример #25
0
    def post(self, request):
        # 获取到当前用户的id
        user = request.user
        # 获取到传入的参数
        dict_data = json.loads(request.body.decode())

        house_id = dict_data.get('house_id')
        start_date_str = dict_data.get('start_date')
        end_date_str = dict_data.get('end_date')

        # 校验参数
        if not all([house_id, start_date_str, end_date_str]):
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        try:
            start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
            end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
            assert start_date < end_date, Exception('开始日期大于结束日期')
            # 计算出入住天数
            days = (end_date - start_date).days
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        # 判断房屋是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"errno": RET.NODATA, "errmsg": "房屋不存在"})

        # 判断房屋是否是当前登录用户的
        if user.id == house.user.id:
            return http.JsonResponse({
                "errno": RET.ROLEERR,
                "errmsg": "不能订购自己的房间"
            })

        # 查询是否存在冲突的订单
        try:
            filters = {
                "house": house,
                "begin_date__lt": end_date,
                "end_date__gt": start_date
            }
            count = Order.objects.filter(**filters).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "数据库查询错误"})

        if count > 0:
            return http.JsonResponse({
                "errno": RET.DATAERR,
                "errmsg": "房间已经被预定"
            })

        amount = days * house.price
        # 生成订单的模型
        order = Order()
        order.user = user
        order.house = house
        order.begin_date = start_date
        order.end_date = end_date
        order.days = days
        order.house_price = house.price
        order.amount = amount

        try:
            order.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "数据库保存失败"})

        return http.JsonResponse({
            "errno": RET.OK,
            "errmsg": "发布成功",
            "data": {
                "order_id": order.pk
            }
        })
Пример #26
0
def order_view(key_id):
    order = Order.retrieve_by_id(key_id)
    if not order:
        return redirect(url_for('admin.order.orders_view'))
    return render_template('admin/order/order.html', order=order)
Пример #27
0
def new_list(request):
    orders = Order.query(Order.status == STATUS_ADD)
    return render_json_response([order.to_json() for order in orders])
Пример #28
0
    def get(self, *args, **kwargs):

        if not self.request.session.get('cart'):
            messages.error(self.request, 'Empty cart.')
            return redirect('product:list')

        if not self.request.user.is_authenticated:
            messages.error(self.request, 'Please, login or create account.')
            return redirect('costumer:create')

        cart = self.request.session.get('cart')
        cart_variation_ids = [v for v in cart]

        variations_db = list(
            Variation.objects.select_related('product').filter(
                id__in=cart_variation_ids))

        for variations in variations_db:
            vid = variations.id
            inventory = variations.inventory
            cart_qt = cart[vid]['quantity']
            price = cart[vid]['price']
            promotional_price = cart[vid]['promotional_price']

            error_msg_inventory = ''

            if inventory < cart_qt:
                cart[vid]['quantity'] = inventory
                cart[vid]['price'] = inventory * price
                cart[vid]['promotional_price'] = inventory * promotional_price
                error_msg_inventory = 'Some products had inventory changes. ' \
                                      'We reduced the quantities in your initial order.'

                if error_msg_inventory:
                    messages.info(
                        self.request,
                        error_msg_inventory,
                    )
                    self.request.save()
                    return redirect('product:cart')

        total_quantity_cart = utils.total_quantity_cart('cart')
        total_value_cart = utils.cart_total('cart')

        order = Order(
            user=self.request.user,
            total=total_value_cart,
            total_quantity=total_quantity_cart,
            status='C',
        )

        order.save()

        ItemOrder.objects.bulk_create([
            ItemOrder(
                order=order,
                product=v['product'],
                product_id=v['product_id'],
                variation=v['variation_name'],
                variation_id=v['variation_id'],
                price=v['quantitative_price'],
                promotional_price=v['quantitative_promotional_price'],
                image=v['image'],
            ) for v in cart.values()
        ])

        context = {
            'total_quantity_cart': total_quantity_cart,
            'total_value_cart': total_value_cart,
        }

        del self.request.session['cart']
        # return render(self.request, self.template_name, context)
        return redirect(reverse('order:payment', kwargs={
            'pk': order.pk,
        }))
Пример #29
0
def accept_list(request):
    orders = Order.query(Order.status == STATUS_ACCEPT)
    return render_json_response([order.to_json() for order in orders])
Пример #30
0
def complete_list(request):
    orders = Order.query(Order.status == STATUS_COMPLETE)
    return render_json_response([order.to_json() for order in orders])
Пример #31
0
    def post(self, request, *args, **kwargs):
        if request.POST.get('is_submitted'):
            cart_items = get_cart_items(self.request)
            total_weight = get_total_weight(cart_items=cart_items)
            client_data_cookie = self.request.COOKIES.get('client_data')
            client_data = cookie_parser(client_data_cookie)
            address = client_data.get('address')

            order = Order()
            order.client_name = address.get('client_name')
            order.payment = PaymentMethod.objects.get(
                method__exact=client_data.get('payment_method'))
            order.phone = address.get('phone')
            order.shipping_address = address.get('shipping_address')
            order.total_weight = total_weight
            order.delivery_price = get_delivery_price(cart_items)
            try:
                order.need_porter = int(client_data.get('need_porter'))
            except ValueError:
                pass

            if request.user.is_authenticated():
                order.customer = request.user

            if order.need_porter:
                order.porter_work_price = get_delivery_price(cart_items)
            order.shipping_time = datetime.fromtimestamp(
                client_data.get('time'), tz=pytz.timezone(settings.TIME_ZONE))
            order.save()

            total_price = 0

            json_data = []
            for cart_item in cart_items:
                cart_item.order = order
                total_price += cart_item.total_price
                cart_item.save()

                title = "{} {}".format(cart_item.variation.product.name,
                                       cart_item.variation.name)
                if cart_item.variation.color:
                    title = "{} {}".format(title,
                                           cart_item.variation.color.name)
                json_data.append({
                    'title': title,
                    'price': float(cart_item.variation.price),
                    'count': cart_item.count,
                    'total_price': float(cart_item.total_price)
                })
            order.products = json_data
            order.products_price = Decimal(total_price)
            order.order_unique_id = uuid.uuid4()

            order.total_price = order.products_price + get_delivery_price(
                cart_items)
            order.save()
            if order.payment.method == PaymentMethod.CASH_ON_DELIVERY:
                return redirect(
                    reverse_lazy('orders:order_detail',
                                 args=[order.phone, order.order_unique_id]))
            elif order.payment.method == PaymentMethod.PAYME:
                # https://checkout.paycom.uz/base64(m=587f72c72cac0d162c722ae2;ac.order_id=197;a=500)
                merchant_id = settings.PAYME_MERCHANT_ID
                ac_order_id = order.id
                ac_customer_id = order.phone
                amount = int(order.total_price.real) * 100
                redirect_url_after_operation = reverse_lazy(' basic:home')
                ct = 15
                cr = 860
                data = "m={};ac.order_id={};ac.customer_id={};a={};c={}".format(
                    merchant_id, ac_order_id, ac_customer_id, amount,
                    redirect_url_after_operation)
                base64_data = base64.b64encode(
                    data.encode('utf-8')).decode('utf-8')
                base64_data_url = "https://checkout.paycom.uz/{}".format(
                    base64_data)
                return redirect(to=base64_data_url)
            elif order.payment.method == PaymentMethod.UZCARD:
                return redirect(
                    reverse('orders:payment_uzcard',
                            args=[order.phone, order.order_unique_id]))
            else:
                return redirect(reverse(' basic:home'))
        return redirect(reverse(' basic:home'))