Example #1
0
def cart_remove(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    r = Recommender()
    r.set_removed_product_id(product_id)
    cart.remove(product)
    return redirect('cart:cart_detail')
Example #2
0
def order_create(request):
	cart = Cart(request)
	if request.method == 'POST':
		form = OrderCreateForm(request.POST)
		if form.is_valid():
			order = form.save(commit=False)
			if cart.coupon:
				order.coupon = cart.coupon
				order.discount = cart.coupon.discount
			order.save()
			products_for_redis=[]
			for item in cart:
				OrderItem.objects.create(order=order,
				product=item['product'],
				price=item['price'],
				quantity=item['quantity'])
				products_for_redis.append(item['product'])
				# clear the cart
			r=Recommender()
			r.products_bought(products_for_redis)
			cart.clear()
			# launch asynchronous task
			current_lang=translation.get_language()
			order_created.delay( order.id, current_lang)
			return render(request,
			'orders/order/created.html',
			{'order': order})
	else:
		form = OrderCreateForm()
	return render(request,
	'orders/order/create.html',
	{'cart': cart, 'form': form})
Example #3
0
def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductsForm(initial={'quantity': item['quantity'],
                                                                    'update': True})
    coupon_apply_form = CouponApplyForm()
    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)
    return render(request, 'cart/detail.html', {'cart': cart, 'coupon_apply_form': coupon_apply_form, 'recommended_products': recommended_products})
Example #4
0
def cart_detail(request):
    cart = Cart(request)
    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(
            initial={
                'quantity': item['quantity'],
                'update': True
            })
    coupon_apply_form = CouponApplyForm()
    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #5
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     # 是否登录
     if self.request.user.is_authenticated:
         is_logined = True
     else:
         is_logined = False
     context['is_logined'] = is_logined
     # 推荐产品
     recommender = Recommender()
     product = context['product']
     suggest_product_ids = recommender.get_suggest_products([product])
     if not suggest_product_ids:
         context['suggest_products'] = None
     else:
         suggest_products = Product.objects.filter(
             pk__in=suggest_product_ids, is_sold=True)
         context['suggest_products'] = suggest_products
     return context
Example #6
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            if cart.coupon:
                order.coupon = cart.coupon
                order.discount = cart.coupon.discount
            if request.user.is_authenticated:
                order.user = request.user
            order.save()
            products = []
            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
                # создаем список продуктов чтобы добавить их в Redis для последующей рекомендации
                products.append(
                    Product.objects.get(translations__name=item['product']))
            # clear the cart
            cart.clear()
            # order send mail
            order_mail = Order.objects.get(id=order.id)
            subject = 'Order nr. {}'.format(order_mail.id)
            message = 'Dear {},\n\nYou have successfully placed an order. Your order id is {}.'.format(
                order_mail.first_name, order_mail.id)
            mail_sent = send_mail(subject, message, '*****@*****.**',
                                  [order_mail.email])
            # set the order in the session
            request.session['order_id'] = order.id
            # добавляем продукт в базу данных редис (added products in redis db)
            r = Recommender()
            r.products_bought(products)
            # redirect for payment
            return redirect(reverse('payment:process'))
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {
        'cart': cart,
        'form': form
    })
Example #7
0
def cart_detail(request):
    cart = Cart(request)
    for product in cart:
        product['update_quantity_form'] = CartAddItemForm(
            initial={
                'quantity': product['quantity'],
                'override': True
            })
    coupon_apply_form = CouponApplyForm()

    r = Recommender()
    cart_products = [product['item'] for product in cart]
    recommended_products = r.suggest_product_for(cart_products, max_result=4)

    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #8
0
def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item["update_quantity_form"] = CartAddProductForm(
            initial={
                "quantity": item["quantity"],
                "update": True
            })
    coupon_apply_form = CouponApplyForm()
    recommender = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = recommender.suggest_products_for(cart_products, 4)
    return render(
        request,
        "cart/detail.html",
        {
            "cart": cart,
            "coupon_apply_form": coupon_apply_form
        },
    )
Example #9
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            if cart.coupon:
                order.coupon = cart.coupon
                order.discount = cart.coupon.discount
            order.save()
            ptr = []
            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
                ptr.append(Product.objects.get(name=item['product'].name))
            r = Recommender()
            r.products_bought(ptr)
            cart.clear()
            request.session['coupon_id'] = None
            # order_created.delay(order.id)
            return render(request, 'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm()
        return render(request, 'orders/order/create.html', {
            'cart': cart,
            'form': form
        })


# @staff_member_required
# def admin_order_pdf(request, order_id):
# 	order = get_object_or_404(Order, id = order_id)
# 	html = render_to_string('orders/order/pdf.html', {'order':order})

# 	response = HttpResponse(content_type = 'application/pdf')
# 	response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(order.id)
# 	weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')])
# 	return response
Example #10
0
def payment_process(request):
    order_id = request.session.get("order_id")
    order = get_object_or_404(Order, id=order_id)
    total_cost = order.get_total_cost()

    if request.method == "POST":
        # retrieve nonce
        nonce = request.POST.get("payment_method_nonce", None)
        # create and submit transaction
        result = gateway.transaction.sale({
            "amount": f"{total_cost:.2f}",
            "payment_method_nonce": nonce,
            "options": {
                "submit_for_settlement": True
            },
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()
            # launch asynchronous task
            payment_completed.delay(order.id)
            # recommendations update
            r = Recommender()
            r.products_bought([item.product for item in order.items.all()])
            return redirect("payment:done")
        else:
            return redirect("payment:canceled")
    else:
        # generate token
        client_token = gateway.client_token.generate()
        return render(
            request,
            "payment/process.html",
            {
                "order": order,
                "client_token": client_token
            },
        )
Example #11
0
def cart_detail(request):
    cart = Cart(request)
    # this loop make a edit field form for each item in cart
    # it sets override True to use cart add method to update it
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(
            initial={
                'quantity': item['quantity'],
                'override': True
            })
    coupon_apply_form = CouponApplyForm()

    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)
    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #12
0
def order_create(request):
    cart = Cart(request)
    r = Recommender()
    r.products_bought(cart.cart.keys())

    if request.method == 'POST':
        # order = form.save()
        order = Order.objects.create(user=request.user)
        for item in cart:
            OrderItem.objects.create(order=order,
                                     product=item['product'],
                                     price=item['price'],
                                     quantity=item['quantity'])
        cart.clear()
        return redirect(reverse('shop:product_list'))
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {
        'cart': cart,
        'form': form
    })
Example #13
0
    def get(self, request):
        template_name = 'cart/detail.html'
        cart = Cart(request)
        for item in cart:
            item['update_quantity_form'] = CartAddProductForm(
                initial={
                    'quantity': item['quantity'],
                    'update': True
                })

        r = Recommender()
        cart_products = [item['product'] for item in cart]
        recommended_products = r.suggest_products_for(cart_products,
                                                      max_results=4)

        ctx = {
            'cart': cart,
            'recommended_product': recommended_products,
        }

        return render(request, template_name, ctx)
Example #14
0
def cart_detail(request):
    """ Отображаем корзину, основывая на данных сохраненных в сессии """
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(
            initial={
                'quantity': item['quantity'],
                'update': True
            })
    coupon_apply_form = CouponApplyForm()

    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)

    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #15
0
def order_created(order_id):
    """
    Task to send an e-mail motification when an order is
    successfully created
    """
    order = Order.objects.get(id=order_id)
    subject = f'Order nr. {order.id}'
    message = f'Dear {order.first_name},\n\n' \
              f'You have successfully placed an order.' \
              f'Your order ID is {order.id}'
    mail_sent = send_mail(subject, message, '*****@*****.**',
                          [order.email])
    # This part call the recommender and add bought product to redis db
    # when an order create
    order_items = order.items.all()
    products = []
    for oi in order_items:
        products.append(oi.product)

    recommender = Recommender()
    recommender.products_bought(products)
    return mail_sent
Example #16
0
def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        # dodaj do dict każdego elementu podane pole
        # czyli teraz dict posiada pole formy, którą można wyświetlić w widoku
        # tutaj nie ma przesyłania formy!
        item['update_quantity_form'] = CartAddProductForm(
            initial={
                'quantity': item['quantity'],
                'update': True
            })
    coupon_apply_form = CouponApplyForm()
    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)
    # web_pdb.set_trace()
    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #17
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            if cart.coupon:
                order.coupn = cart.coupon
                order.discount = cart.coupon.discount
            order.save()
            for item in cart:
                OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity'])
            cart.clear()
            order_created.delay(order.id)
            request.session['order_id'] = order.id
            r = Recommender()
            r.products_bought([ item['product'] for item in cart])
            return redirect(reverse('payment:process'))
            # return render(request, 'orders/order/created.html', {'order': order})
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {'cart': cart, 'form': form})
Example #18
0
def cart_detail(request: HttpRequest):
    cart = Cart(request)

    for item in cart:
        item: CartItemDetail
        item['update_quantity_form'] = CardAddProductForm(
            initial={
                'quantity': item['quantity'],
                'override': True,
            })

    coupon_apply_form = CouponApplyForm()
    r = Recommender()
    recommended_products = r.suggest_products_for(item['product']
                                                  for item in cart)

    context = {
        'cart': cart,
        'coupon_apply_form': coupon_apply_form,
        'recommended_products': recommended_products,
    }
    return render(request, 'cart/detail.html', context)
Example #19
0
def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        # create an 'update_quantity_form' for all objects in d cart, then set their values to initial value
        item['update_quantity_form'] = CartUpdateProductForm(
            initial={
                'quantity': item['quantity'],
                'update': True
            })

    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)

    coupon_apply_form = CouponApplyForm()
    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'html_title': 'My Shopping Cart',
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #20
0
def cart_detail(request):
    """Обработчик для страницы списка товаров, добавленных в корзину"""
    cart = Cart(request)
    # Изменение количества товаров
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(
            initial={
                'quantity': item['quantity'],
                'update': True
            })
    coupon_apply_form = CouponApplyForm()

    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)

    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #21
0
def order_create(request):
    cart=Cart(request)
    if request.method=="POST":
        form=OrderCreateForm(request.POST)
        if form.is_valid():
            order=form.save(commit=False)
            if cart.coupon:
                order.coupon=cart.coupon
                order.discount=cart.coupon.discount
            order.save()
            for item in cart:
                OrderItem.objects.create(order=order,product=item['product'],price=item['price'],quantity=item['quantity'])
            r=Recommender()
            r.products_bought([item['product'] for item in cart])
            cart.clear()
            order_created.delay(order.id)
            request.session['order_id']=order.id
            return redirect(reverse('payment:process'))

    else:
        form=OrderCreateForm()
    return render(request, 'orders/order/create.html', {'cart':cart, 'form':form})
Example #22
0
def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item["update_quantity_form"] = CartAddProductForm(
            initial={
                "quantity": item["quantity"],
                "override": True
            })
    coupon_apply_form = CouponApplyForm()

    r = Recommender()
    cart_products = [item["product"] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_results=4)

    return render(
        request,
        "cart/detail.html",
        {
            "cart": cart,
            "coupon_apply_form": coupon_apply_form,
            "recommended_products": recommended_products,
        },
    )
def cart_detail(request):
    '''
    method for showing details of the cart
    '''
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CarAddProductForm(
            initial={
                'quantity': item['quantity'],
                'override': True
            })
    coupon_apply_form = CouponApplyForm()

    # recommendation in the cart
    r = Recommender()
    cart_products = [item['product'] for item in cart]
    recommended_products = r.suggest_products_for(cart_products, max_result=4)
    return render(
        request, 'cart/details.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #24
0
def cart_detail(request):
    cart = Cart(request)
    # updating quantity of product in the cart
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(
            initial={
                'quantity': item['quantity'],
                'override': True
            })
        coupon_apply_form = CouponApplyForm()
        r = Recommender()
        cart_products = [item['product'] for item in cart]
        print(cart_products)
        recommended_products = r.suggest_products_for(cart_products,
                                                      max_results=3)
        if coupon_apply_form is None:
            return render(request, 'cart/detail.html', {'cart': cart})
    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #25
0
def create_order(request):
    """使用 cart 的数据创建 order"""
    cart = Cart(request)
    if request.method == 'POST':
        order_form = OrderForm(request.POST)
        if order_form.is_valid():
            # create order
            order = order_form.save(commit=False)
            order.customer = request.user
            order.email = request.user.email
            if cart.coupon:
                order.coupon = cart.coupon
                order.discount = cart.coupon.discount
            order.save()
            # create order_item
            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            cart.clear()
            # store order id
            request.session['order_id'] = order.id
            # send notice mail by celery
            order_created.delay(order.id)
            # 推荐计分
            recommender = Recommender()
            recommender.cal_products_bought(
                [item.product for item in order.items.all()])
            # 重定向到支付页
            return redirect('order:payment_process')
    else:
        order_form = OrderForm()
    return render(request, 'order/create.html', {
        'order_form': order_form,
        'cart': cart
    })
Example #26
0
def cart_detail(request):
    cart = Cart(request)
    # create an instance of CartAddProductForm for each item in the cart to allow
    # changing product quantities.
    for item in cart:
        # You initialize the form with the current item quantity and set the override field to True so that when you submit the form to the cart_
        # add view, the current quantity is replaced with the new one.
        item['update_quantity_form'] = CartAddProductForm(
            initial={
                'quantity': item['quantity'],
                'override': True
            })
        coupon_apply_form = CouponApplyForm()

        r = Recommender()
        cart_products = [item['product'] for item in cart]
        recommended_products = r.suggest_products_for(cart_products,
                                                      max_results=4)
    return render(
        request, 'cart/detail.html', {
            'cart': cart,
            'coupon_apply_form': coupon_apply_form,
            'recommended_products': recommended_products
        })
Example #27
0
def dorder_create(request):
    cart = Cart(request)

    try:
        usr = request.user.id
        user = User.objects.get(id=usr)
        address = Address.objects.get(user_id=user)
    except Address.DoesNotExist:
        user = User.objects.get(id=1)
        address = None

    if request.method == "POST":
        form = BillingAddressCreateForm(
            request.POST,
            initial={
                "billing_street_address": address.street_address,
                "billing_apartment_address": address.apartment_address,
                "billing_city": address.city,
                "billing_postal_code": address.postal_code,
            },
        )

        if cart.coupon == None:
            disc = 0
        else:
            disc = cart.coupon.discount

        if form.is_valid():
            Order.objects.create(
                user=user,
                first_name=user.first_name,
                last_name=user.last_name,
                email=user.email,
                # address=address.street_address,
                # address2=address.apartment_address,
                # postal_code=address.postal_code,
                # city=address.city,
                coupon=cart.coupon,
                discount=disc,
                payment_method=form.cleaned_data["payment_method"],
            )

            order = Order.objects.latest("id")

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

            if form.cleaned_data["same_billing"] == True:
                BillingAddress.objects.create(
                    order=order,
                    billing_street_address=address.street_address,
                    billing_apartment_address=address.apartment_address,
                    billing_city=address.city,
                    billing_postal_code=address.postal_code,
                    phone_number=address.phone_number,
                )
            else:
                BillingAddress.objects.create(
                    order=order,
                    billing_street_address=form.
                    cleaned_data["billing_street_address"],
                    billing_apartment_address=form.
                    cleaned_data["billing_apartment_address"],
                    billing_city=form.cleaned_data["billing_city"],
                    billing_postal_code=form.
                    cleaned_data["billing_postal_code"],
                )

            # Adding products bought to the recommender engine.
            r = Recommender()
            products_bought = [item["product"] for item in cart]
            print(products_bought)
            r.products_bought(products_bought)

            # Deleting items from the cart.
            cart.clear()

            # launch asynchronus task
            order_created.delay(order.id)

            request.session["order_id"] = order.id

            # Payment option is cash after delivery:
            if form.cleaned_data["payment_method"] == "3":
                return render(request, "orders/order/created.html",
                              {"order": order})
            else:
                # redirect for credit / debit card payment
                return redirect(reverse("payment:process"))

    else:
        form = BillingAddressCreateForm()

    return render(
        request,
        "orders/order/create.html",
        {
            "cart": cart,
            "form": form,
            "user": user,
            "address": address
        },
    )
Example #28
0
def order_create(request):
    cart = Cart(request)
    address = None
    user = None
    form = None

    # If user is authenticated.
    if request.user.is_authenticated:
        usr = request.user.id
        user = User.objects.get(id=usr)
        try:
            address = Address.objects.get(user_id=user)
        except Address.DoesNotExist:
            address = None

        if request.method == "POST":
            form = BillingAddressCreateForm(request.POST)

            # Setting discount to zero if there is no Coupon
            if cart.coupon == None:
                disc = 0
            else:
                disc = cart.coupon.discount

            if form.is_valid():

                # Creating Order from OrderCreateForm
                Order.objects.create(
                    user=user,
                    first_name=user.first_name,
                    last_name=user.last_name,
                    email=user.email,
                    coupon=cart.coupon,
                    discount=disc,
                    payment_method=form.cleaned_data["payment_method"],
                )

                order = Order.objects.latest("id")

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

                # Creating Shipping address from User details
                ShippingAddress.objects.create(
                    order=order,
                    shipping_street_address=address.street_address,
                    shipping_apartment_address=address.apartment_address,
                    shipping_city=address.city,
                    shipping_postal_code=address.postal_code,
                    phone_number=address.phone_number,
                )

                if form.cleaned_data["same_billing"] == True:
                    BillingAddress.objects.create(
                        order=order,
                        billing_street_address=address.street_address,
                        billing_apartment_address=address.apartment_address,
                        billing_city=address.city,
                        billing_postal_code=address.postal_code,
                        phone_number=address.phone_number,
                    )
                else:
                    BillingAddress.objects.create(
                        order=order,
                        billing_street_address=form.
                        cleaned_data["billing_street_address"],
                        billing_apartment_address=form.
                        cleaned_data["billing_apartment_address"],
                        billing_city=form.cleaned_data["billing_city"],
                        billing_postal_code=form.
                        cleaned_data["billing_postal_code"],
                        phone_number=form.cleaned_data["phone_number"],
                    )

                # Adding products bought to the recommender engine.
                r = Recommender()
                products_bought = [item["product"] for item in cart]
                r.products_bought(products_bought)

                # Deleting items from the cart.
                cart.clear()

                # launch asynchronus task for email sending
                order_created.delay(order.id)

                request.session["order_id"] = order.id

                # Payment option is cash after delivery:
                if form.cleaned_data["payment_method"] == "3":
                    return render(request, "orders/order/created.html",
                                  {"order": order})
                else:
                    # redirect for credit / debit card payment
                    return redirect(reverse("payment:process"))

        else:
            form = BillingAddressCreateForm()

    # If user is NOT authenticated.
    else:
        user = None
        address = None

        # Using dummy user (VitaKing) for future analytics and idenctification
        dummy_user = User.objects.get(id=1)

        if request.method == "POST":

            form = OrderCreateForm(request.POST)

            # Setting discount to zero if there is no Coupon
            if cart.coupon == None:
                disc = 0
            else:
                disc = cart.coupon.discount

            if form.is_valid():

                # Creating Order from OrderCreateForm
                Order.objects.create(
                    user=dummy_user,
                    first_name=form.cleaned_data["first_name"],
                    last_name=form.cleaned_data["last_name"],
                    email=form.cleaned_data["email"],
                    payment_method=form.cleaned_data["payment_method"],
                    coupon=cart.coupon,
                    discount=disc,
                )

                order = Order.objects.latest("id")

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

                ShippingAddress.objects.create(
                    order=order,
                    shipping_street_address=form.
                    cleaned_data["shipping_street_address"],
                    shipping_apartment_address=form.
                    cleaned_data["shipping_apartment_address"],
                    shipping_city=form.cleaned_data["shipping_city"],
                    shipping_postal_code=form.
                    cleaned_data["shipping_postal_code"],
                    phone_number=form.cleaned_data["phone_number"],
                )

                if form.cleaned_data["same_billing"] == True:
                    BillingAddress.objects.create(
                        order=order,
                        billing_street_address=form.
                        cleaned_data["shipping_street_address"],
                        billing_apartment_address=form.
                        cleaned_data["shipping_apartment_address"],
                        billing_city=form.cleaned_data["shipping_city"],
                        billing_postal_code=form.
                        cleaned_data["shipping_postal_code"],
                        phone_number=form.cleaned_data["phone_number"],
                    )
                else:
                    BillingAddress.objects.create(
                        order=order,
                        billing_street_address=form.
                        cleaned_data["billing_street_address"],
                        billing_apartment_address=form.
                        cleaned_data["billing_apartment_address"],
                        billing_city=form.cleaned_data["billing_city"],
                        billing_postal_code=form.
                        cleaned_data["billing_postal_code"],
                        phone_number=form.cleaned_data["phone_number"],
                    )

                # Adding products bought to the recommender engine.
                r = Recommender()
                products_bought = [item["product"] for item in cart]
                r.products_bought(products_bought)

                # Deleting items from the cart.
                cart.clear()

                # launch asynchronus task for email sending
                order_created.delay(order.id)

                request.session["order_id"] = order.id

                # Payment option is cash after delivery:
                if form.cleaned_data["payment_method"] == "3":
                    return render(request, "orders/order/created.html",
                                  {"order": order})
                else:
                    # redirect for credit / debit card payment
                    return redirect(reverse("payment:process"))

        else:
            form = OrderCreateForm()

    return render(
        request,
        "orders/order/create.html",
        {
            "cart": cart,
            "form": form,
            "user": user,
            "address": address
        },
    )
Example #29
0
from decimal import Decimal
from django.conf import settings
from shop.models import Product
from coupons.models import Coupon
from shop.recommender import Recommender
r = Recommender()


class Cart(object):
    def __init__(self, request):
        """
        Initialize the cart
        """
        self.session = request.session
        self.coupon_id = self.session.get('coupon_id')
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, product, quantity=1, override_quantity=False):
        """
        Add a product to the cart or update its quantity
        """
        r.products_bought([product])
        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {
                'quantity': 0,
                'price': str(product.price)
            }
Example #30
0
def create_order(request):
    cart = Cart(request)
    if request.method == "POST" and ('order_form' in request.POST
                                     or 'order_form_payment' in request.POST):
        order_form = OrderCreateForm(request.POST)
        order_delivery = OrderDeliveryForm(request.POST)
        if order_form.is_valid() and order_delivery.is_valid():
            order = order_form.save(commit=False)
            cd = order_delivery.cleaned_data
            order.city = cd['city']
            order.address = cd['address']
            order.postal_code = cd['postal_code']
            if cart.coupon:
                order.coupon = cart.coupon
                order.discount = cart.coupon.discount
            request.session['coupon_id'] = None
            if request.user.is_authenticated:
                order.user = request.user
            order.save()
            product_list = []
            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
                product_list.append(item['product'])
            cart.clear()
            orderitems = OrderItem.objects.filter(order=order)
            order_url = request.build_absolute_uri(order.get_absolute_url())
            order_created.delay(order.id, order_url)
            r = Recommender()
            r.products_bought(product_list)
            if request.user.is_authenticated:
                description = f'Оформление заказа №{order.id}'
                Bonuses.objects.create(user=request.user,
                                       summa=order.get_bonuses_summ(),
                                       description=description)
            if 'order_form_payment' in request.POST:
                request.session['order_id'] = order.id
                return redirect(reverse('payment:process'))
            else:
                return render(request, 'orders/created.html', {
                    'order': order,
                    'orderitems': orderitems
                })

    else:
        if request.user.is_authenticated:
            order_form = OrderCreateForm(instance=request.user)
            try:
                delivery = Delivery.objects.get(user=request.user)
            except:
                delivery = Delivery.objects.create(user=request.user)
            order_delivery = OrderDeliveryForm(instance=delivery)

        else:
            order_form = OrderCreateForm()
            order_delivery = OrderDeliveryForm()
    context = {
        'cart': cart,
        'order_form': order_form,
        'order_delivery': order_delivery
    }
    return render(request, 'orders/create.html', context)
Example #31
0
# Script to setup a demo recommending system

from shop.models import Product
from shop.recommender import Recommender

r = Recommender()

dell_inspiron = Product.objects.get(name='Dell Inspiron')
dell_laptop = Product.objects.get(name='Dell Laptop')
dell_monitor = Product.objects.get(name='Dell Monitor')
dell_keyboard = Product.objects.get(name='Dell Keyboard')

r.products_bought([dell_monitor, dell_keyboard])
r.products_bought([dell_inspiron, dell_laptop])
r.products_bought([dell_inspiron, dell_keyboard, dell_monitor])
Example #32
0
def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = braintree.Transaction.sale({
            'amount':
            '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce':
            nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()

            # 更新Redis中本次购买的商品分数
            r = Recommender()
            order_items = [
                order_item.product for order_item in order.items.all()
            ]
            r.products_bought(order_items)

            # create invoice e-mail
            subject = 'My Shop - Invoice no. {}'.format(order.id)
            message = 'Please, find attached the invoice for your recent purchase.'
            email = EmailMessage(subject, message, '*****@*****.**',
                                 [order.email])

            # generate PDF
            html = render_to_string('orders/order/pdf.html', {'order': order})
            out = BytesIO()
            stylesheets = [
                weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')
            ]
            weasyprint.HTML(string=html).write_pdf(out,
                                                   stylesheets=stylesheets)
            # attach PDF file
            email.attach('order_{}.pdf'.format(order.id), out.getvalue(),
                         'application/pdf')
            # send e-mail
            email.send()

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # generate token
        client_token = braintree.ClientToken.generate()
        return render(request, 'payment/process.html', {
            'order': order,
            'client_token': client_token
        })
Example #33
0
def payment_process(request):
    # everything = request.session.all() - attempt to catch all objects in the payment
    # print(everything) - creates an error
    order_id = request.session.get('order_id')
    print(order_id)
    order = get_object_or_404(Order, id=order_id)
    print(order)

    # total_cost = order.get_total_cost()
    # trying below with comman for two return values, one of which is the cart object list
    # ref: https://note.nkmk.me/en/python-function-return-multiple-values/
    # total_cost, cart_products_list = order.get_total_cost()
    total_cost = order.get_total_cost()

    # The above print commands were used to identify what was being passed to the order
    # print results:
    # 37
    # Order 37

    # The below doesn't run correctly
    # recommender_add_list = order.get_product_name_list()

    # The below two lines works but gets a list of numbers, a long list. It gets the Foreign Key.
    # name = OrderItem.objects.values_list('product', flat=True)
    # print(product)

    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = gateway.transaction.sale({
            'amount': f'{total_cost:.2f}',
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()
            # launch asynchronous task - not enabled due to invalid OS
            # payment_completed.delay(order.id)
            # name = list(Product.objects.get(name=OrderItem.objects.get(product=product)))
            # cart_products = [item['product'] for item in cart]

            # Insert Recommender Update Here
            r = Recommender()
            # r.products_bought(cart_products_list)
            # r.products_bought(cart_products)
            # r = Recommender()
            # r.products_bought([afternoon_tea, apple_and_elderflower_tea, assam_tea, yunnan_tea])

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # generates a token for payment
        client_token = gateway.client_token.generate()
        return render(request, 'payment/process.html', {
            'order': order,
            'client_token': client_token
        })