Beispiel #1
0
def cart(request):
    cartProducts = request.session.get('products')

    orderItems = get_order_items(cartProducts)

    # if there is a promo code, update the cart with order items
    coupon = Coupon()
    orderItems, couponMessage = coupon.apply_coupon(orderItems, request)
    cart_total = get_order_items_cart_total(orderItems)

    context = {}
    context['orderItems'] = orderItems
    context['cart_total'] = cart_total
    context['couponMessage'] = couponMessage
    # context = {'order': order}
    context['categories'] = Category.objects.all()[:50]

    return render(request, 'cart.html', context)
Beispiel #2
0
def checkout(request):
    context = {}

    cartProducts = request.session.get('products')
    orderItems = get_order_items(cartProducts)
    coupon = Coupon()
    orderItems, couponMessage = coupon.apply_coupon(orderItems, request)
    cart_total = get_order_items_cart_total(orderItems)

    context['categories'] = Category.objects.all()[:50]
    context['orderItems'] = orderItems
    context['cart_total'] = cart_total
    context['couponMessage'] = couponMessage

    ### GET REQUEST #############
    if request.method == 'GET':
        ## FORMS
        context['CustomerSignUpForm'] = CustomerSignUpForm()
        # context['ProductCollectionForm'] = ProductCollectionForm()
        context['PaymentStoreSelectForm'] = PaymentStoreSelectForm()
        context['ShippingAddressSelectForm'] = ShippingAddressSelectForm()
        context[
            'CustomerFaceAddressCreateForm'] = CustomerFaceAddressCreateForm()
        context['CheckoutPaymentMethodsForm'] = CheckoutPaymentMethodsForm()

    ### POST REQUEST #############
    if request.method == 'POST':
        passCriteria = False

        # productCollectionForm = ProductCollectionForm(request.POST)
        shippingAddressSelectForm = ShippingAddressSelectForm(request.POST)
        customerSignUpForm = CustomerSignUpForm(request.POST)
        customerFaceAddressCreateForm = CustomerFaceAddressCreateForm(
            request.POST)
        checkoutPaymentMethodsForm = CheckoutPaymentMethodsForm(request.POST)
        paymentStoreSelectForm = PaymentStoreSelectForm(request.POST)
        paymentStoreId = None
        product_collection_choice = request.POST.get(
            'product_collection_choice')

        ## FOR LOGIN USERS
        if request.user.is_authenticated:
            user = request.user

            # inserting the selected address option into the form, as they are loaded dynamically on the frontend
            addressSelectedID = request.POST.get('addressSelected')
            shippingAddressSelectForm.fields['addressSelected'].choices = [
                (addressSelectedID, addressSelectedID)
            ]

            # PRODUCT COLLECTION VIA SHIPPING:
            if product_collection_choice == 'shipping':

                # user selects an existing address
                if shippingAddressSelectForm.is_valid(
                ) and shippingAddressSelectForm.cleaned_data[
                        'addressSelected'] != '-1':

                    shippingAddress = Address.objects.get(
                        pk=shippingAddressSelectForm.
                        cleaned_data['addressSelected'])
                    passCriteria = True

                # User selects a new address
                elif customerFaceAddressCreateForm.is_valid():
                    shippingAddress = customerFaceAddressCreateForm.save(
                        commit=False)
                    passCriteria = True

            # PRODUCT COLLECTION IN STORE:
            elif product_collection_choice == 'store-pickup' and paymentStoreSelectForm.is_valid(
            ):
                paymentStoreId = paymentStoreSelectForm.cleaned_data.get(
                    'paymentStore')
                passCriteria = True

        ## IF NOT LOGGEDIN: CHECK IF ADDRESS FORM  OR COLLECTION STORE IS CORRECT
        elif customerSignUpForm.is_valid():
            if product_collection_choice == 'shipping' and customerFaceAddressCreateForm.is_valid(
            ):
                shippingAddress = customerFaceAddressCreateForm.save(
                    commit=False)
                passCriteria = True
            elif product_collection_choice == 'store-pickup' and paymentStoreSelectForm.is_valid(
            ):
                paymentStoreId = paymentStoreSelectForm.cleaned_data.get(
                    'paymentStore')
                passCriteria = True

        ## IF NOT LOGGEDIN: CHECK IF PAYMENT STORE IS SELECTED
        if passCriteria:
            if checkoutPaymentMethodsForm.is_valid():

                # create new user if the user is not authenticated
                if not request.user.is_authenticated:
                    user = customerSignUpForm.save(request)

                ## Reuse Indodana order if exists, else create new
                order, order_created = Order.objects.get_or_create(
                    customer=user.customer,
                    paymentOption='Indodana',
                    status='Awaiting Indodana payment',
                    defaults={
                        'customer': user.customer,
                        'orderChannel': 'Website',
                        'coupon': coupon.coupon,
                    })
                # remove all order items from the order in case the customer has manipulated the cart
                if not order_created:
                    order.orderitem_set.clear()

                # Saving the address or payment store
                if paymentStoreId:
                    order.store = Store.objects.get(id=paymentStoreId)
                else:
                    shippingAddress.save()
                    order.shippingAddress = shippingAddress
                    user.customer.address_set.add(shippingAddress)
                    user.save()

                order.paymentOption = checkoutPaymentMethodsForm.cleaned_data.get(
                    'payment_method')
                if checkoutPaymentMethodsForm.cleaned_data.get(
                        'installment_period'):
                    order.installmentPeriod = checkoutPaymentMethodsForm.cleaned_data.get(
                        'installment_period')

                if checkoutPaymentMethodsForm.cleaned_data.get(
                        'payment_store'):
                    order.installmentPeriod = checkoutPaymentMethodsForm.cleaned_data.get(
                        'payment_store')

                # status setting:
                if order.paymentOption == 'Bank Transfer':
                    order.status = 'Awaiting Bank Transfer'
                elif order.paymentOption == 'Payment in the store':
                    order.status = 'Awaiting payment in store'
                elif order.paymentOption == 'Payment on delivery':
                    order.status = 'Awaiting payment on delivery'
                elif order.paymentOption == 'Indodana':
                    order.status = 'Awaiting Indodana payment'
                else:
                    order.status = 'Unknown'

                order.save()

                for orderItem in orderItems:
                    orderItem.save()
                    order.orderitem_set.add(orderItem)

                ### REGULAR ORDER PROCESSING ###
                if not order.paymentOption == 'Indodana':

                    for orderItem in orderItems:
                        productHistory = ProductHistory()
                        productHistory.adjust_stock_order(
                            orderItem, 'Website Purchase')

                    # updating the coupon code stats
                    if coupon.coupon:
                        coupon.coupon.amountUsed += 1
                        coupon.coupon.customersUsedCoupons.add(user)
                        coupon.coupon.save()

                    # delete the products from the cart
                    if request.session.get('products'):
                        del request.session['products']
                    # todo delete coupon code from session

                    # login the customer if the customer is not logged in already
                    if not request.user.is_authenticated:
                        login(
                            request,
                            user,
                            backend='django.contrib.auth.backends.ModelBackend'
                        )

                    send_order_emails(order)
                    return render(request, 'order-completed.html', context)

                ## INDODANA REQUEST SENDING ##
                else:
                    indodana = Indodana(order)
                    indodana.send_transaction_request()
                    #! save transaction code!!
                    print('RESP DATA',
                          indodana.resp_data)  # todo delete this line

                    if indodana.is_valid():
                        return redirect(indodana.redirect_url)
                    else:
                        context[
                            'indodata_error_message'] = indodana.error_message

        context['ShippingAddressSelectForm'] = shippingAddressSelectForm
        context['CustomerSignUpForm'] = customerSignUpForm
        context[
            'CustomerFaceAddressCreateForm'] = customerFaceAddressCreateForm
        context['CheckoutPaymentMethodsForm'] = checkoutPaymentMethodsForm

    return render(request, 'checkout.html', context)
Beispiel #3
0
def order_create_cart_view(request, pk):
    """view for staff to create orders for customers"""

    customer_user = User.objects.get(pk=pk)

    order, orderIsCreated = Order.objects.get_or_create(
        customer=customer_user.customer, status='Pending')

    orderItems = order.orderitem_set.all()
    coupon = Coupon()
    orderItems, couponMessage = coupon.apply_coupon(
        orderItems, request, customer_user=customer_user)
    cart_total = get_order_items_cart_total(orderItems)

    if request.method == 'GET':
        shippingAddressSelectForm = ShippingAddressSelectForm()
        checkoutPaymentMethodsForm = CheckoutPaymentMethodsForm()
        staffOrderCreateForm = StaffOrderCreateForm()
        del checkoutPaymentMethodsForm.fields['payment_method'].choices[
            -1]  # deleting indodana as option in the list
        checkoutPaymentMethodsForm.fields[
            'installment_period'].widget = forms.HiddenInput(
            )  # disabling installment period, as it can be used only directly by the customer login
        paymentStoreSelectForm = PaymentStoreSelectForm()
        customerFaceAddressCreateForm = CustomerFaceAddressCreateForm()

    if request.method == 'POST':
        passCriteria = False

        # inserting the selected address option into the form, as they are loaded dynamically on the frontend
        shippingAddressSelectForm = ShippingAddressSelectForm(request.POST)
        customerFaceAddressCreateForm = CustomerFaceAddressCreateForm(
            request.POST)
        checkoutPaymentMethodsForm = CheckoutPaymentMethodsForm(request.POST)
        paymentStoreSelectForm = PaymentStoreSelectForm(request.POST)
        paymentStoreId = None
        product_collection_choice = request.POST.get(
            'product_collection_choice')

        staffOrderCreateForm = StaffOrderCreateForm(request.POST)

        ## PRODUCT COLLECTION VIA SHIPPING:
        if product_collection_choice == 'shipping':

            addressSelectedID = request.POST.get('addressSelected')
            shippingAddressSelectForm.fields['addressSelected'].choices = [
                (addressSelectedID, addressSelectedID)
            ]

            # SECTION OF EXISTING ADDRESS
            if shippingAddressSelectForm.is_valid(
            ) and shippingAddressSelectForm.cleaned_data[
                    'addressSelected'] != '-1':

                shippingAddress = Address.objects.get(
                    pk=shippingAddressSelectForm.
                    cleaned_data['addressSelected'])
                passCriteria = True

            # SELECTION TO ENDER A NEW ADDRESS
            elif customerFaceAddressCreateForm.is_valid():
                shippingAddress = customerFaceAddressCreateForm.save(
                    commit=False)
                passCriteria = True

        ## PRODUCT COLLECTION IN STORE:
        elif product_collection_choice == 'store-pickup' and paymentStoreSelectForm.is_valid(
        ):
            paymentStoreId = paymentStoreSelectForm.cleaned_data.get(
                'paymentStore')
            passCriteria = True


        if passCriteria and \
            checkoutPaymentMethodsForm.is_valid() and \
            staffOrderCreateForm.is_valid():

            # Saving the address or payment store
            if paymentStoreId:
                order.store = Store.objects.get(id=paymentStoreId)
            else:
                shippingAddress.save()
                customer_user.customer.address_set.add(shippingAddress)
                order.shippingAddress = shippingAddress

            # setting payment option
            order.paymentOption = checkoutPaymentMethodsForm.cleaned_data.get(
                'payment_method')

            # status setting:
            if order.paymentOption == 'Bank Transfer':
                order.status = 'Awaiting Bank Transfer'
            elif order.paymentOption == 'Payment in the store':
                order.status = 'Awaiting payment in store'
            elif order.paymentOption == 'Payment on delivery':
                order.status = 'Awaiting payment on delivery'
            elif order.paymentOption == 'Indodana':
                order.status = 'Awaiting Indodana payment'
            else:
                order.status = 'Unknown'

            order.orderChannel = staffOrderCreateForm.cleaned_data.get(
                'orderChannel')
            order.shippingCost = staffOrderCreateForm.cleaned_data.get(
                'shippingCost')
            order.notes = staffOrderCreateForm.cleaned_data.get('notes')
            order.staff = request.user
            customer_user.save()

            # managing stock
            for orderItem in orderItems:
                orderItem.save()
                productHistory = ProductHistory()
                productHistory.adjust_stock_order(orderItem,
                                                  'Purchase via backoffice')

            # processing the coupon
            if coupon.coupon:
                coupon.coupon.amountUsed += 1
                coupon.coupon.customersUsedCoupons.add(customer_user)
                coupon.coupon.save()
                order.coupon = coupon.coupon

            order.save()

            return redirect('order-details', pk=order.id)

    context = {}
    context['user'] = customer_user
    context['attributes'] = Attribute.objects.all()
    context['categories'] = Category.objects.all()
    context['ShippingAddressSelectForm'] = shippingAddressSelectForm
    context['CheckoutPaymentMethodsForm'] = checkoutPaymentMethodsForm
    context['PaymentStoreSelectForm'] = paymentStoreSelectForm
    context['StaffOrderCreateForm'] = staffOrderCreateForm
    context['CustomerFaceAddressCreateForm'] = customerFaceAddressCreateForm
    context['orderItems'] = orderItems
    context['couponMessage'] = couponMessage

    return render(request, 'order-create-cart.html', context)