def post_message(request,to):
    from_user = request.user
    to_user = get_object_or_404(User,username=to)
    if from_user==to_user:
#        messages.error(request,'can not write email to yourself')
        messages.error(request,_(u'Вы не можете написать сообщение самому себе'))
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
        #get existed chat
    chat= Chat.objects.filter(from_user=from_user,to_user=to_user) or Chat.objects.filter(to_user=from_user,from_user=to_user)
    if chat:
        chat=chat[0]

    #if chat first time then create it
    if not chat:
        chat=Chat.objects.create(from_user=from_user,to_user=to_user)

    if chat.from_user==from_user:
        chat.is_to_user_read=True
    else:
        chat.is_from_user_read=True

    file = request.FILES['file'] if 'file' in request.FILES else None
    chat.add_message(from_user,request.POST['message'],file=file)

    UserLog.objects.create(user=to_user,
        text_en='Got <a href="/show_chat/%s/">message</a> %s from user %s'%(request.user,request.POST['message'],request.user),
        text_ru=u'Получено <a href="/show_chat/%s/">сообщениe</a> %s от пользователя %s'%(request.user,request.POST['message'],request.user))
    sendEmail(user=to_user,type='message',extra={'from':request.user,'message':request.POST['message']})
    SystemLog.objects.create(user=to_user, text='Message %s from user %s to user %s'%(request.POST['message'],request.user,to_user))

    return HttpResponseRedirect(reverse('send_message',args=[to,]))
def take_money(request):
    liq=Liqpay(settings.MERCHANT_ID,settings.SEND_MONEY_SIGNATURE)
    amount=float(request.POST['amount'])
    if amount>request.user.get_profile().account or amount==0:
        messages.error(request,_(u'Не достаточно денег на вашем счету'))
        return HttpResponseRedirect(request.META['HTTP_REFERER'])

    to=request.POST['to']
    comission=amount/100*float(settings.COMISSION_RATE)
    try:
        liq.send_money(to=to,amount=amount-comission,currency='USD')
        liq.send_money(to=settings.COMISSION_PHONE,amount=comission,currency='USD')

        UserLog.objects.create(user=request.user, type='payment',
            text_ru=u'Выведено %s$ на liqpay счет %s ' % (amount,to),
            text_en='Sent %s$ to liqpay account %s ' % (amount,to),
        )
        SystemLog.objects.create(user=request.user, type='payment',
            text='Sent %s$ to liqpay account %s ' % (amount,to))

        Balance.objects.outFromBalance(amount)
        Balance.objects.commission(comission)

        profile = request.user.get_profile()
        profile.account-=amount
        profile.save()

        sendEmail(user=request.user, type='TakeMoney',extra={'to':to,'amount':amount})
    except Exception, err:
        messages.error(request,err)
def post_comment(request, id):
    product = get_object_or_404(Product, id=id)

    result = product.add_comment(request)
    if result == 'Comment added':
        UserLog.objects.create(
            user=product.user,
            text_en='Posted comment %s about product %s' %
            (request.POST['comment'], product.name),
            text_ru=
            u'Получен комментарий %s о товаре <a href="/product/%s/"> %s</a>' %
            (request.POST['comment'], product.id, product.name))
        SystemLog.objects.create(
            user=request.user,
            text='Post comment %s about product %s, id=%s' %
            (request.POST['comment'], product.name, product.id))
        sendEmail(user=product.user,
                  type='productFeedback',
                  extra={
                      'message': request.POST['comment'],
                      'product': product,
                      'who': request.user
                  })
    messages.info(request, result)
    return HttpResponseRedirect(request.META['HTTP_REFERER'] + '#allComments')
def cancelOrder(request,id):
    order=get_object_or_404(Order,id=id)
    profileSeller=order.seller.get_profile()
    profileBuyer=order.buyer.get_profile()

    if profileSeller.account>=order.payed:
            profileSeller.account-=order.payed
            profileSeller.save()
            profileBuyer.account+=order.payed
            payed= order.payed
            profileBuyer.save()
            order.cancelReason=request.POST['note']
            order.is_canceled=True
            order.status='Closed'
            order.refunded=order.payed
            order.payed=0
            order.save()
            sendEmail(user=order.buyer,type='cancelOrder',extra={'order':order})
            UserLog.objects.create(user=order.seller,
                text_ru=u'Вы отменили заказ #%s по причине %s'%(order.id,order.cancelReason),
                text_en='You canceled order #%s for reason %s'%(order.id,order.cancelReason))
            UserLog.objects.create(user=order.buyer,
                text_ru=u'Продавец %s отменил заказ #%s по причине %s'%(order.seller,order.id,order.cancelReason),
                text_en='Seller %s canceled order #%s for reason %s'%(order.seller,order.id,order.cancelReason))
            if payed:
                messages.success(request,_(u'Деньги с вашого счета перечислены обратно на счет покупателя ')+order.buyer.username)
            else:
                messages.success(request,_(u'Заказ отменен'))
    else:
            messages.error(request,_(u'Не достаточно денег'))

    return HttpResponseRedirect(request.META['HTTP_REFERER']+'?tab=third')
def send_money(request):
    try:
        amount = float(request.POST['amount'])

        if amount>request.user.get_profile().account:
            messages.error(request,'Not enough money')
            return HttpResponseRedirect(reverse('payments'))

        user = User.objects.get(username=request.POST['username'])
        if user==request.user:
            messages.error(request,'Can not send money to yourself')
            return HttpResponseRedirect(reverse('payments'))
        user.get_profile().account += amount
        user.get_profile().save()
        request.user.get_profile().account -= amount
        request.user.get_profile().save()
        messages.success(request,'Payment successful')
        UserLog.objects.create(user=request.user, type='payment',
            text_en='Sent %s$ to user %s' % (amount,user.username),
            text_ru=u'Выслано %s$ пользователю %s' % (amount,user.username))
        UserLog.objects.create(user=user, type='payment',
            text_en='Get money %s$ from %s' % (amount,request.user.username),
            text_ru=u'Получено %s$ от %s' % (amount,request.user.username)
        )

        sendEmail(user=request.user, type='sendMoneyTo',extra={'to':user,'amount':amount})
        sendEmail(user=user, type='sendMoneyGet',extra={'from':request.user,'amount':amount})


        SystemLog.objects.create(user=request.user, type='payment', text='Send %s to user %s' % (amount,user.username))
    except :
        messages.error(request,'Error')

    return HttpResponseRedirect(reverse('payments'))
def post_comment(request,id):
    product = get_object_or_404(Product,id=id)

    result= product.add_comment(request)
    if result=='Comment added':
        UserLog.objects.create(user=product.user, text_en='Posted comment %s about product %s' % (request.POST['comment'],product.name),
            text_ru=u'Получен комментарий %s о товаре <a href="/product/%s/"> %s</a>' % (request.POST['comment'],product.id,product.name))
        SystemLog.objects.create(user=request.user, text='Post comment %s about product %s, id=%s' %
                                                       (request.POST['comment'],product.name,product.id))
        sendEmail(user=product.user,type='productFeedback',
            extra={'message':request.POST['comment'],'product':product,'who':request.user})
    messages.info(request,result)
    return HttpResponseRedirect(request.META['HTTP_REFERER']+'#allComments')
Beispiel #7
0
def get_liqpay(request):
    user = User.objects.get(id=1)
    SystemLog.objects.create(user=user, type='payment', text='GET LIQPAY')

    liq = Liqpay(settings.MERCHANT_ID, settings.SIGNATURE)
    response = liq.parse_merchant_response_xml(
        opxml=request.POST['operation_xml'],
        signature=request.POST['signature'])
    username = request.GET['username']
    user = User.objects.get(username=username)

    if (response.status == 'success'):
        Payment.objects.create(status=response.status,
                               pay_way='liqpay',
                               sender_phone=response.sender_phone,
                               code=response.code,
                               amount=response.amount,
                               currency=response.currency,
                               description=response.description,
                               pay_details=response.pay_details,
                               type='in',
                               invoice_id=response.order_id,
                               user=user)
        user.get_profile().account += float(response.amount)
        user.get_profile().save()

        UserLog.objects.create(
            user=user,
            type='payment',
            text_en='You add %s$ to own account by liqpay' %
            float(response.amount),
            text_ru=u'Вы поставили %s$ на свой счет с помощью liqpay' %
            float(response.amount))
        sendEmail(user=user, type='getLiqpay', extra={'amount': amount})
        SystemLog.objects.create(user=user,
                                 type='payment',
                                 text='User %s add %s$  to account by liqpay' %
                                 (user.username, response.amount))
        Balance.objects.addToBalance(response.amount)
    else:
        UserLog.objects.create(
            user=user,
            type='payment',
            text_en='Failed to add %s$ to own account by liqpay' %
            response.amount,
            text_ru=
            u'Liqpay транзакция на суму %s$ не прошла обратитесь в службу поддержки ликпей на liqay.com'
            % response.amount)

    return HttpResponse('complete')
Beispiel #8
0
def send_money(request):
    try:
        amount = float(request.POST['amount'])

        if amount > request.user.get_profile().account:
            messages.error(request, 'Not enough money')
            return HttpResponseRedirect(reverse('payments'))

        user = User.objects.get(username=request.POST['username'])
        if user == request.user:
            messages.error(request, 'Can not send money to yourself')
            return HttpResponseRedirect(reverse('payments'))
        user.get_profile().account += amount
        user.get_profile().save()
        request.user.get_profile().account -= amount
        request.user.get_profile().save()
        messages.success(request, 'Payment successful')
        UserLog.objects.create(
            user=request.user,
            type='payment',
            text_en='Sent %s$ to user %s' % (amount, user.username),
            text_ru=u'Выслано %s$ пользователю %s' % (amount, user.username))
        UserLog.objects.create(
            user=user,
            type='payment',
            text_en='Get money %s$ from %s' % (amount, request.user.username),
            text_ru=u'Получено %s$ от %s' % (amount, request.user.username))

        sendEmail(user=request.user,
                  type='sendMoneyTo',
                  extra={
                      'to': user,
                      'amount': amount
                  })
        sendEmail(user=user,
                  type='sendMoneyGet',
                  extra={
                      'from': request.user,
                      'amount': amount
                  })

        SystemLog.objects.create(user=request.user,
                                 type='payment',
                                 text='Send %s to user %s' %
                                 (amount, user.username))
    except:
        messages.error(request, 'Error')

    return HttpResponseRedirect(reverse('payments'))
def post_message(request, to):
    from_user = request.user
    to_user = get_object_or_404(User, username=to)
    if from_user == to_user:
        #        messages.error(request,'can not write email to yourself')
        messages.error(request,
                       _(u'Вы не можете написать сообщение самому себе'))
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
        #get existed chat
    chat = Chat.objects.filter(from_user=from_user,
                               to_user=to_user) or Chat.objects.filter(
                                   to_user=from_user, from_user=to_user)
    if chat:
        chat = chat[0]

    #if chat first time then create it
    if not chat:
        chat = Chat.objects.create(from_user=from_user, to_user=to_user)

    if chat.from_user == from_user:
        chat.is_to_user_read = True
    else:
        chat.is_from_user_read = True

    file = request.FILES['file'] if 'file' in request.FILES else None
    chat.add_message(from_user, request.POST['message'], file=file)

    UserLog.objects.create(
        user=to_user,
        text_en='Got <a href="/show_chat/%s/">message</a> %s from user %s' %
        (request.user, request.POST['message'], request.user),
        text_ru=
        u'Получено <a href="/show_chat/%s/">сообщениe</a> %s от пользователя %s'
        % (request.user, request.POST['message'], request.user))
    sendEmail(user=to_user,
              type='message',
              extra={
                  'from': request.user,
                  'message': request.POST['message']
              })
    SystemLog.objects.create(user=to_user,
                             text='Message %s from user %s to user %s' %
                             (request.POST['message'], request.user, to_user))

    return HttpResponseRedirect(reverse('send_message', args=[
        to,
    ]))
Beispiel #10
0
def pay(request,id):
    order=get_object_or_404(request.user.get_profile().orders,id=id)
    profile =request.user.get_profile()
    if order.is_payed:
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    if profile.account >= order.price():
        for cart in order.carts.all():
            if cart.quantity>cart.product.quantity:
                messages.error(request, _(u'Максимально доступное количество товара ')+cart.product.name+' '+str(cart.product.quantity))
                return HttpResponseRedirect(reverse('orders'))
            else:
                cart.product.quantity -=cart.quantity
                cart.product.bought += cart.quantity
                cart.product.deals +=1
                cart.product.save()

        profile.account -= order.price()
        order.payed = order.price()
        profile.save()

        seller_profile=order.seller.get_profile()
        seller_profile.account+=order.price()
        seller_profile.save()

        order.is_payed = True
        order.payed_date=datetime.now()
        order.status = 'Payed'
        order.save()

        UserLog.objects.create(user=order.seller,
            text_en='User %s pay <a href="shop/orders/">for order #%s</a>'%(order.buyer,order.id),
            text_ru=u'Пользователь %s оплатил <a href="shop/orders/">заказ #%s</a>'%(order.buyer,order.id))
        UserLog.objects.create(user=order.buyer,
            text_en='Payed for  <a href="/orders/">order #%s</a>'%order.id,
            text_ru=u'Оплачен <a href="/orders/">заказ #%s</a>'%order.id)
        SystemLog.objects.create(user=request.user,text='Pay for order %s'%order.id)
        sendEmail(user=order.seller,type="payedSeller",extra={'buyer':order.buyer,'order':order})
        sendEmail(user=order.buyer,type="payedBuyer",extra={'seller':order.seller,'order':order})
        messages.success(request,_(u'Заказ оплачен'))
        return HttpResponseRedirect(reverse('orders')+'?tab=second')
    else:
        SystemLog.objects.create(user=request.user,text='Pay for order %s, but not anough money'%order.id)
        messages.error(request,_(u'У вас на счету недостаточно средств'))

    return HttpResponseRedirect(reverse('orders')+'?tab=second')
Beispiel #11
0
def take_money(request):
    liq = Liqpay(settings.MERCHANT_ID, settings.SEND_MONEY_SIGNATURE)
    amount = float(request.POST['amount'])
    if amount > request.user.get_profile().account or amount == 0:
        messages.error(request, _(u'Не достаточно денег на вашем счету'))
        return HttpResponseRedirect(request.META['HTTP_REFERER'])

    to = request.POST['to']
    comission = amount / 100 * float(settings.COMISSION_RATE)
    try:
        liq.send_money(to=to, amount=amount - comission, currency='USD')
        liq.send_money(to=settings.COMISSION_PHONE,
                       amount=comission,
                       currency='USD')

        UserLog.objects.create(
            user=request.user,
            type='payment',
            text_ru=u'Выведено %s$ на liqpay счет %s ' % (amount, to),
            text_en='Sent %s$ to liqpay account %s ' % (amount, to),
        )
        SystemLog.objects.create(user=request.user,
                                 type='payment',
                                 text='Sent %s$ to liqpay account %s ' %
                                 (amount, to))

        Balance.objects.outFromBalance(amount)
        Balance.objects.commission(comission)

        profile = request.user.get_profile()
        profile.account -= amount
        profile.save()

        sendEmail(user=request.user,
                  type='TakeMoney',
                  extra={
                      'to': to,
                      'amount': amount
                  })
    except Exception, err:
        messages.error(request, err)
def cancelOrder(request, id):
    order = get_object_or_404(Order, id=id)
    profileSeller = order.seller.get_profile()
    profileBuyer = order.buyer.get_profile()

    if profileSeller.account >= order.payed:
        profileSeller.account -= order.payed
        profileSeller.save()
        profileBuyer.account += order.payed
        payed = order.payed
        profileBuyer.save()
        order.cancelReason = request.POST['note']
        order.is_canceled = True
        order.status = 'Closed'
        order.refunded = order.payed
        order.payed = 0
        order.save()
        sendEmail(user=order.buyer, type='cancelOrder', extra={'order': order})
        UserLog.objects.create(user=order.seller,
                               text_ru=u'Вы отменили заказ #%s по причине %s' %
                               (order.id, order.cancelReason),
                               text_en='You canceled order #%s for reason %s' %
                               (order.id, order.cancelReason))
        UserLog.objects.create(
            user=order.buyer,
            text_ru=u'Продавец %s отменил заказ #%s по причине %s' %
            (order.seller, order.id, order.cancelReason),
            text_en='Seller %s canceled order #%s for reason %s' %
            (order.seller, order.id, order.cancelReason))
        if payed:
            messages.success(
                request,
                _(u'Деньги с вашого счета перечислены обратно на счет покупателя '
                  ) + order.buyer.username)
        else:
            messages.success(request, _(u'Заказ отменен'))
    else:
        messages.error(request, _(u'Не достаточно денег'))

    return HttpResponseRedirect(request.META['HTTP_REFERER'] + '?tab=third')
Beispiel #13
0
def get_liqpay(request):
    user=User.objects.get(id=1)
    SystemLog.objects.create(user=user, type='payment', text='GET LIQPAY')

    liq=Liqpay(settings.MERCHANT_ID,settings.SIGNATURE)
    response=liq.parse_merchant_response_xml(opxml=request.POST['operation_xml'],signature=request.POST['signature'])
    username = request.GET['username']
    user = User.objects.get(username=username)

    if (response.status=='success'):
        Payment.objects.create(status = response.status,pay_way = 'liqpay',
            sender_phone = response.sender_phone,
            code = response.code,
            amount = response.amount,
            currency = response.currency,
            description = response.description,
            pay_details = response.pay_details,
            type='in',
            invoice_id = response.order_id,
            user=user
        )
        user.get_profile().account+=float(response.amount)
        user.get_profile().save()

        UserLog.objects.create(user=user, type='payment',
            text_en='You add %s$ to own account by liqpay' % float(response.amount),
            text_ru=u'Вы поставили %s$ на свой счет с помощью liqpay' % float(response.amount)
        )
        sendEmail(user=user,type='getLiqpay',extra={'amount':amount})
        SystemLog.objects.create(user=user, type='payment', text='User %s add %s$  to account by liqpay'% (user.username,response.amount))
        Balance.objects.addToBalance(response.amount)
    else:
        UserLog.objects.create(user=user, type='payment',
            text_en='Failed to add %s$ to own account by liqpay' % response.amount,
            text_ru=u'Liqpay транзакция на суму %s$ не прошла обратитесь в службу поддержки ликпей на liqay.com' % response.amount
        )

    return HttpResponse('complete')
Beispiel #14
0
def cart(request):
    carts=CartItem.objects.filter(cart_id=request.session['cart_id'])
    full_price = carts.full_price()
    carts=carts.order_by_shop()

    if request.user.is_authenticated():
        lForm,rForm='',''
    else:
        lForm,rForm=LoginForm(),RegistrationFormUniqueEmail()

    addressForm = AddressForm()

    if request.method == 'POST':
        address= request.POST['address'] if 'address' in request.POST else 'new'
        addressForm = AddressForm(request.POST)
        lForm = LoginForm(request.POST)
        if not addressForm.is_valid()  and address=='new':
            if not request.user.is_authenticated():
                return render_to_response('public/cart.html',{'carts':carts,'full_price':full_price, 'rForm':rForm,'lForm':lForm,'addressForm':addressForm},context_instance=RequestContext(request))
            else:
                return render_to_response('cart/cart.html',{'carts':carts,'full_price':full_price, 'rForm':rForm,'lForm':lForm,'addressForm':addressForm},context_instance=RequestContext(request))
#            messages.info(request,'Enter address')
#            return HttpResponseRedirect(reverse('cart'))

        if lForm.is_valid():
            user = authenticate(username=lForm.cleaned_data['login'], password=lForm.cleaned_data['password'])
            #if user try to login by email in username
            if user is None:
                username=User.objects.filter(email=lForm.cleaned_data['login'])
                if username:
                    username=username[0].username
                    user = authenticate(username=username, password=lForm.cleaned_data['password'])
                else:
                    from django.forms.forms import NON_FIELD_ERRORS
                    lForm._errors[NON_FIELD_ERRORS] = lForm.error_class(["Your username or password was incorrect."])

            if user is not None and user.is_active:
                for shop in carts:
                    for cart in shop.carts.all():
                        if cart.product.user==user:
                            messages.error(request,_(u'Вы не можете купить товар у самого себя'))
                            return render_to_response('public/cart.html',{'carts':carts,'full_price':full_price, 'rForm':rForm,'lForm':lForm,'addressForm':addressForm},context_instance=RequestContext(request))
                login(request,user)

        rForm= RegistrationFormUniqueEmail(request.POST)
        if rForm.is_valid():
            rForm.save()
            user = authenticate(username=rForm.cleaned_data['username'], password=rForm.cleaned_data['password1'])
            login(request,user)

        if  rForm.is_valid() or lForm.is_valid() or request.user.is_authenticated():
            if address=='new':
                address = addressForm.save()
                request.user.get_profile().addresses.add(address)
            else:
                address=address.replace('address_','')
                address=request.user.get_profile().addresses.get(id=address)

            shops=CartItem.objects.filter(cart_id=request.session['cart_id']).order_by_shop()

            for shop in shops:
                order=Order.objects.create(seller=shop.user,buyer = request.user,
                    status = 'Not payed', country = address.country,
                    region = address.region, phone = address.phone,
                    city = address.city,street = address.street, zip_code = address.zip_code)
                for cart in shop.carts:
                    cart.cart_id=''
                    cart.save()
                    order.carts.add(cart)
                request.user.get_profile().orders.add(order)

                UserLog.objects.create(user=order.seller,
                    text_en=(u'Got <a href="/shop/orders/">  order #%s</a> from user %s'% (order.id,order.buyer)),
                    text_ru=(u'Поступил <a href="/shop/orders/"> заказ #%s</a> от пользователя %s'% (order.id,order.buyer)))
                UserLog.objects.create(user=order.buyer,
                    text_en=(u'Created <a href="/orders/">order #%s</a>' % order.id),
                    text_ru=(u'Создан <a href="/orders/">заказ #%s</a>' % order.id))
                SystemLog.objects.create(user=request.user,text='Create order %s' % order.id)
                sendEmail(user=order.seller,type='createOrder',extra={'order':order})
            messages.success(request,u'Спасибо за заказ! Продавец свяжется с вами в кратчайшие сроки.')
            return HttpResponseRedirect(reverse('orders'))

    if not request.user.is_authenticated():
        return render_to_response('public/cart.html',{'carts':carts,'full_price':full_price, 'rForm':rForm,'lForm':lForm,'addressForm':addressForm},context_instance=RequestContext(request))

    return render_to_response('cart/cart.html',{'carts':carts,'full_price':full_price, 'rForm':rForm,'lForm':lForm,'addressForm':addressForm},context_instance=RequestContext(request))
def pay(request, id):
    order = get_object_or_404(request.user.get_profile().orders, id=id)
    profile = request.user.get_profile()
    if order.is_payed:
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    if profile.account >= order.price():
        for cart in order.carts.all():
            if cart.quantity > cart.product.quantity:
                messages.error(
                    request,
                    _(u'Максимально доступное количество товара ') +
                    cart.product.name + ' ' + str(cart.product.quantity))
                return HttpResponseRedirect(reverse('orders'))
            else:
                cart.product.quantity -= cart.quantity
                cart.product.bought += cart.quantity
                cart.product.deals += 1
                cart.product.save()

        profile.account -= order.price()
        order.payed = order.price()
        profile.save()

        seller_profile = order.seller.get_profile()
        seller_profile.account += order.price()
        seller_profile.save()

        order.is_payed = True
        order.payed_date = datetime.now()
        order.status = 'Payed'
        order.save()

        UserLog.objects.create(
            user=order.seller,
            text_en='User %s pay <a href="shop/orders/">for order #%s</a>' %
            (order.buyer, order.id),
            text_ru=
            u'Пользователь %s оплатил <a href="shop/orders/">заказ #%s</a>' %
            (order.buyer, order.id))
        UserLog.objects.create(
            user=order.buyer,
            text_en='Payed for  <a href="/orders/">order #%s</a>' % order.id,
            text_ru=u'Оплачен <a href="/orders/">заказ #%s</a>' % order.id)
        SystemLog.objects.create(user=request.user,
                                 text='Pay for order %s' % order.id)
        sendEmail(user=order.seller,
                  type="payedSeller",
                  extra={
                      'buyer': order.buyer,
                      'order': order
                  })
        sendEmail(user=order.buyer,
                  type="payedBuyer",
                  extra={
                      'seller': order.seller,
                      'order': order
                  })
        messages.success(request, _(u'Заказ оплачен'))
        return HttpResponseRedirect(reverse('orders') + '?tab=second')
    else:
        SystemLog.objects.create(
            user=request.user,
            text='Pay for order %s, but not anough money' % order.id)
        messages.error(request, _(u'У вас на счету недостаточно средств'))

    return HttpResponseRedirect(reverse('orders') + '?tab=second')
def cart(request):
    carts = CartItem.objects.filter(cart_id=request.session['cart_id'])
    full_price = carts.full_price()
    carts = carts.order_by_shop()

    if request.user.is_authenticated():
        lForm, rForm = '', ''
    else:
        lForm, rForm = LoginForm(), RegistrationFormUniqueEmail()

    addressForm = AddressForm()

    if request.method == 'POST':
        address = request.POST[
            'address'] if 'address' in request.POST else 'new'
        addressForm = AddressForm(request.POST)
        lForm = LoginForm(request.POST)
        if not addressForm.is_valid() and address == 'new':
            if not request.user.is_authenticated():
                return render_to_response(
                    'public/cart.html', {
                        'carts': carts,
                        'full_price': full_price,
                        'rForm': rForm,
                        'lForm': lForm,
                        'addressForm': addressForm
                    },
                    context_instance=RequestContext(request))
            else:
                return render_to_response(
                    'cart/cart.html', {
                        'carts': carts,
                        'full_price': full_price,
                        'rForm': rForm,
                        'lForm': lForm,
                        'addressForm': addressForm
                    },
                    context_instance=RequestContext(request))


#            messages.info(request,'Enter address')
#            return HttpResponseRedirect(reverse('cart'))

        if lForm.is_valid():
            user = authenticate(username=lForm.cleaned_data['login'],
                                password=lForm.cleaned_data['password'])
            #if user try to login by email in username
            if user is None:
                username = User.objects.filter(
                    email=lForm.cleaned_data['login'])
                if username:
                    username = username[0].username
                    user = authenticate(
                        username=username,
                        password=lForm.cleaned_data['password'])
                else:
                    from django.forms.forms import NON_FIELD_ERRORS
                    lForm._errors[NON_FIELD_ERRORS] = lForm.error_class(
                        ["Your username or password was incorrect."])

            if user is not None and user.is_active:
                for shop in carts:
                    for cart in shop.carts.all():
                        if cart.product.user == user:
                            messages.error(
                                request,
                                _(u'Вы не можете купить товар у самого себя'))
                            return render_to_response(
                                'public/cart.html', {
                                    'carts': carts,
                                    'full_price': full_price,
                                    'rForm': rForm,
                                    'lForm': lForm,
                                    'addressForm': addressForm
                                },
                                context_instance=RequestContext(request))
                login(request, user)

        rForm = RegistrationFormUniqueEmail(request.POST)
        if rForm.is_valid():
            rForm.save()
            user = authenticate(username=rForm.cleaned_data['username'],
                                password=rForm.cleaned_data['password1'])
            login(request, user)

        if rForm.is_valid() or lForm.is_valid(
        ) or request.user.is_authenticated():
            if address == 'new':
                address = addressForm.save()
                request.user.get_profile().addresses.add(address)
            else:
                address = address.replace('address_', '')
                address = request.user.get_profile().addresses.get(id=address)

            shops = CartItem.objects.filter(
                cart_id=request.session['cart_id']).order_by_shop()

            for shop in shops:
                order = Order.objects.create(seller=shop.user,
                                             buyer=request.user,
                                             status='Not payed',
                                             country=address.country,
                                             region=address.region,
                                             phone=address.phone,
                                             city=address.city,
                                             street=address.street,
                                             zip_code=address.zip_code)
                for cart in shop.carts:
                    cart.cart_id = ''
                    cart.save()
                    order.carts.add(cart)
                request.user.get_profile().orders.add(order)

                UserLog.objects.create(
                    user=order.seller,
                    text_en=
                    (u'Got <a href="/shop/orders/">  order #%s</a> from user %s'
                     % (order.id, order.buyer)),
                    text_ru=
                    (u'Поступил <a href="/shop/orders/"> заказ #%s</a> от пользователя %s'
                     % (order.id, order.buyer)))
                UserLog.objects.create(
                    user=order.buyer,
                    text_en=(u'Created <a href="/orders/">order #%s</a>' %
                             order.id),
                    text_ru=(u'Создан <a href="/orders/">заказ #%s</a>' %
                             order.id))
                SystemLog.objects.create(user=request.user,
                                         text='Create order %s' % order.id)
                sendEmail(user=order.seller,
                          type='createOrder',
                          extra={'order': order})
            messages.success(
                request,
                u'Спасибо за заказ! Продавец свяжется с вами в кратчайшие сроки.'
            )
            return HttpResponseRedirect(reverse('orders'))

    if not request.user.is_authenticated():
        return render_to_response('public/cart.html', {
            'carts': carts,
            'full_price': full_price,
            'rForm': rForm,
            'lForm': lForm,
            'addressForm': addressForm
        },
                                  context_instance=RequestContext(request))

    return render_to_response('cart/cart.html', {
        'carts': carts,
        'full_price': full_price,
        'rForm': rForm,
        'lForm': lForm,
        'addressForm': addressForm
    },
                              context_instance=RequestContext(request))