예제 #1
0
def remove_from_cart(request, product_id):
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)
예제 #2
0
def cart_clear(request):
    pics = Cart(request)
    pics.clear()
    return HttpResponseRedirect(reverse(viewname='cart'))
예제 #3
0
파일: views.py 프로젝트: bazanta/jarvis
def update_from_cart(request, product_id, quantity):
    product = FicheProduit.objects.get(id=product_id)
    cart = Cart(request)
    cart.update(product, quantity, product.prix)
예제 #4
0
def cart_clear(request):
    cart = Cart(request)
    cart.clear()
    return redirect("favorities")
예제 #5
0
def item_clear(request, id):
    pic = Cart(request)
    product = Picture.objects.get(id=id)
    pic.remove(product)
    return HttpResponseRedirect(reverse(viewname='cart'))
예제 #6
0
파일: views.py 프로젝트: mmaleka/ecommerce
def order_create(request):

    cart = Cart(request)
    orders = Order.objects.all()
    last_order = orders[0]
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            print("form.cleaned_data['shipping']: ", form.cleaned_data['shipping'])
            first_name = request.user.first_name
            last_name = request.user.last_name
            email = request.user.email


            # order = form.save(commit=False)

            address = form.cleaned_data['address']
            postal_code = form.cleaned_data['postal_code']
            city = form.cleaned_data['city']
            # total_price_with_shipping = form.cleaned_data['total_price_with_shipping']
            payment_method = form.cleaned_data['payment_method']

            if form.cleaned_data['shipping'] == 'FD':
                total_price_with_shipping = float(cart.get_total_price_discountTOTAL())
            elif form.cleaned_data['shipping'] == 'PL':
                total_price_with_shipping = float(cart.get_total_price_discountTOTAL()) + float(40)

            order = form.save(commit=False)

            order.first_name = first_name
            order.last_name = last_name
            order.email = email
            # order = form.save(commit=False)
            order.address = address
            order.postal_code = postal_code
            order.city = city
            order.total_price = total_price_with_shipping
            order.payment_method = payment_method

            order = form.save()
            # data = cleaned_data
            order.save()
            for item in cart:
                OrderItem.objects.create(
                    order=order,
                    product=item['product'],
                    price=item['price'],
                    quantity=item['quantity']
                )
            cart.clear()
        # else:
        #     raise Http404
        return render(request, 'orders/order/payment.html', {'order': order})

    else:
        form = OrderCreateForm()

    context = {
    'last_order': last_order,
    'form': form,
    'orders': orders
    }
    return render(request, 'orders/order/create.html', context)
예제 #7
0
def cart_add(request, id):
    cart = Cart(request)
    product = Films.objects.get(id=id)
    cart.add(product=product)
    return redirect("detail", pk=id)
예제 #8
0
def get_checkout_review(request):
    return render(request, 'checkout_review.html', {
        'cart': Cart(request),
    })
예제 #9
0
파일: views.py 프로젝트: parcox/CoffeShopku
    def post(self, request, *args, **kwargs):
        """
        Handle POST requests: instantiate a form instance with the passed
        POST variables and then check if it's valid.
        """
        self.object = None  # assign the object to the view
        User = get_user_model()
        method = self.request.POST['customer']
        cart = Cart(request)
        if (method):
            try:
                qty = []
                product = []
                orders = True
                for x in Item.objects.all():
                    product.append(x.object_id)
                    qty.append(x.quantity)
                queryset = Products.objects.filter(
                    id__in=product).values('stock')
                for i in range(len(queryset)):
                    if queryset[i]['stock'] < qty[i]:
                        orders = False
                if not Item.objects.all():
                    orders = False
                if int(request.POST['payment']) < int(cart.summary()):
                    orders = False
                if request.POST['payment'] == "":
                    orders = False

                name = None
                if (request.POST['name'] == "others"):
                    name = request.POST['name_input']
                else:
                    name = request.POST['name']

                if name == "":
                    orders = False
                if request.POST['barista'] == "":
                    orders = False

                if orders:
                    barista = User.objects.get(id=request.POST['barista']).id
                    customer = Customers.objects.create(
                        name=name,
                        email=request.POST['email'],
                        address=request.POST['address'],
                        phone=request.POST['phone'],
                        payment=request.POST['payment'],
                        barista_id=barista,
                    )

                    order = Orders(invoice=generateInvoice(),
                                   total=cart.summary(),
                                   user_id=request.user.id,
                                   customer_id=customer.id)
                    order.save()
                    if (order):
                        for x in Item.objects.all():
                            orderdetail = OrderDetails(order_id=order.id,
                                                       product_id=x.object_id,
                                                       qty=x.quantity,
                                                       price=x.unit_price)
                            orderdetail.save()
                            if (orderdetail):
                                product = Products.objects.get(id=x.object_id)
                                product.stock = F('stock') - x.quantity
                                product.save()
                                cart.clear()
                    return HttpResponseRedirect(self.get_success_url())
                else:
                    messages.error(
                        request,
                        'Order fail out of stock or form important null or payment minus'
                    )
                    return redirect(reverse('check_out_product'))
            except Exception as e:
                messages.error(
                    request,
                    'Order fail out of stock or form important null or cart null or payment minus'
                )
                return redirect(reverse('check_out_product'))
예제 #10
0
def checkout(request):

    client = Client('http://soap.dev/server.php?wsdl')
    # Get Current Cart
    current_cart = Cart(request)
    myCart = Cart.get_cart_details(current_cart)
    logged_in_user = User.objects.get(pk=request.user.id)
    first_name = logged_in_user.first_name
    last_name = logged_in_user.last_name
    email = logged_in_user.email
    error_message = "Please Fill In Your Personal Details (First Name, Last Name) In USER PROFILE section."
    telephone_error = 'Please correct the telephone number.'

    telephone = request.POST.get('telephone')
    company = request.POST.get('company_name')

    # Check if user wants greater quantity of products than one available in warehouse
    for item in current_cart:
        item_soap_qty = client.service.getQuantity(item.product.id)
        if item.quantity > item_soap_qty:
            template_soap = int(item_soap_qty)
            return render(
                request, 'checkout_review.html', {
                    'error_message':
                    'WARNING! There are only ' + str(template_soap) +
                    ' available pieces for the movie ' +
                    str(item.product.title) + '. You added ' +
                    str(item.quantity) + ' in your cart.',
                    'cart':
                    Cart(request)
                })

    if telephone and not telephone.isdigit():
        return render(request, 'checkout_review.html', {
            'error_message': telephone_error,
            'cart': Cart(request)
        })

    if not first_name:
        return render(request, 'checkout_review.html', {
            'error_message': error_message,
            'cart': Cart(request)
        })
    if not last_name:
        return render(request, 'checkout_review.html', {
            'error_message': error_message,
            'cart': Cart(request)
        })
    if not email:
        return render(request, 'checkout_review.html', {
            'error_message': error_message,
            'cart': Cart(request)
        })

    # Get Current Cart
    current_cart = Cart(request)
    # END

    # Check If Cart Is Empty And Return To Homepage
    if myCart['total_items'] == 0:
        context = Movies.objects.all()
        return render(request, 'homepage.html', {
            'data': context,
            'homepage': True
        })
    # END

    # Create List To Store In DB
    myList = ",".join([str(item.product.id) for item in current_cart])
    # END

    all_products = []
    for item in current_cart:
        temp = {
            'item_id': item.product.id,
            'item_title': item.product.title,
            'quantity': item.quantity,
            'price': str(item.total_price)
        }
        all_products.append(temp)
    json_products = json.dumps(all_products)

    # Get Post DateTime Details And Create DateTime Objects
    delivery_time = request.POST.get('timepicker')
    delivery_date = request.POST.get('datepicker')
    object_date = datetime.datetime.strptime(delivery_date, '%d-%m-%Y')
    object_time = datetime.datetime.strptime(delivery_time, '%H:%M:%S')
    # END

    # Format Date To Store In DB
    dt_store = object_date.date()
    # END

    # Save Cart Details In Order To Appear Later On Checkout Details
    cart_details_for_template = []
    for item in Cart(request):
        cart_details_for_template.append(item)
    # END

    # Add New Order
    new_order = Orders(user_id=request.user.id,
                       session_user_id=request.session.session_key,
                       shopping_cart=myList,
                       shopping_cart_details=json_products,
                       delivery_date=dt_store,
                       delivery_time=delivery_time,
                       total_order_price=myCart['total_price'])
    new_order.save()
    # END

    # Update SOAP DB
    for item in current_cart:
        client.service.removeQuantity(item.product.id, item.quantity)
    # END

    # Get Latest Order Id
    last_order_id = Orders.objects.latest('id')
    #END

    # Generate Random Invoice Number
    random_number = str(random.randint(1000000, 10000000))
    # END

    # Add new Invoice
    new_invoice = Invoices(
        user_id=request.user.id,
        order=last_order_id,
        invoice_identifier=random_number,
        session_user_id=request.session.session_key,
        shopping_cart=myList,
        first_name=first_name,
        last_name=last_name,
        email=email,
        telephone=telephone,
        company=company,
    )
    new_invoice.save()
    # END

    # Clear Current Cart
    current_cart.clear()
    # END

    return render(
        request, 'order_completed.html', {
            'cart': cart_details_for_template,
            'delivery_time': object_time,
            'delivery_date': object_date,
            'total_items': 0,
            'total_price': 0,
        })
예제 #11
0
def get_cart(request):
    return render(request, 'cart.html', {
        'cart': Cart(request),
    })
예제 #12
0
파일: views.py 프로젝트: S1Lv3R5/mrpit
def order_create(request):
    [categories, suppliers, objectives, products_rec, offers] = list()
    cart = Cart(request)
    if not cart:
        messages.error(request, "Корзина пуста!")
        return redirect('cart:cart_detail')
    profile = Profile.published.get(user=request.user)
    data = {
        'first_name': profile.first_name,
        'last_name': profile.last_name,
        'email': profile.email,
        'address': profile.address,
        'city': profile.city,
        'postal_code': profile.postal_code,
        'phone': profile.phone
    }
    postal_code = ''
    if request.method == 'POST':
        if 'form' in request.POST:
            form = OrderCreateForm(request.POST, initial=data)
            order = form.save(commit=False)
        else:
            perm_form = PermOrderCreateForm(request.POST, initial=data)
            order = perm_form.save(commit=False)
        if cart.coupon:
            order.coupon = cart.coupon
            order.discount = cart.coupon.discount

        order.client = request.user
        order.status = 'Новый'
        order.save()
        # Высчитываем массу и создаём объекты заказа в функции calc_order_total_mass
        order.total_mass = calc_order_total_mass(cart, order)
        cart.clear()
        # Пробуем получить стоимость доставки по API почты России.
        try:
            # если Пермь, то по дефолту будет стоить 200р. Если другой  населенный пункт,
            # то пробуем рассчитать через API почты
            if order.city != 'Пермь':
                order.deliver_cost = russian_post_calc(
                    postal_code=order.postal_code, mass=order.total_mass)
        except:
            try:
                # если пользователь ввёл неверный индекс, то пробуем посчитать доставку до белгорода
                order.deliver_cost = russian_post_calc(postal_code='308000',
                                                       mass=order.total_mass)
            except:
                # если пользователь ввёл неверный индекс и API почты не работает, то ставим среднюю доставку 350 р
                order.deliver_cost = 350
        order.save()
        messages.success(request, 'Заказ успешно создан.')
        messages.success(request, 'Оплатить заказ можно по форме ниже.')

        # Отправка письма администрации
        subject = 'Новый заказ'
        sender = '*****@*****.**'
        message = 'Новый заказ!<br> Номер заказа:{}<br> Город: {}<br>' \
                  'Перейти в <a href="https://mrpit.online/admin/orders/order">Админку</a> для просмотра заказа. ' \
            .format(order.id, order.city)
        mail_admin = EmailMessage(subject, message, sender,
                                  ['*****@*****.**', '*****@*****.**'])
        mail_admin.content_subtype = "html"
        mail_admin.send()
        # Отправка письма Клиенту
        client_subject = 'Заказ с сайта MrPit.Online'
        mail_from = '*****@*****.**'
        mail_to = [order.email]
        сlient_message = 'Спасибо за Ваш заказ!<br>Номер заказа:{}<br>' \
                         'Стоимость заказа:{} р., Стоимость доставки:{} р.' \
                         'Масса посылки с учетом упаковки:{} гр.<br>' \
                         'Оплатить заказ Вы можете на сайте в ' \
                         '<a href="https://mrpit.online/account">Личном Кабинете</a><br>' \
                         'После оплаты заказа мы начнём сборку. ' \
                         'Статус заказа Вы можете отслеживать также в личном кабинете.<br><br>' \
                         'Наши соцсети ждут именно Вас:<br>' \
                         '<a href="https://vk.com/mrpit.online">Вконтакте</a><br>' \
                         '<a href="https://instagram.com/mrpit.online">Instagram</a>' \
            .format(order.id, order.get_total_cost(), order.deliver_cost, order.total_mass)
        mail = EmailMessage(client_subject, сlient_message, mail_from, mail_to)
        mail.content_subtype = "html"
        mail.send()
        username = request.user.username
        # перенаправляем пользователя в личный кабинет, где он сможет оплатить заказ
        return redirect('profile')
    else:
        form = OrderCreateForm(initial=data)
        perm_form = PermOrderCreateForm(initial=data)
    template = 'orders/order/create.html'
    context = locals()
    return render(request, template, context)
예제 #13
0
def display_cart(request):

    return render_to_response('cart.html', dict(cart=Cart(request)))
예제 #14
0
def cart(request):
    cart = Cart(request)
    return {'cart': cart}
예제 #15
0
파일: views.py 프로젝트: fanggaoshang/mshop
def remove_from_cart(request, product_id):
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)
    return redirect('/cart/')
예제 #16
0
파일: views.py 프로젝트: parcox/CoffeShopku
def remove_from_cart(request, product_id):
    product = Products.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)
    return HttpResponseRedirect(reverse('order_list_products'))
예제 #17
0
def cart_remove(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    cart.remove(product)
    return redirect('cart:cart_detail')
예제 #18
0
파일: views.py 프로젝트: parcox/CoffeShopku
def get_cart(request):
    return render(request, 'orders/products/cart.html',
                  {'cart': Cart(request)})
예제 #19
0
파일: views.py 프로젝트: ex8/Flower-Flour
def order_create(request):
    config = OrderConfig.objects.get(id=1)
    access_token = Clover.objects.filter().latest('achieved').access_token
    clover = CloverApiClient(api_url=settings.CLOVER_API_URL,
                             merchant_id=settings.CLOVER_MERCHANT_ID,
                             api_key=access_token)
    cart = Cart(request)
    order_items_m = []
    if request.method == 'POST':
        order_form = OrderForm(request.POST)
        card_form = CloverPayForm(request.POST)
        if order_form.is_valid() and card_form.is_valid():
            order = order_form.save()
            # Create OrderItems for FF internal DB
            for item in cart:
                order_item = OrderItem(order=order,
                                       product=item['product'],
                                       price=item['price'],
                                       quantity=item['quantity'])
                order_item.save()
                order_items_m.append(order_item.product.name)

            # Send to Clover PoS, total is converted to cents
            clover_order = clover.order_service.create_order({
                'state':
                'open',
                'title':
                str(order.id),
                'total': (float(order.get_total_cost()) * 100),
                'currency':
                'USD',
            })
            # Create Clover LineItem(s)
            for item in cart:
                if item['quantity'] > 1:
                    for el in range(item['quantity']):
                        clover.order_service.create_line_item(
                            order_id=clover_order['id'],
                            line_item={
                                'name': str(item['product']),
                                'price': float(item['price'] * 100),
                            })
                else:
                    clover.order_service.create_line_item(
                        order_id=clover_order['id'],
                        line_item={
                            'name': str(item['product']),
                            'price': float(item['price'] * 100),
                        })

            # Clover CC Pay
            clover_pay = CloverPay(api_url=settings.CLOVER_API_URL,
                                   merchant_id=settings.CLOVER_MERCHANT_ID,
                                   api_key=access_token)
            card = card_form.cleaned_data
            secrets = clover_pay.get_secrets()
            card_number = card['card_number'].encode()
            # card_number = b'4242424242424242'
            modulus = int(secrets['modulus'])
            exponent = int(secrets['exponent'])
            prefix = secrets['prefix'].encode()
            RSAkey = RSA.construct((modulus, exponent))
            cipher = PKCS1_OAEP.new(RSAkey)
            encrypted = cipher.encrypt(prefix + card_number)
            card_encrypted = b64encode(encrypted).decode()
            payload = {
                "orderId": clover_order['id'],
                "zip": card['zip_code'],
                "expMonth": card['exp_month'],
                "cvv": card['cvv'],
                "amount": (float(order.get_total_cost()) * 100),
                "currency": "usd",
                "last4": card['card_number'][-4:],
                "expYear": card['exp_year'],
                "first6": card['card_number'][0:6],
                "cardEncrypted": card_encrypted
            }
            payment = clover_pay.send_payment(payload)
            if payment['result'] == 'APPROVED':
                order.paid = True
                order.save()
                order.send_client_order_confirm_email(order_items_m,
                                                      clover_order, payment)
                order.send_admin_order_confirm_emails(order_items_m,
                                                      clover_order, payment)
                order.send_admin_order_confirm_sms(clover_order)
                cart.clear()
                return render(request, 'orders/order/created.html',
                              {'config': config})
            else:
                return render(request, 'orders/order/pay-error.html',
                              {'config': config})
        else:
            return render(request, 'orders/order/order-error.html',
                          {'config': config})
    else:
        order_form = OrderForm()
        card_form = CloverPayForm()
    return render(
        request, 'orders/order/create.html', {
            'config': config,
            'order_form': order_form,
            'card_form': card_form,
            'cart': cart,
        })
예제 #20
0
def order_create(request):
    cart = Cart(request)
    total = cart.get_total_price() + SHIPPING_COST
    shipping_address = get_or_create(ShippingAddress, request.user)
    billing_address = get_or_create(BillingAddress, request.user)
    host = request.get_host()
    invoice_str = generate_random_invoice_number()
    request.session['invoice_str'] = invoice_str
    paypal_dict = {
        'business': settings.PAYPAL_RECEIVER_EMAIL,
        'amount': '%.2f' % total.quantize(Decimal('.01')),
        'item_name': 'El Gran Cazador México, carrito de compras',
        'invoice': invoice_str,
        'currency_code': 'MXN',
        'custom': invoice_str,
        'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')),
        'return_url': 'http://{}{}'.format(host, reverse('payment:done')),
        'cancel_return': 'http://{}{}'.format(host,
                                              reverse('payment:canceled'))
    }

    form = PayPalPaymentsForm(initial=paypal_dict)

    if request.method == 'POST':
        domain = settings.URL_DOMAIN

        order = Order()
        order.user = request.user
        order.reference_code = ''
        order.transaction_id = ''
        order.reference_pol = ''
        order.save()

        for item in cart:
            OrderItem.objects.create(order=order,
                                     product=item['product'],
                                     price=item['price'],
                                     quantity=item['quantity'])
        payment_type = request.POST.get('payment_type', '')

        # if the payment was made with oxxo
        if payment_type == 'oxxo':
            charge = payment_oxxo(request)

            order.method = "Oxxo"

            # Create the order with pending status
            order.status = 'PENDIENTE'
            order.reference_code = charge.charges[0]["payment_method"][
                "reference"]
            order.transaction_id = charge.id
            order.save()

            ctx = {
                "total": total,
                "reference": order.reference_code,
                "domain": domain,
            }

            send_mail(request, ctx, payment_type)

            # Clear the cart
            cart.clear()

            # Redirect to response with parameters
            return render(request, 'orders/created.html', {
                'order': order,
            })

        return render(request, 'orders/created.html', {
            'order': order,
        })
    else:
        return {
            'cart': cart,
            'shipping_price': SHIPPING_COST,
            'total': total,
            'shipping_address': shipping_address,
            'billing_address': billing_address,
            'form': form
        }
예제 #21
0
def item_clear(request, id):
    cart = Cart(request)
    product = Films.objects.get(id=id)
    cart.remove(product)
    return redirect("favorities")
예제 #22
0
def cart(request):
    product = Product.objects.all(
    )  #使用ORM执行SELECT * FROM shop_products 查询所有商品,传入模板
    cart = Cart(request)  #使用ORM执行SELECT * FROM cart_item 查询购物车中所有商品,传入模板
    print(cart, request.session['CART-ID'])
    return render(request, 'cart.html', locals())
예제 #23
0
 def get_context_data(self, **kwargs):
     context = super(MainPageMixin, self).get_context_data(**kwargs)
     context['request'] = self.request
     context['cart'] = Cart(self.request)
     return context
예제 #24
0
 def get(sefl, request):
     cart = Cart(request)
     form = OrderCreateForm()
     template = 'orders/order/create.html'
     context = {'cart': cart, 'form': form}
     return render(request, template, context)
예제 #25
0
def item_clear_2(request, id):
    pic = Cart(request)
    product = Picture.objects.get(id=id)
    pic.remove(product)
    return HttpResponseRedirect(
        reverse(viewname="picture", args=[product.title]))
예제 #26
0
파일: views.py 프로젝트: fanggaoshang/mshop
def cart(request):
    all_categories = Category.objects.all()
    cart = Cart(request)
    return render(request, 'cart.html', locals())
예제 #27
0
def cart_add(request, id):
    pic = Cart(request)
    product = Picture.objects.get(id=id)
    pic.add(product=product)
    return HttpResponseRedirect(
        reverse(viewname="picture", args=[product.title]))
예제 #28
0
파일: views.py 프로젝트: fanggaoshang/mshop
def add_to_cart(request, product_id, quantity):
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.add(product, product.price, quantity)
    return redirect('/')
예제 #29
0
파일: views.py 프로젝트: bazanta/jarvis
def delete_from_cart(request, product_id):
    product = FicheProduit.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)
 def wrapper(request, *args, **kwargs):
     cart = Cart(request)
     if len(cart) == 0:
         return render(request, 'order/cart_empty.html')
     else:
         return func(request, *args, **kwargs)