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": f"{order.get_total_cost():.2f}",
            "payment_method_nonce": nonce,
            "options": {
                "submit_for_settlement": True
            },
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            recommender = Recommender()
            recommender.products_bought(order.items.all())

            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()

            # create invoice email
            subject = f"My Shop - Invoice No. {order.id}"
            msg = "Please, find attached the invoice for your recent purchase"
            email = EmailMessage(subject, msg, "*****@*****.**",
                                 [order.email])

            # generate PDF
            html = render_to_string("orders/order/pdf.html", {"order": order})
            out = BytesIO()
            static_root = settings.STATIC_ROOT
            stylesheets = [weasyprint.CSS(f"{static_root}css/pdf.css")]
            weasyprint.HTML(string=html).write_pdf(out,
                                                   stylesheets=stylesheets)

            # attach PDF file
            email.attach(f"order_{order.id}.pdf", out.getvalue(),
                         "application/pdf")

            # send email
            email.send()

            return redirect("payment:done")
        else:
            return redirect("payment:cancelled")
    else:
        # generate token
        client_token = braintree.ClientToken.generate()
        return render(
            request,
            "payment/process.html",
            {
                "client_token": client_token,
                "order": order
            },
        )
Beispiel #2
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 == 'GET':
        random_id = random.randint(0, 999999)
        braintree_id = time.strftime('%Y%m%d%H%M%S') + str(random_id)
        return render(request, 'pays/process.html', {'app_id': settings.APP_ID, 'total_cost': total_cost,'braintree_id':braintree_id})
    else:
        total_cost = request.POST.get('total_cost')
        braintree_id = request.POST.get('braintree_id')
        alipay = AliPay(
            appid=settings.APP_ID,
            app_notify_url=None,
            app_private_key_string=settings.APP_PRIVATE_KEY,
            alipay_public_key_string=settings.APP_PUBLIC_KEY,
            sign_type='RSA2',
            debug=True
        )
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no = braintree_id,
            total_amount = total_cost,
            subject = str(Order.items.product),
            return_url = redirect('payment:done'),
        )
        order.braintree_id = braintree_id
        order.paid = True
        order.save()
        #更新redis中本次购买的商品分数
        r = Recommender()
        order_items = [order_item.product for order_item in order.items.all()]
        r.products_bought(order_items)

        send_order_mail(order)
        return redirect("https://openapi.alipaydev.com/gateway.do?" + order_string)
Beispiel #3
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = Order(**form.data)
            order.save()
            order.paid="1"
            for item in cart:
                order.products.connect(item["product"], {'quantity':item['quantity']})

            order.save()
            print(order.products.all())
            product_ids = list(cart.cart.keys())
            print(product_ids)
            products = []
            for id in product_ids:
                query = f"match (a) where ID(a) = {id} return a"
                result, meta = db.cypher_query(query)
                products.append(Product.inflate(result[0][0]))

            r = Recommender()
            r.products_bought([products])

            # clear the cart
            cart.clear()
            return render(request,
                          'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm()
    return render(request,
                  'orders/order/create.html',
                  {'cart': cart, 'form': form})
Beispiel #4
0
def payment_notification(sender, **kwargs):
    ipn_obj = sender
    if ipn_obj.payment_status == ST_PP_COMPLETED:
        # payment was successful
        order = get_object_or_404(Order, id=ipn_obj.invoice)
        # mark the order as paid
        order.paid = True
        order.save()

        # 支付成功后将产品添加到一起购买的redis中
        items = []
        for item in order.items.all():
            items.append(item.product)
        r = Recommender()
        r.products_bought(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()
    def post(self, *args, **kwargs):
        """
        If the payment process successful, we create an index for products with Redis.
        Add celery task, which sends email invoice with order information [[tasks.py]].
        """

        order = self.get_object()
        total_cost = order.get_total_cost()
        r = Recommender()
        nonce = self.request.POST.get('payment_method_nonce', None)
        result = gateway.transaction.sale({
            'amount': f'{total_cost:.2f}',
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })

        if result.is_success:
            order.paid = True
            order.braintree_id = result.transaction.id
            order.save()
            r.products_bought(order.items.all())
            payment_completed.apply_async([order.pk])
            return redirect('payment:done')

        return redirect('payment:canceled')
Beispiel #6
0
def order_create(request: HttpRequest):
    r = Recommender()
    cart_products = []
    cart = Cart(request)
    if cart.get_total_price() <= 0:
        return redirect(reverse('shop:product_list'))
    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'])
                cart_products.append(item['product'])
            r.products_bought(cart_products)
            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
    })
Beispiel #7
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)
            # 如果session中有优惠码,就修改order模型中的优惠码、折扣字段再保存
            if cart.coupon:
                order.coupon = cart.coupon
                order.discount = cart.coupon.discount
            order.save()
            r = Recommender()
            r.products_bought([item['product'] for item in cart])
            # 这里还是按原价算
            for item in cart:
                OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity'])
                # 清空购物车
                cart.clear()
                # 执行发送邮件通知的异步任务,任务将会被添加进队列中,将会尽快被worker执行
                order_created.delay(order.id)
                # 在session中保存订单号
                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})
Beispiel #8
0
def order_view(request):
    if request.method == 'POST':
        order_form = OrderForm(request.POST)
        if order_form.is_valid():
            cart = Cart(request)
            order = order_form.save()
            for item in cart:
                # Create new order item
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
                # Update ranking for products
                r.zincrby('product_ranking', item['quantity'],
                          item['product'].pk)
            rec = Recommender()
            rec.products_bought(order)
            cart.clear()
            payment_url = request.build_absolute_uri(
                reverse('order:payment', args=[
                    order.pk,
                ]))
            send_order_created_email.delay(order.pk, order.email, payment_url)
            return redirect('order:payment', pk=order.pk)
    else:
        order_form = OrderForm()

    return render(request, 'order/order.html', {'order_form': order_form})
Beispiel #9
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.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(name=item['product']))
            # очистить корзину
            cart.clear()
            # order send mail
            queue = django_rq.get_queue('default')
            queue.enqueue(order_created, order.id)
            # добавляем продукт в базу данных редис
            r = Recommender()
            r.products_bought(products)
            return render(request, 'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {
        'cart': cart,
        'form': form
    })
Beispiel #10
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})
Beispiel #11
0
def order_create(request):
    """
    view for creating customer order
    :param request:
    :return:
    """
    cart = Cart(request)
    form = OrderCreateForm()
    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()
            cart_products = [item['product'] for item in cart]
            r.products_bought(cart_products)
            # clear the cart
            cart.clear()
            order_created.delay(order.id)
            # set the order id in the session
            request.session['order_id'] = order.id
            # redirect for payment
            return redirect(reverse('payment:process'))
    return render(request, 'order/create.html', {'cart': cart, 'form': form})
Beispiel #12
0
def order_create(request):
    cart = Cart(request)
    r = Recommender()
    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.products_bought([item['product'] for item in cart])
            # clear the cart
            cart.clear()
            # launch asynchronous task
            order_created.delay(order.id)
            # set the order in the session
            request.session['order_id'] = order.id
            # redirect for payment
            request.session['order_id'] = order.id
            # redirect for payment
            return redirect(reverse('payment:process'))
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {
        'cart': cart,
        'form': form
    })
Beispiel #13
0
def place_order(request):

    if request.method == 'POST':

        form = OrderForm(request.POST)

        r = Recommender()

        cart = Cart(request)

        if form.is_valid():
            order = form.save(commit=False)
            order.discount = cart.get_discount()
            order.coupon = cart.coupon
            order.save()

            for item in cart:

                order.items.create(product=item['product'],
                                   price=item['price'],
                                   quantity=item['quantity'])

            cart.clear()

            send_order_email.delay(order.id)

            r.products_bought([item['product'] for item in cart])

            return render(request, 'order/successful_order.html',
                          {'order_id': order.id})

    return render(request, 'order/order_form.html', {'form': OrderForm()})
Beispiel #14
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"],
                )
            # clear the cart
            cart.clear()
            # launch asynchronous task
            order_created.delay(order.id)
            # set the order in the session
            request.session["order_id"] = order.id
            # add recommendation
            recommender = Recommender()
            recommender.products_bought(order.items.all())
            # redirect for payment
            return redirect("payment:process")
    else:
        form = OrderCreateForm()
    return render(request, "orders/order/create.html", {
        "cart": cart,
        "form": form
    })
Beispiel #15
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":
        # 获得token
        nonce = request.POST.get('payment_method_nonce', None)
        # 使用token 创建提交交易
        result = braintree.Transaction.sale({
            'amount':
            '{:2f}'.format(order.get_total_cost()),
            'payment_method_nonce':
            nonce,
            'options': {
                'submit_for_settlement': True,
            }
        })
        if result.is_success:
            # 更改支付状态
            order.paid = True
            # 保存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)
            # 创建代有pdf的发票
            subject = 'My shop - Invoice no {}'.format(order_id)
            message = 'Please,find attached the invouce for your recent purchase'
            email = EmailMessage(subject, message, '*****@*****.**',
                                 [order.email])

            # 生成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)

            # 附加pdf附件
            email.attach('order_{}.pdf'.format(order_id), out.getvalue(),
                         'application/pdf')
            # 发送邮件
            email.send()
            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # 生成临时token交给js
        client_token = braintree.ClientToken.generate()
        return render(request, 'payment/process.html', {
            'order': order,
            'client_token': client_token
        })
Beispiel #16
0
def cart_detail(request):
    cart = Cart(request)

    r = Recommender()
    cart_products = [item['product'] for item in cart]
    r.products_bought([item['product'] for item in cart])

    recommended_products = r.suggest_products_for(cart_products , max_results = 4)
    return render(request, 'cart/details.html', {'cart': cart , 'recommended_products': recommended_products})
Beispiel #17
0
def payment_process(request):
    order_id = request.session['order_id']
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        nonce = request.POST.get('payment_method_nonce', None)
        result = braintree.Transaction.sale({
            'amount':
            '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce':
            nonce,
            "options": {
                "submit_for_settlement": True
            }
        })
        if result.is_success:
            order.paid = True
            order.braintree_id = result.transaction.id
            order.save()

            #record products to be bought together
            r = Recommender()
            products = [item.product for item in order.items.all()]
            r.products_bought(products)

            #create mail of invoice
            subject = "My shop - invoice no. {}".format(order.id)
            message = 'Please, find attateched the invoice for your recent purchases.'
            email = EmailMessage(subject, message, '*****@*****.**',
                                 [order.email])

            html = render_to_string('admin/orders/order/pdf.html',
                                    {'order': order})
            stylesheets = [
                weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')
            ]
            out = weasyprint.HTML(string=html).write_pdf(
                stylesheets=stylesheets)

            email.attach('order_{}'.format(order.id), out, 'application/pdf')
            email.send()

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')

    else:
        #client_token=braintree.ClientToken.generate()

        gateway = braintree.BraintreeGateway(
            braintree.Configuration.instantiate())
        client_token = gateway.client_token.generate()

        return render(request, 'payment/process.html', {
            'order': order,
            'client_token': client_token
        })
Beispiel #18
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'])
                # name=item['name'])
            # last line 'name' ^^^ is addtional, in order to list names dircetly for recommender, as oppsed to a separate query
            # This is non-functional at present, it will only return a list of numbers as a foriegn key as opposed to one name
            # of the product as originally intended.

            # cart_product_objects = [item['product'] for item in cart] - original iteration causes a tuple unpacking error.
            cart_product_objects = [item['product'] for item in cart]
            print(type(cart_product_objects))
            print(cart_product_objects)

            for item in cart_product_objects:
                print(item)

            # Update recommender

            r = Recommender()
            r.products_bought(cart_product_objects)

            # clear the cart
            cart.clear()

            # The system to send a confirmation email below is disabled due to system incompatibility.
            # launch asynchronous task
            # order_created.delay(order.id)
            # set the order in the session
            request.session['order_id'] = order.id
            # redirect for payment. Original version passed the objects list to the payment section,
            # however this caused multiple errors through a problem GET request that were best resolved here.
            return redirect(
                reverse('payment:process'))  #, cart_product_objects
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {
        'cart': cart,
        'form': form
    })
Beispiel #19
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]

    r.products_bought(cart_products)

    recommended_products = r.suggest_products_for(cart_products, 4)
    return render(request, 'cart/detail.html', {'cart': cart,
                                                'coupon_apply_form': coupon_apply_form,
                                                'recommended_products': recommended_products})
Beispiel #20
0
def payment_process(request):
    anon_user, created = User.objects.get_or_create(
        username='******')
    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':
        # retrive 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
            # set order payer for different types of users
            if request.user.is_authenticated:
                order.payer = request.user
            else:
                order.payer = anon_user
            # get list of products that were bought together
            products = _get_list_of_products_from_the_order(order)
            if len(products) > 1:

                # store and score the products that were bought together.
                r = Recommender()
                r.products_bought(products)
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()
            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
        })
Beispiel #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
            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
    })
Beispiel #22
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
            },
        )
Beispiel #23
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
Beispiel #24
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
    })
Beispiel #25
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
Beispiel #26
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})
Beispiel #27
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
        },
    )
Beispiel #28
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])
Beispiel #29
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
        },
    )
Beispiel #30
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
        })
Beispiel #31
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)