Example #1
0
def inquiry_part(request, pnumber):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    if request.method == 'POST':
        part = Product.objects.filter(partnumber=pnumber)
        name = request.POST['name']
        telephone = request.POST['telephone']
        e_mail = request.POST['e_mail']
        comment = request.POST['comment']
        order_mail_sus(part, e_mail, name, telephone, comment)
        return render(
            request, 'catalog/inquiry.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice,
                'part': part[0],
                'name': name,
                'telephone': telephone,
                'e_mail': e_mail,
                'comment': comment
            })
    else:

        return render(
            request, 'base.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
Example #2
0
def singup(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()

    args = {}

    args['form'] = SingupForm()
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice

    if request.method == 'POST':
        newuser_form = SingupForm(request.POST)
        if newuser_form.is_valid():
            newuser_form.save()
            newuser = auth.authenticate(
                username=newuser_form.cleaned_data['username'],
                password=newuser_form.cleaned_data['password2'])
            auth.login(request, newuser)

            return redirect('/')
        else:
            args['form'] = newuser_form

    return render(request, 'lk/registration.html', args)
Example #3
0
def invoice_update(request, id_invoice):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username
    url = request.META.get('HTTP_REFERER', '/')
    if request.user.is_authenticated() and request.user.is_staff:
        if request.method == "POST":
            i = 0
            for item in request.POST.getlist('pk'):
                iteminvoce = ItemInvoice.objects.get(invoice_id=id_invoice,
                                                     pk=item)
                iteminvoce.purchase_price = Decimal(
                    request.POST.getlist('price_in')[i])
                iteminvoce.quantity_in = int(request.POST.getlist('qty_in')[i])
                iteminvoce.save()
                i += 1
        return redirect(url, "supplier/invoice_detail.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #4
0
def draft_del(request, draft):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()

    args = dict(cart=Cart(request))
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.method == 'GET':
        if request.user.is_authenticated():
            args['username'] = auth.get_user(request).username
            draft_del = Draft.objects.get(
                pk=draft, accounts_id=auth.get_user(request).id)
            draft_del.delete()
            return redirect('/lk/drafts/', "draft/draft.html", args)

        else:
            # Отображение страницы с ошибкой
            args['login_errors'] = 'Войдите под своей учетной записью'
            args['username'] = auth.get_user(request).username

            return redirect('%s?next=%s' % ('/lk/login/', request.path), args)

    else:
        return render(request, "draft/draft.html", args)
Example #5
0
def search_brand(request, brand, partnumber):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    if request.method == 'GET':

        p = partnumber

        product = get_object_or_404(
            Product,
            partnumber=p,
            producer=ProductManufacturer.objects.get(name=brand))
        parts = Price.objects.filter(p_product=p)
        return render(
            request, 'catalog/products.html', {
                'parts': parts,
                'product': product,
                'p': p,
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
    else:

        return render(
            request, 'base.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
Example #6
0
def drafts(request):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()

    args = dict(cart=Cart(request))
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.method == 'GET':

        if request.user.is_authenticated():

            args['draft'] = Draft.objects.filter(
                accounts=auth.get_user(request))
            args['username'] = auth.get_user(request).username
            return render(request, "draft/draft.html", args)
        else:
            # Отображение страницы с ошибкой
            args['login_errors'] = 'Пользователь не найден!'
            args['username'] = auth.get_user(request).username

            return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
            # return render(request,"lk/login.html",args)
    else:
        return render(request, "draft/draft.html", args)
Example #7
0
def lk_order(request, id=1):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.user.is_authenticated():
        #if user is not None and user.is_active:
        # Правильный пароль и пользователь "активен"
        if request.method == 'POST':
            order = Order.objects.get(pk=id)
            order.status_id = int(request.POST['status'])
            order.save()

        itemorder = OrderPosition.objects.select_related().filter(order=id)
        order = Order.objects.get(pk=id)
        if request.user.is_staff:
            status = OrderStatus.objects.all()
            args['status'] = status
        args['numOrder'] = id
        args['statusO'] = itemorder[0].order.status
        args['order'] = itemorder
        args['orderPrice'] = order
        #auth.login(request, user)
        # Перенаправление на "правильную" страницу
        return render(request, "lk/order_detail.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #8
0
def custom_proc(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username
    return args
Example #9
0
def invoice_order(request, id_invoice):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    url = request.META.get('HTTP_REFERER', '/')
    if request.user.is_authenticated() and request.user.is_staff:
        if request.method == "POST":
            iteminvoice = ItemInvoice.objects.select_related().filter(
                invoice_id=id_invoice)
            for item in iteminvoice:
                #Обработка заявок
                for offer in item.offers.all():
                    itemoffer = ItemOffer.objects.get(offer_id=offer,
                                                      product=item.product,
                                                      stock=item.stock,
                                                      brand=item.brand)
                    itemoffer.status_offer = int(2)
                    itemoffer.save()
                    offeritem_count = ItemOffer.objects.filter(
                        offer_id=offer).count()
                    offeritem_count_status = ItemOffer.objects.filter(
                        offer_id=offer, status_offer=2).count()
                    if offeritem_count_status == offeritem_count:
                        offer_s = Offer.objects.get(pk=str(offer))
                        offer_s.status_id = int(3)
                        offer_s.save()
                # Обработка заказов с сайта
                for order in item.orders.all():
                    itemorder = OrderPosition.objects.get(order_id=order,
                                                          product=item.product,
                                                          id_stock=item.stock,
                                                          brand=item.brand)
                    itemorder.status_order = int(2)
                    itemorder.save()
                    orderitem_count = OrderPosition.objects.filter(
                        order_id=order).count()
                    orderitem_count_status = OrderPosition.objects.filter(
                        order_id=order, status_order=2).count()
                    if orderitem_count_status == orderitem_count:
                        order_s = Order.objects.get(pk=str(order))
                        order_s.status_id = int(3)
                        order_s.save()
            invoice = Invoice.objects.get(pk=id_invoice)
            invoice.status = int(1)
            invoice.save()
        return redirect(url, "supplier/invoice_detail.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #10
0
def custom_proc(request):
    "A context processor that provides 'app', 'user' and 'ip_address'."
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username
    return args
Example #11
0
def order_finish(request):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice

    if request.method == 'GET':
        if request.user.is_authenticated():
            # if user is not None and user.is_active:
            # Правильный пароль и пользователь "активен"
            id_order = request.session.get('id_order', None)
            if 'id_order' in request.session:
                del request.session['id_order']
            else:
                return redirect(url_referer, args)
            request.session.save()
            order = Order.objects.get(number_order=id_order)
            order_item = OrderPosition.objects.select_related().filter(
                order=id_order)
            delivery = 0
            for item in order_item:
                if delivery < item.id_stock.delivery_time:
                    delivery = item.id_stock.delivery_time

            now_date = datetime.date.today()
            delta = datetime.timedelta(days=delivery)  # дельта в днях
            now_date = now_date + delta  # Узнаем какое число будет через n дней
            args['delivery'] = now_date.strftime('%d.%m.%Y')
            args['order_position'] = order_item
            args[
                'name'] = request.user.last_name + ' ' + request.user.first_name
            args['phone'] = order.accounts.telephone
            args['order'] = order
            args['address'] = order.address

            args['username'] = auth.get_user(request).username

            # auth.login(request, user)
            # Перенаправление на "правильную" страницу
            return render(request, "orders/order_chekout.html", args)
        else:
            # Отображение страницы с ошибкой
            args['login_errors'] = 'Пользователь не найден!'
            args['username'] = auth.get_user(request).username

            return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
            # return render(request,"lk/login.html",args)
    else:
        return redirect(url_referer, args)
Example #12
0
def home(request):
    #form = SearchForm()
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()

    return render(
        request, 'slider.html', {
            'username': auth.get_user(request).username,
            'cartItem': cartItem,
            'cartTotal': totalprice
        })  #, {'form': form}
Example #13
0
def logout(request):
    url_referer = request.META.get('HTTP_REFERER', '/')
    #cartid=request.session['CART-ID']
    auth.logout(request)
    #request.session['CART-ID']=cartid
    #request.session.save()
    # Перенаправление на страницу.
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    return redirect(
        url_referer, {
            'username': auth.get_user(request).username,
            'cartItem': cartItem,
            'cartTotal': totalprice
        })
Example #14
0
def user_detail(request, username):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.user.is_authenticated():
        # if user is not None and user.is_active:
        # Правильный пароль и пользователь "активен"
        # if request.method == 'POST':
        #     if request.user.is_staff:
        #         find_str = ''
        #         if find_str != '':
        #             orders = Order.objects.filter(Q(number_order__icontains=find_str) |
        #                                           Q(accounts__telephone__icontains=find_str) |
        #                                           Q(accounts__first_name__icontains=find_str) |
        #                                           Q(accounts__last_name__icontains=find_str))
        #         if request.user.is_staff:
        #             form = FindOrderUsers()
        #             form.fields['status'].choices = [(x.pk, x) for x in OrderStatus.objects.all()]
        #             args['find_form'] = form
        #
        #         return render(request, "lk/lk_users.html", args)
        #     else:
        #         return render(request, "lk/lk_users.html", args)
        # else:
        if request.user.is_staff:
            account = Accounts.objects.get(pk=username)
            orders = Order.objects.filter(accounts=account)
            history_pay = BalanceHistoryAccounts.objects.filter(
                account=username)
            args['account'] = account
            args['orders'] = orders
            args['history_pay'] = history_pay
        return render(request, "lk/user_detail.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #15
0
def add_to_draft_old(request):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()

    args = dict(cart=Cart(request))
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.method == 'POST':
        if request.user.is_authenticated():
            draft = get_object_or_404(Draft,
                                      pk=int(request.POST['draft']),
                                      accounts_id=auth.get_user(request).id)
            itemD = ItemD.objects.filter(draft=draft)

            for item in cart:
                flagItem = 0
                for draft_item in itemD:
                    if item.product == draft_item.product and item.stock.pk == draft_item.stock.pk and item.brand == draft_item.brand:
                        draft_item.quantity += item.quantity
                        draft_item.save()
                        flagItem = 1
                if flagItem != 1:
                    itemd = ItemD()
                    itemd.draft = draft
                    itemd.product = item.product
                    itemd.stock = Stock.objects.get(pk=item.stock.pk)
                    itemd.quantity = item.quantity
                    itemd.unit_price = item.unit_price
                    itemd.brand = item.brand
                    itemd.save()

            cart.clear()
            cartItem = cart.count()
            totalprice = cart.summary()
            args['cartItem'] = cartItem
            args['cartTotal'] = totalprice

            return redirect('/lk/drafts/', "draft/draft.html", args)
        else:
            return render(request, "cart/cart.html", args)

    else:
        return render(request, "cart/cart.html", args)
Example #16
0
def get_invoces(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.user.is_authenticated() and request.user.is_staff:
        invoices = Invoice.objects.all()
        args['invoices'] = invoices
        return render(request, "supplier/invoices.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #17
0
def offer_item_del(request, product, stock, offer, brand):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()

    args = dict(cart=Cart(request))

    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.method == 'GET':
        if request.user.is_authenticated() and request.user.is_staff:
            args['username'] = auth.get_user(request).username
            itemOffer = ItemOffer.objects.get(
                offer_id=offer,
                # поставил заглушку от дублей вместо get
                product=Product.objects.filter(partnumber=product,
                                               producer_id=brand)[0],
                stock_id=stock,
                brand_id=brand,
            )
            itemOffer.delete()
            offerN = ItemOffer.objects.select_related().filter(offer_id=offer)
            if len(offerN) == 0:
                offer_del = Offer.objects.get(pk=offer)
                offer_del.delete()
                return redirect('/lk/offers/', "offer/offers.html", args)
            else:
                args['offer'] = offerN
                return redirect('/lk/offer_detail/' + offer + '/',
                                "offer/offer_detail.html", args)
        else:
            # Отображение страницы с ошибкой
            args['login_errors'] = 'Войдите под своей учетной записью'
            args['username'] = auth.get_user(request).username

            return redirect('%s?next=%s' % ('/lk/login/', request.path), args)

    else:
        return render(request, "offer/offers.html", args)
Example #18
0
def draft_item_del(request, product, stock, draft, brand):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()

    args = dict(cart=Cart(request))
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.method == 'GET':
        if request.user.is_authenticated():
            args['username'] = auth.get_user(request).username
            itemd = ItemD.objects.get(
                draft_id=draft,
                # поставил заглушку от дублей вместо get
                product=Product.objects.filter(partnumber=product,
                                               producer_id=brand)[0],
                stock_id=stock,
                brand_id=brand,
            )
            itemd.delete()
            draftN = ItemD.objects.select_related().filter(draft_id=draft)
            if len(draftN) == 0:
                draft_del = Draft.objects.get(pk=draft)
                draft_del.delete()
                return redirect('/lk/drafts/', "draft/draft.html", args)
            else:
                args['draft'] = draftN
                return redirect('/lk/draft_detail/' + draft + '/',
                                "draft/draft_detail.html", args)
        else:
            # Отображение страницы с ошибкой
            args['login_errors'] = 'Войдите под своей учетной записью'
            args['username'] = auth.get_user(request).username

            return redirect('%s?next=%s' % ('/lk/login/', request.path), args)

    else:
        return render(request, "draft/draft.html", args)
Example #19
0
def to_all_bmw(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    if request.method == 'GET':

        return render(
            request, 'to_all_bmw.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
    else:

        return render(
            request, 'base.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
Example #20
0
def draft_detail(request, id=1):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()

    args = dict(cart=Cart(request))
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.method == 'GET':
        if request.user.is_authenticated():
            draft = get_object_or_404(Draft,
                                      pk=id,
                                      accounts_id=auth.get_user(request).id)
            item_draft = ItemD.objects.select_related().filter(draft_id=id)

            for item in item_draft:
                # дописать проверку на бренд!!!!!!!!
                price = Price.objects.filter(p_product=item.product,
                                             id_stock=item.stock)
                if price[0].our_price != item.unit_price:
                    item.unit_price = price[0].our_price
                    item.save()

            item_draft = ItemD.objects.select_related().filter(draft_id=id)
            args['draftName'] = draft
            args['draft'] = item_draft
            args['username'] = auth.get_user(request).username
            return render(request, "draft/draft_detail.html", args)
        else:
            # Отображение страницы с ошибкой
            args['login_errors'] = 'Войдите под своей учетной записью'
            args['username'] = auth.get_user(request).username

            return redirect('%s?next=%s' % ('/lk/login/', request.path), args)

    else:
        return render(request, "draft/draft.html", args)
Example #21
0
def singup(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()

    args = {}

    args['form'] = SingupForm()
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice

    if request.method == 'POST':
        newuser_form = SingupForm(request.POST)
        if newuser_form.is_valid():
            recaptcha_response = request.POST.get('g-recaptcha-response')
            url = 'https://www.google.com/recaptcha/api/siteverify'
            values = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': recaptcha_response
            }
            data = urllib.urlencode(values)
            req = urllib2.Request(url, data)
            response = urllib2.urlopen(req)
            result = json.load(response)
            if result['success']:
                newuser_form.save()
                newuser = auth.authenticate(
                    username=newuser_form.cleaned_data['username'],
                    password=newuser_form.cleaned_data['password2'])
                auth.login(request, newuser)
                messages.success(request, u'Вы успешно зарегистрировались')
                return redirect('/lk/')
            else:
                messages.error(request, u'Вы не правильно ввели CAPTCHA')
                args['form'] = newuser_form
                args['messages'] = messages
                return render(request, 'lk/registration.html', args)
        else:
            args['form'] = newuser_form

    return render(request, 'lk/registration.html', args)
Example #22
0
def del_invoice(request, id_invoice):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.user.is_authenticated() and request.user.is_staff:
        invoice = Invoice.objects.get(pk=id_invoice)
        itemInvoice = ItemInvoice.objects.filter(invoice=id_invoice)
        itemInvoice.delete()
        invoice.delete()
        return redirect('/lk/invoices/', "supplier/invoices.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #23
0
def add_to_draft(request):
    url_referer = request.META.get('HTTP_REFERER', '/')
    cart = Cart(request)

    cartItem = cart.count()
    totalprice = cart.summary()

    args = dict(cart=Cart(request))
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.method == 'POST':
        if len(request.POST['name_draft']
               ) > 2 and request.user.is_authenticated():
            draft = Draft()
            draft.name = request.POST['name_draft']
            draft.creation_date = datetime.datetime.now()
            draft.accounts = Accounts.objects.get(
                username=auth.get_user(request))
            draft.save()

            for item in cart:
                itemd = ItemD()
                itemd.draft = draft
                itemd.product = item.product
                itemd.stock = Stock.objects.get(pk=item.stock.pk)
                itemd.quantity = item.quantity
                itemd.unit_price = item.unit_price
                itemd.brand = item.brand
                itemd.save()

            cart.clear()
            cartItem = cart.count()
            totalprice = cart.summary()
            args['cartItem'] = cartItem
            args['cartTotal'] = totalprice

            return redirect('/lk/drafts/', "draft/draft.html", args)
        else:
            return redirect('/cart/', "cart/cart.html", args)

    else:
        return render(request, "cart/cart.html", args)
Example #24
0
def oil_tech(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    if request.method == 'GET':
        products_oil = Product.objects.filter(category_id=2)
        products_tehnical = Product.objects.filter(category_id=3)
        return render(
            request, 'teh_oil.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice,
                'products_oil': products_oil,
                'products_tehnical': products_tehnical
            })
    else:

        return render(
            request, 'base.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
Example #25
0
def lk(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.user.is_authenticated():
        #if user is not None and user.is_active:
        # Правильный пароль и пользователь "активен"
        balance_history = BalanceHistoryAccounts.objects.filter(
            account_id=request.user.id)
        args['balance_history'] = balance_history
        #auth.login(request, user)
        # Перенаправление на "правильную" страницу
        return render(request, "lk/lk.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #26
0
def login(
    request
):  # периписать все как логин все!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}

    if 'login_errors' not in request.session:
        request.session['login_errors'] = ''

    if request.session['login_errors'] != '':
        args['login_errors'] = request.session['login_errors']
        request.session['login_errors'] = ''
        request.session.save()

    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    url_referer_next = request.META.get('HTTP_REFERER', '/')
    #print url_referer_next

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None:  #and user.is_active
            # Правильный пароль и пользователь "активен"
            if user.accounts.cart_id == 0:
                #print(user.accounts.cart_id)
                user.accounts.cart_id = request.session['CART-ID']
                user.accounts.save()
                #print(user.accounts.cart_id)
            else:
                request.session['CART-ID'] = user.accounts.cart_id
                request.session.save()
                cart = Cart(request)
                cartItem = cart.count()
                totalprice = cart.summary()
                args['cartItem'] = cartItem
                args['cartTotal'] = totalprice

            auth.login(request, user)
            # Перенаправление на "правильную" страницу
            args['username'] = auth.get_user(request).username

            return redirect('/lk/', args)
        else:
            # Отображение страницы с ошибкой
            #args['login_errors']='Пользователь не найден!'
            request.session[
                'login_errors'] = 'Данный пользователь не существует или указана не правильная пара Логин и Пароль!'
            request.session.save()
            return redirect('/lk/login/', args)
    else:
        if request.user.is_authenticated():
            args['username'] = auth.get_user(request).username
            cart = Cart(request)
            cartItem = cart.count()
            totalprice = cart.summary()
            args['cartItem'] = cartItem
            args['cartTotal'] = totalprice
        return render(request, "lk/login.html", args)
Example #27
0
def model_to(request, series, kuzov=None, motor=None):

    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    if request.method == 'GET':

        if series and motor == None:
            if series == '1' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/kuzov/F20.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/kuzov/E87.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == '2' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == '3' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == '4' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == '5' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == '6' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == '7' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == 'i8' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == 'X1' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == 'i8' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == 'X3' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == 'X4' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == 'X5' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            if series == 'X6' and motor == None:
                models = [{
                    'model': 'F20',
                    'img': '/img/models/3_Series.png',
                    'motor': ['116i', '125i', '135i', '120d']
                }, {
                    'model': 'E87',
                    'img': '/img/models/2_Series.png',
                    'motor': ['116i', '118i', '120i', '130i', '120d']
                }]

            return render(
                request, 'model_to.html', {
                    'username': auth.get_user(request).username,
                    'cartItem': cartItem,
                    'cartTotal': totalprice,
                    'models': models,
                    'series': series
                })

        if series and motor != None:
            parts = {}
            if series == '1' and motor == '116i' and kuzov == 'F20':
                parts = {
                    'oil_filter': '11427635557',
                    'air_filter': '13718507320',
                    'salon_filter': '64119237555',
                    'break_front': '34116858910',
                    'break_rear': '34216873093',
                    'disc_brake_front': '34116792215',
                    'disc_brake_rear': '34216792225',
                    'sensor_brake_front': '34356792289',
                    'sensor_brake_rear': '34356792292'
                }

            if series == '1' and motor == '125i' and kuzov == 'F20':
                parts = {
                    'oil_filter': '11428683204',
                    'air_filter': '13718507320',
                    'salon_filter': '64119237555',
                    'break_front': '34106859181',
                    'break_rear': '34216873093',
                    'disc_brake_front': '34116792219',
                    'disc_brake_rear': '34216792227',
                    'sensor_brake_front': '34356792289',
                    'sensor_brake_rear': '34356792292'
                }

            if series == '1' and motor == '135i' and kuzov == 'F20':
                parts = {
                    'oil_filter': '11427566327',
                    'air_filter': '13718616909',
                    'salon_filter': '64119237555',
                    'break_front': '34116878876',
                    'break_rear': '34216876422',
                    'disc_brake_front': '34116792223',
                    'disc_brake_rear': '34206797605',
                    'sensor_brake_front': '34356792289',
                    'sensor_brake_rear': '34356792292'
                }

            if series == '1' and motor == '120d' and kuzov == 'F20':
                parts = {
                    'oil_filter': '11428507683',
                    'air_filter': '13718511668',
                    'salon_filter': '64119237555',
                    'break_front': '34116850568',
                    'break_rear': '34216873093',
                    'disc_brake_front': '34116792217',
                    'disc_brake_rear': '34216792227',
                    'sensor_brake_front': '34356792289',
                    'sensor_brake_rear': '34356792292'
                }
            if len(parts) > 0:
                return render(
                    request, 'model_to.html', {
                        'username': auth.get_user(request).username,
                        'cartItem': cartItem,
                        'cartTotal': totalprice,
                        'parts': parts,
                        'series': series,
                        'motor': motor,
                        'kuzov': kuzov
                    })
            else:
                page_not = u'Страница находится в разработке и скоро появится!'
                return render(
                    request, 'model_to.html', {
                        'username': auth.get_user(request).username,
                        'cartItem': cartItem,
                        'cartTotal': totalprice,
                        'page_not': page_not
                    })
        page_not = u'Страница находится в разработке и скоро появится!'
        return render(
            request, 'model_to.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice,
                'page_not': page_not
            })
    else:

        return render(
            request, 'base.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
Example #28
0
def search(request, brand=None, partnumber=None):
    # if this is a POST request we need to process the form data
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()

    if request.method == 'GET':
        url_referer = request.META.get('HTTP_REFERER', '/')
        if brand != None and partnumber != None:
            product = Product.objects.filter(partnumber=partnumber,
                                             producer__name=brand)
            p = partnumber
            p_null = 0
            if p.startswith('0'):
                for n in p:
                    if n == '0':
                        p_null += 1
                    else:
                        break
                p = p[p_null:]
        else:
            pn = request.GET['partnumber']
            reg = re.compile('[^a-zA-Z0-9]')
            p = reg.sub('', pn)
            p_null = 0
            if p.startswith('0'):
                for n in p:
                    if n == '0':
                        p_null += 1
                    else:
                        break
                p = p[p_null:]

        #Ищем номер в базе


#найти способ искать запчать по производителю
#product = Product.objects.filter(partnumber=p).values('partnumber','producer').order_by().distinct()

            product = Product.objects.filter(partnumber=p)
        # Если не нашли

        if len(product) == 0:
            if 'lk/offer_detail/' in url_referer:
                if 'error_request' not in request.session:
                    request.session[
                        'error_request'] = 'У нас в каталоге нет такой запчасти!'
                    request.session.save()
                return redirect(
                    url_referer, 'offer/offer_detail.html', {
                        'p': p,
                        'username': auth.get_user(request).username,
                        'cartItem': cartItem,
                        'cartTotal': totalprice
                    })
            else:
                return render(
                    request, 'catalog/products.html', {
                        'p': p,
                        'error_request':
                        'У нас в каталоге нет такой запчасти!',
                        'username': auth.get_user(request).username,
                        'cartItem': cartItem,
                        'cartTotal': totalprice
                    })
        # Если нашли больше одного номера выводим на экран пользователю для выбора
        if len(product) > 1:
            return render(
                request, 'catalog/products.html', {
                    'p': p,
                    'many_products': product,
                    'username': auth.get_user(request).username,
                    'cartItem': cartItem,
                    'cartTotal': totalprice
                })
        else:
            #ПОИСК не оригинала
            user = auth.get_user(request)
            if user.is_authenticated:
                u_discount = user.accounts.discount
            else:
                u_discount = 0

            cross_parts = []
            no_price_cross_parts = []
            if len(p) < 11:
                cross_p = CrossProduct.objects.filter(
                    crossnumber__icontains='---' + p + '---')
            else:
                cross_p = CrossProduct.objects.filter(crossnumber__icontains=p)

            corss_p_uniq = set()

            for c_p_u in cross_p:
                cross_sep = c_p_u.crossnumber.split('---')
                for c_sep in cross_sep:
                    corss_p_uniq.add(c_sep)

            if len(cross_p) > 0:
                # if len(cross_p)==1:
                #     cross = cross_p.crossnumber.split('---')
                # else:
                #     cross=cross_p[0].crossnumber.split('---')

                # for c_p in corss_p_uniq:
                #     cross = c_p.crossnumber.split('---')
                #     cross_product = Product.objects.filter(partnumber__in=cross)
                #print corss_p_uniq
                c = Price.objects.select_related().filter(
                    p_product__in=corss_p_uniq)
                #print c
                for price in c:
                    if price.p_product != p:
                        product_cross = Product.objects.select_related(
                        ).filter(partnumber=price.p_product).values(
                            'description', 'producer',
                            'producer__name').order_by().distinct()
                        utc_3 = datetime.timedelta(hours=3)
                        date_price = price.created_at + utc_3
                        cross_dict = {
                            'stock': price.id_stock.name_stock,
                            'producer': product_cross[0].get('producer__name'),
                            'p_product': price.p_product,
                            'description': product_cross[0].get('description'),
                            'qty': price.qty,
                            'delivery_time': price.id_stock.delivery_time,
                            'purchase_price': str(price.purchase_price),
                            'our_price': str(price.our_price),
                            'id_stock': price.id_stock.pk,
                            'pk': price.pk,
                            'producer_pk': product_cross[0].get('producer'),
                            'created_at':
                            date_price.strftime("%d %B %Y г. %H:%M"),
                        }
                        if user.is_authenticated and u_discount > 0:
                            cross_dict['our_price_discount'] = str(
                                dicsount_user(u_discount, price.our_price))
                        cross_parts.append(cross_dict)

                # for cp in cross_product:
                #    if cp.partnumber != p:
                #            c = Price.objects.select_related().filter(p_product=cp.partnumber)
                #            if len(c) > 0:
                #                cross_dict = {'partnumber': cp.partnumber,
                #                              'description': cp.description,
                #                              'producer': cp.producer,
                #                              'qty': c[0].qty,
                #                              'price_in': c[0].purchase_price,
                #                              'delivery_time':c[0].id_stock.delivery_time,
                #                              'our_price':c[0].our_price,
                #                              'stock':c[0].id_stock.pk,
                #                              'id_price':c[0].pk}
                #                cross_parts.append(cross_dict)
                #            else:
                #                no_price_cross_parts.append(cp)

            parts = Price.objects.filter(p_product=p)
            if u_discount > 0:
                parts1 = []
                for p in parts:
                    p_dict = {
                        'p_product':
                        p.p_product,
                        'id_stock':
                        p.id_stock,
                        'qty':
                        p.qty,
                        'purchase_price':
                        p.purchase_price,
                        'our_price':
                        p.our_price,
                        'our_price_discount':
                        dicsount_user(u_discount, p.our_price),
                        'brand':
                        p.brand,
                        'dealer_price':
                        p.dealer_price,
                        'created_at':
                        p.created_at,
                        'pk':
                        p.pk
                    }
                    parts1.append(p_dict)
                parts = parts1
                # redirect to a new URL:

            if len(parts) > 0:
                if 'lk/offer_detail/' in url_referer:
                    if 'offer' not in request.session:
                        request.session['offer'] = list()
                        for price in parts:
                            stock = price.id_stock.name_stock
                            producer = product[0].producer.name
                            description = product[0].description
                            request.session['offer'].append({
                                'stock':
                                stock,
                                'producer':
                                producer,
                                'p_product':
                                price.p_product,
                                'description':
                                description,
                                'qty':
                                price.qty,
                                'delivery_time':
                                price.id_stock.delivery_time,
                                'purchase_price':
                                str(price.purchase_price),
                                'our_price':
                                str(price.our_price),
                                'dealer_price':
                                str(price.dealer_price),
                                'created_at':
                                str(price.created_at),
                                'id_stock':
                                price.id_stock.pk,
                                'pk':
                                price.pk,
                                'producer_pk':
                                product[0].producer.pk,
                            })
                        if 'offer_cross' not in request.session:
                            request.session['offer_cross'] = cross_parts
                        else:
                            del request.session['offer_cross']
                            request.session['offer_cross'] = cross_parts
                    else:
                        if 'offer_cross' not in request.session:
                            request.session['offer_cross'] = cross_parts
                        else:
                            del request.session['offer_cross']
                            request.session['offer_cross'] = cross_parts

                        del request.session['offer']
                        request.session['offer'] = list()
                        for price in parts:
                            stock = price.id_stock.name_stock
                            producer = product[0].producer.name
                            description = product[0].description
                            request.session['offer'].append({
                                'stock':
                                stock,
                                'producer':
                                producer,
                                'p_product':
                                price.p_product,
                                'description':
                                description,
                                'qty':
                                price.qty,
                                'delivery_time':
                                price.id_stock.delivery_time,
                                'purchase_price':
                                str(price.purchase_price),
                                'our_price':
                                str(price.our_price),
                                'dealer_price':
                                str(price.dealer_price),
                                'created_at':
                                str(price.created_at),
                                'id_stock':
                                price.id_stock.pk,
                                'pk':
                                price.pk,
                                'producer_pk':
                                product[0].producer.pk,
                            })
                    request.session.save()
                    return redirect(
                        url_referer, 'offer/offer_detail.html', {
                            'username': auth.get_user(request).username,
                            'cartItem': cartItem,
                            'cartTotal': totalprice
                        })

                else:

                    return render(
                        request, 'catalog/products.html', {
                            'parts': parts,
                            'producer': unicode(product[0].producer),
                            'descript': unicode(product[0].description),
                            'cross_parts': cross_parts,
                            'no_price_cross_parts': no_price_cross_parts,
                            'product': product[0],
                            'p': p,
                            'username': auth.get_user(request).username,
                            'cartItem': cartItem,
                            'cartTotal': totalprice
                        })

            else:
                if 'lk/offer_detail/' in url_referer:
                    if 'no_price_offer' not in request.session:
                        request.session['no_price_offer'] = list()
                        producer = product[0].producer.name
                        description = product[0].description
                        request.session['no_price_offer'].append({
                            'producer':
                            producer,
                            'partnumber':
                            product[0].partnumber,
                            'description':
                            description,
                        })
                        if 'offer_cross' not in request.session:
                            request.session['offer_cross'] = cross_parts
                        else:
                            del request.session['offer_cross']
                            request.session['offer_cross'] = cross_parts
                    else:
                        if 'offer_cross' not in request.session:
                            request.session['offer_cross'] = cross_parts
                        else:
                            del request.session['offer_cross']
                            request.session['offer_cross'] = cross_parts

                        del request.session['no_price_offer']
                        request.session['no_price_offer'] = list()
                        producer = product[0].producer.name
                        description = product[0].description
                        request.session['no_price_offer'].append({
                            'producer':
                            producer,
                            'partnumber':
                            product[0].partnumber,
                            'description':
                            description,
                        })
                    request.session.save()
                    return redirect(
                        url_referer, 'offer/offer_detail.html', {
                            'username': auth.get_user(request).username,
                            'cartItem': cartItem,
                            'cartTotal': totalprice
                        })
                return render(
                    request, 'catalog/products.html', {
                        'no_price': product[0],
                        'descript': product[0].description,
                        'producer': product[0].producer,
                        'cross_parts': cross_parts,
                        'no_price_cross_parts': no_price_cross_parts,
                        'p': p,
                        'username': auth.get_user(request).username,
                        'cartItem': cartItem,
                        'cartTotal': totalprice
                    })

    # if a GET (or any other method) we'll create a blank form
    else:
        return render(
            request, 'base.html', {
                'username': auth.get_user(request).username,
                'cartItem': cartItem,
                'cartTotal': totalprice
            })
Example #29
0
def make_invoices(request):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    if request.user.is_authenticated() and request.user.is_staff:
        itemOffer = ItemOffer.objects.select_related().filter(
            offer__status_id=2, status_offer=0).order_by('stock')
        itemOrder = OrderPosition.objects.select_related().filter(
            order__status_id=2, status_order=0).order_by('id_stock')
        stock_list = listmerge1([item.stock.pk for item in itemOffer],
                                [item.id_stock.pk for item in itemOrder])
        suppliers = Supplier.objects.filter(stock__in=stock_list).distinct()

        for sup in suppliers:
            for stk in sup.stock.all():
                # Обработка заявок
                if len(itemOffer.filter(stock=stk)) or len(
                        itemOrder.filter(id_stock=stk)):
                    invoice = Invoice()
                    invoice.supplier = sup
                    invoice.stock_sup = stk
                    invoice.save()

                    for item in itemOffer.filter(
                            stock=stk, offer__status_id=2).order_by('product'):
                        try:
                            iteminvoice = ItemInvoice.objects.get(
                                invoice=invoice,
                                product=item.product,
                                stock=item.stock,
                                brand=item.brand,
                            )
                        except ItemInvoice.DoesNotExist:
                            iteminvoice = ItemInvoice()
                            iteminvoice.invoice = invoice
                            iteminvoice.quantity = item.quantity
                            iteminvoice.quantity_in = item.quantity
                            iteminvoice.purchase_price = item.purchase_price
                            iteminvoice.product = item.product
                            iteminvoice.stock = item.stock
                            iteminvoice.brand = item.brand
                            iteminvoice.save()
                            iteminvoice.offers.add(item.offer)
                            iteminvoice.save()
                            item.status_offer = 1
                            item.invoice = invoice
                            item.save()

                        else:  # ItemAlreadyExists
                            iteminvoice.quantity += item.quantity
                            iteminvoice.quantity_in += item.quantity
                            iteminvoice.offers.add(item.offer)
                            iteminvoice.save()
                            item.status_offer = 1
                            item.invoice = invoice
                            item.save()

                # Обработка ЗАКАЗОВ
                    for item in itemOrder.filter(
                            id_stock=stk,
                            order__status_id=2).order_by('product'):
                        try:
                            iteminvoice = ItemInvoice.objects.get(
                                invoice=invoice,
                                product=item.product,
                                stock=item.id_stock,
                                brand=item.brand,
                            )
                        except ItemInvoice.DoesNotExist:
                            iteminvoice = ItemInvoice()
                            iteminvoice.invoice = invoice
                            iteminvoice.quantity = item.count
                            iteminvoice.quantity_in = item.count
                            iteminvoice.purchase_price = item.price_purchase
                            iteminvoice.product = item.product
                            iteminvoice.stock = item.id_stock
                            iteminvoice.brand = item.brand
                            iteminvoice.save()
                            iteminvoice.orders.add(item.order)
                            iteminvoice.save()
                            item.status_order = 1
                            item.invoice = invoice
                            item.save()

                        else:  # ItemAlreadyExists
                            iteminvoice.quantity += item.count
                            iteminvoice.quantity_in += item.count
                            iteminvoice.orders.add(item.order)
                            iteminvoice.save()
                            item.status_order = 1
                            item.invoice = invoice
                            item.save()

        invoices = Invoice.objects.all()
        args['invoices'] = invoices
        return render(request, "supplier/invoices.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
Example #30
0
def invoice_accept(request, id_invoice):
    cart = Cart(request)
    cartItem = cart.count()
    totalprice = cart.summary()
    args = {}
    args['cartItem'] = cartItem
    args['cartTotal'] = totalprice
    args['username'] = auth.get_user(request).username

    url = request.META.get('HTTP_REFERER', '/')
    if request.user.is_authenticated() and request.user.is_staff:
        if request.method == "POST":
            iteminvoice = ItemInvoice.objects.select_related().filter(
                invoice_id=id_invoice)
            for item in iteminvoice:
                offersort = item.offers.all().order_by('created_at')
                ordersort = item.orders.all().order_by('created_at')

                count_out = item.quantity
                count_in = item.quantity_in

                # Обработка заказов
                for order in ordersort:
                    itemorder = OrderPosition.objects.get(order_id=order,
                                                          product=item.product,
                                                          id_stock=item.stock,
                                                          brand=item.brand)
                    if count_in == count_out:
                        itemorder.status_order = 3
                        itemorder.price_purchase = item.purchase_price
                        itemorder.save()

                        orderitem_count = OrderPosition.objects.filter(
                            order_id=order).count()
                        orderitem_count_status = OrderPosition.objects.filter(
                            order_id=order, status_order=3).count()

                        if orderitem_count_status == orderitem_count:
                            order_s = Order.objects.get(
                                number_order=str(order))
                            order_s.status_id = int(4)
                            order_s.save()
                    else:
                        if count_out > count_in:

                            if itemorder.count <= count_in:
                                itemorder.status_order = 3
                                itemorder.price_purchase = item.purchase_price
                                itemorder.save()

                                orderitem_count = OrderPosition.objects.filter(
                                    order_id=order).count()
                                orderitem_count_status = OrderPosition.objects.filter(
                                    order_id=order, status_order=3).count()
                                if orderitem_count_status == orderitem_count:
                                    order_s = Order.objects.get(
                                        number_order=str(order))
                                    order_s.status_id = int(4)
                                    order_s.save()
                                count_in -= itemorder.count
                            else:
                                if count_in != 0:
                                    itemCount_in = itemorder.count - count_in
                                    itemorder.count -= itemCount_in
                                    itemorder.save()

                                    account = Accounts.objects.get(
                                        pk=order.accounts_id)
                                    account.balance += Decimal(
                                        itemCount_in * itemorder.price_sale)
                                    account.save()
                                    balance = BalanceHistoryAccounts()
                                    balance.balance_price = Decimal(
                                        itemCount_in * itemorder.price_sale)
                                    balance.account = account
                                    balance.operations = '' \
                                                         'Возврат средств по заказу №' + str(order) + '' \
                                                                                                      ' не пришла запчасть ' + str(
                                        itemorder.product) + '' \
                                                             ' в колличестве ' + str(itemCount_in) + ' штук'

                                    balance.save()

                                    count_in = 0

                                    itemorder.status_offer = 4
                                    itemorder.price_purchase = item.purchase_price
                                    itemorder.save()
                                    order_s = Order.objects.get(
                                        number_order=str(order))
                                    order_s.status_id = int(7)
                                    order_s.save()
                                else:

                                    account = Accounts.objects.get(
                                        pk=order.accounts_id)
                                    account.balance += Decimal(
                                        itemorder.count * itemorder.price_sale)
                                    account.save()
                                    balance = BalanceHistoryAccounts()
                                    balance.balance_price = Decimal(
                                        itemorder.count * itemorder.price_sale)
                                    balance.account = account
                                    balance.operations = 'Возврат средств по заказу №' + str(order) + '' \
                                                                                                      ' не пришла запчасть ' + str(
                                        itemorder.product) + '' \
                                                             ' в колличестве ' + str(itemorder.count) + ' штук'

                                    balance.save()

                                    itemorder.status_offer = 4
                                    itemorder.price_purchase = item.purchase_price
                                    itemorder.count = 0
                                    itemorder.save()
                                    order_s = Order.objects.get(
                                        number_order=str(order))
                                    order_s.status_id = int(7)
                                    order_s.save()

            #Обработка заявок
                for offer in offersort:
                    itemoffer = ItemOffer.objects.get(offer_id=offer,
                                                      product=item.product,
                                                      stock=item.stock,
                                                      brand=item.brand)
                    if count_in == count_out:
                        itemoffer.status_offer = 3
                        itemoffer.purchase_price = item.purchase_price
                        itemoffer.save()

                        offeritem_count = ItemOffer.objects.filter(
                            offer_id=offer).count()
                        offeritem_count_status = ItemOffer.objects.filter(
                            offer_id=offer, status_offer=3).count()
                        if offeritem_count_status == offeritem_count:
                            offer_s = Offer.objects.get(pk=str(offer))
                            offer_s.status_id = int(4)
                            offer_s.save()
                    else:
                        if count_out > count_in:

                            if itemoffer.quantity <= count_in:
                                itemoffer.status_offer = 3
                                itemoffer.purchase_price = item.purchase_price
                                itemoffer.save()

                                offeritem_count = ItemOffer.objects.filter(
                                    offer_id=offer).count()
                                offeritem_count_status = ItemOffer.objects.filter(
                                    offer_id=offer, status_offer=3).count()
                                if offeritem_count_status == offeritem_count:
                                    offer_s = Offer.objects.get(pk=str(offer))
                                    offer_s.status_id = int(4)
                                    offer_s.save()
                                count_in -= itemoffer.quantity
                            else:
                                if count_in != 0:
                                    itemCount_in = itemoffer.quantity - count_in
                                    itemoffer.quantity -= itemCount_in
                                    itemoffer.save()

                                    customer = Customer.objects.get(
                                        pk=offer.customer_id)
                                    customer.balance += Decimal(
                                        itemCount_in *
                                        itemoffer.unit_price_discount)
                                    customer.save()
                                    balance = BalanceHistory()
                                    balance.balance_price = Decimal(
                                        itemCount_in *
                                        itemoffer.unit_price_discount)
                                    balance.customer = customer
                                    balance.operations = 'Возврат средств по заказу №'+str(offer)+'' \
                                                         ' не пришла запчасть '+str(itemoffer.product)+'' \
                                                         ' в колличестве '+str(itemCount_in)+' штук'

                                    balance.save()

                                    count_in = 0

                                    itemoffer.status_offer = 4
                                    itemoffer.purchase_price = item.purchase_price
                                    itemoffer.save()
                                    offer_s = Offer.objects.get(pk=str(offer))
                                    offer_s.status_id = int(7)
                                    offer_s.save()
                                else:

                                    customer = Customer.objects.get(
                                        pk=offer.customer_id)
                                    customer.balance += Decimal(
                                        itemoffer.quantity *
                                        itemoffer.unit_price_discount)
                                    customer.save()
                                    balance = BalanceHistory()
                                    balance.balance_price = Decimal(
                                        itemoffer.quantity *
                                        itemoffer.unit_price_discount)
                                    balance.customer = customer
                                    balance.operations = 'Возврат средств по заказу №' + str(offer) + '' \
                                                         ' не пришла запчасть ' + str(itemoffer.product) + '' \
                                                         ' в колличестве ' + str(itemoffer.quantity) + ' штук'

                                    balance.save()

                                    itemoffer.status_offer = 4
                                    itemoffer.purchase_price = item.purchase_price
                                    itemoffer.quantity = 0
                                    itemoffer.save()
                                    offer_s = Offer.objects.get(pk=str(offer))
                                    offer_s.status_id = int(7)
                                    offer_s.save()

            invoice = Invoice.objects.get(pk=id_invoice)
            invoice.status = int(2)
            invoice.save()
        return redirect(url, "supplier/invoice_detail.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)