Ejemplo n.º 1
0
    def post(self, request, *args, **kwargs):
        profile = request.user.get_profile()
        self.object = self.get_object()
        has_errors = not (profile.billing_address and profile.shipping_address) and not self.object
        if has_errors:
            return self.render_to_response(self.get_context_data())
        try:
            with transaction.atomic():
                profile = UserProfile.objects.get(user=request.user)
                if profile.balance < self.object.price:
                    raise NotEnoughCoins

                self.object.is_sold = True
                self.object.save()

                profile.balance -= self.object.price
                profile.save()

                billing_address = profile.billing_address
                billing_address.pk = None
                billing_address.save()

                shipping_address = profile.shipping_address
                shipping_address.pk = None
                shipping_address.save()

                order = Order()
                order.item = self.object
                order.amount = self.object.price
                order.customer = request.user
                order.billing_address = billing_address
                order.shipping_address = shipping_address
                order.save()
        except IntegrityError:
            messages.error(request, 'Could not process request')
            return self.render_to_response(self.get_context_data())
        except NotEnoughCoins:
            messages.error(request, 'You have not enough coins.')
            return self.render_to_response(self.get_context_data())

        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        signals.item_was_sold.send(sender=self.__class__,
                                   order=order,
                                   site=site,
                                   request=request)
        return HttpResponseRedirect(self.get_success_url())
Ejemplo n.º 2
0
def checkout(request):
    # get Request
    if request.method == 'GET':
        form = CheckForm()
        cart = request.session.get('cart')
        if cart is None:
            cart = []

        for c in cart:
            size_str = c.get('size')
            tshirt_id = c.get('tshirt')
            size_obj = SizeVariant.objects.get(size=size_str, tshirt=tshirt_id)
            c['size'] = size_obj
            c['tshirt'] = size_obj.tshirt

        print(cart)

        return render(request, 'store/checkout.html', {
            "form": form,
            'cart': cart
        })
    else:
        # post request
        form = CheckForm(request.POST)
        user = None
        if request.user.is_authenticated:
            user = request.user
        if form.is_valid():
            # payment
            cart = request.session.get('cart')
            if cart is None:
                cart = []
            for c in cart:
                size_str = c.get('size')
                tshirt_id = c.get('tshirt')
                size_obj = SizeVariant.objects.get(size=size_str,
                                                   tshirt=tshirt_id)
                c['size'] = size_obj
                c['tshirt'] = size_obj.tshirt
            shipping_address = form.cleaned_data.get('shipping_address')
            phone = form.cleaned_data.get('phone')
            payment_method = form.cleaned_data.get('payment_method')
            total = cal_total_payable_amount(cart)
            print(shipping_address, phone, payment_method, total)

            order = Order()
            order.shipping_address = shipping_address
            order.phone = phone
            order.payment_method = payment_method
            order.total = total
            order.order_status = "PENDING"
            order.user = user
            order.save()

            # saving order items
            for c in cart:
                order_item = OrderItem()
                order_item.order = order
                size = c.get('size')
                tshirt = c.get('tshirt')
                order_item.price = floor(size.price -
                                         (size.price *
                                          (tshirt.discount / 100)))
                order_item.quantity = c.get('quantity')
                order_item.size = size
                order_item.tshirt = tshirt
                order_item.save()

            buyer_name = f'{user.first_name} {user.last_name}'
            print(buyer_name)
            # crating payment
            response = API.payment_request_create(
                amount=order.total,
                purpose="Payment For Tshirts",
                send_email=False,
                buyer_name=f'{user.first_name} {user.last_name}',
                email=user.email,
                redirect_url="http://localhost:8000/validate_payment")

            payment_request_id = response['payment_request']['id']
            url = response['payment_request']['longurl']

            payment = Payment()
            payment.order = order
            payment.payment_request_id = payment_request_id
            payment.save()
            return redirect(url)
        else:
            return redirect('/checkout/')
def checkout(request):
    if request.method == 'GET':     #for get Request
        form = CheckForm()
        cart=request.session.get('cart')
        if cart is None:
            cart=[]
        
        for c in cart:
            size_str = c.get('size')
            tshirt_id = c.get('tshirt')
            size_obj=SizeVariant.objects.get(size=size_str , tshirt=tshirt_id)   #now in cart list ,size is replaced by its object
            c['size']=size_obj
            c['tshirt']=size_obj.tshirt   #replacing in cart list , tshirt is id ,inplace of id tshirt object is stored

        return render(request,'store/checkout.html',{"form" : form, 'cart':cart})
    else:
        #this is for POST request
        form = CheckForm(request.POST)
        user = None
        if request.user.is_authenticated :
            user = request.user
        if form.is_valid():
            #payment should be done here
            cart=request.session.get('cart')
            if cart is None:
                cart = []
            for c in cart:
                size_str = c.get('size')
                tshirt_id = c.get('tshirt')
                size_obj=SizeVariant.objects.get(size=size_str , tshirt=tshirt_id)   #now in cart list ,size is replaced by its object
                c['size']=size_obj
                c['tshirt']=size_obj.tshirt
            shipping_address=form.cleaned_data.get('shipping_address')   #the shipping address entered will be stored in shipping_address variable
            phone=form.cleaned_data.get('phone')
            payment_method = form.cleaned_data.get('payment_method')
            total = cal_total_payable_amount(cart)
            print(shipping_address,phone,payment_method , total)
            order= Order()               #created Order Model object
            order.shipping_address = shipping_address   #entering data in ORDER table
            order.phone = phone
            order.payment_method= payment_method
            order.total = total
            order.order_status = "PENDING"
            order.user = user
            order.save()    
            #print(order.id)        # we will get order id 

            #saving to OrderItems Table
            for c in cart :
                order_item = OrderItem()   #creating new object for OrderItem Table
                order_item.order = order      #order id will be stored in order
                size=c.get('size')   #to access dictionary we use get('key')
                tshirt=c.get('tshirt')
                order_item.price = floor(size.price- (size.price*(tshirt.discount/100)))
                order_item.quantity = c.get('quantity')
                order_item.size = size
                order_item.tshirt = tshirt
                order_item.save()

            
            # CREATING PAYMENT
            # Create a new Payment Request
            response = API.payment_request_create(
                amount=order.total,
                purpose='Payment For Tshirts',
                buyer_name=f'{user.first_name} {user.last_name}',
                send_email=True,
                email=user.email,
                redirect_url="http://localhost:8000/validate_payment"
                )
            #print(response['payment_request'])
            payment_request_id = response['payment_request']['id']
            #the long URL of the payment request
            url =response['payment_request']['longurl']
            print(url)
            
            payment= Payment()
            payment.order= order
            payment.payment_request_id= payment_request_id
            payment.save()
            return redirect(url)
        else:
            return redirect('/checkout/')
Ejemplo n.º 4
0
    def post(self, request):
        user = None
        form = CheckoutForm(request.POST)
        if request.user.is_authenticated:
            user = request.user

        if form.is_valid():
            buy = request.session.get('buy')
            cart = request.session.get('cart')

            #creating order
            shipping_address = form.cleaned_data.get('shipping_address')
            phone = form.cleaned_data.get('phone')
            payment_method = form.cleaned_data.get('payment_method')
            order = Order()
            order.shipping_address = shipping_address
            order.phone = phone
            order.payment_method = payment_method

            #logic for buing item directly through pay button
            if buy:
                price = 0
                for b in buy:
                    size_str = b.get('size')
                    cloth_id = b.get('cloth')
                    cloth_obj = Size_Variant.objects.get(size=size_str,
                                                         cloth=cloth_id)
                    cloth = Cloth.objects.get(id=cloth_id)
                    b['size'] = cloth_obj
                    b['cloth'] = cloth_obj.cloth
                    price = cloth_obj.price
                    price = floor(price - (price *
                                           (cloth.cloth_discount / 100)))
                    b['total'] = price

                order.total = price

                order.order_status = "PENDING"
                order.user = user
                order.save()
                # preventing duplicated value in buy
                preventing_duplicate(buy)

                #creating order item
                for b in buy:
                    order_item = Order_Item()
                    order_item.order = order
                    size = b.get('size')
                    cloth = b.get('cloth')
                    order_item.price = floor(size.price -
                                             (size.price *
                                              (cloth.cloth_discount / 100)))
                    order_item.quantity = 1
                    order_item.size = size
                    order_item.cloth = cloth
                    order_item.save()

        #logic for buying item through cart
            else:
                if cart is None:
                    cart = []
                for c in cart:
                    size_str = c.get('size')
                    cloth_id = c.get('cloth')
                    cloth_obj = Size_Variant.objects.get(size=size_str,
                                                         cloth=cloth_id)
                    c['size'] = cloth_obj
                    c['cloth'] = cloth_obj.cloth
                total = total_payable_amount(cart)
                order.total = total
                order.order_status = "PENDING"
                order.user = user
                order.save()

                # saving order items
                for c in cart:
                    order_item = Order_Item()
                    order_item.order = order
                    size = c.get('size')
                    cloth = c.get('cloth')
                    order_item.price = floor(size.price -
                                             (size.price *
                                              (cloth.cloth_discount / 100)))
                    order_item.quantity = c.get('quantity')
                    order_item.size = size
                    order_item.cloth = cloth
                    order_item.save()

            if payment_method == "ONLINE":
                # creating payment
                try:
                    client = razorpay.Client(auth=(KEY_ID, KEY_SECRET))
                    payment_id = client.order.create({
                        "amount": order.total * 100,
                        'currency': 'INR',
                        'payment_capture': '1',
                    })
                except:
                    messages.error(
                        request,
                        'Payment gateway is not Responding , Check your connection !'
                    )
                    return redirect('Checkout')

                payment = Payment()
                payment.order = order
                payment.payment_request_id = payment_id['id']
                payment.save()
                form = CheckoutForm()
                context = {
                    'form': form,
                    'cart': cart,
                    'buy': buy,
                    'payment': payment_id
                }
                return render(request, 'store/checkout.html', context=context)
            else:
                order.order_status = "PLACED"
                order.save()
                try:
                    context = {
                        "username": user.first_name,
                        "order": order,
                    }

                    html_message = loader.render_to_string(
                        "store/product_email.html", context=context)

                    # mail to coustomer
                    send_mail(
                        'Product Purchased',
                        'Payment for ordered product has successfull worth of money !',
                        EMAIL_HOST_USER,
                        [user.email],
                        fail_silently=False,
                        html_message=html_message,
                    )
                    # mail to user
                    send_mail(
                        'Product Purchased',
                        f"You have recieved a COD delivery order of {order.total} Rupee for order id = {order.id}, check it out and procced for delivery",
                        EMAIL_HOST_USER,
                        [EMAIL_HOST_USER],
                        fail_silently=False,
                    )
                except:
                    return redirect('Orders')

                return redirect('Orders')
        else:
            return redirect('/checkout/')