Exemplo n.º 1
0
def checkout(request):
    if request.method == "POST":
        item_json = request.POST.get('item_json', '')
        name = request.POST.get('name', '')
        email = request.POST.get('email', '')
        address = request.POST.get('add1', '') + request.POST.get('add2', '')
        city = request.POST.get('city', '')
        zip_code = request.POST.get('name', '')
        state = request.POST.get('name', '')

        order = Order(item_json=item_json,
                      name=name,
                      email=email,
                      address=address,
                      city=city,
                      zip_code=zip_code,
                      state=state)
        order.save()
        thank = True
        id = order.order_id
        return render(request, 'store/checkout.html', {
            'thank': thank,
            "id": id
        })

    return render(request, 'store/checkout.html')
Exemplo n.º 2
0
def custom_confirmation(request):
    if request.method == "POST":
        form = CustomOrderForm(request.POST)
        # Check if the form is valid:
        if form.is_valid():
            material_id = form.cleaned_data['custom_material']

            order_obj = Order(
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                student_id=form.cleaned_data['student_id'],
                email=form.cleaned_data['email'],
                phone=form.cleaned_data['phone'],
                is_custom=True,
                custom_links=form.cleaned_data['custom_links'],
                custom_quantity=form.cleaned_data['custom_quantity'],
                custom_material=Material.objects.get(
                    id=material_id) if material_id != -1 else None,
                special_instructions=form.cleaned_data['special_instructions'],
                grand_total=0.0)
            order_obj.save()

            context = {"order": order_obj}

            send_confirmation_email(context, form.cleaned_data['email'])

            return render(request, 'confirmation.html', context=context)
    else:
        return custom_ordering(request)
Exemplo n.º 3
0
def place_order(request, product_id): ## VTR1 Done.
	"""
	Place order and update customer details.
	"""
	try:
		if user is None:
			return HttpResponseRedirect('/shop/login/')
	except:
		return HttpResponseRedirect('/shop/login/')
	
	customer = Customer.objects.get(customer_name=user.customer_name)
	product = Product.objects.get(pk=product_id)
	time_of_order = timezone.now()
	## Decide mode of payment and take appropriate action
	if customer.store_credit >= product.price:
		customer.store_credit -= product.price
		payment_type = 1
	else:
		payment_type = 2
	## Update purchase history and save instance
	customer.purchase_history += product.price
	customer.save()
	## Create a new Order object
	order = Order(customer = customer, product = product, status = 1, status_change_time = time_of_order, payment_type = payment_type)
	order.save()

	if payment_type == 1:
		payment_type = 'Paid from store credit'
	else:
		payment_type = 'Cash on delivery'
	context = {'product':product, 'customer':customer, 'time_of_order':time_of_order,
			   'payment_type':payment_type, 'user':user}
	return render(request, 'store/order_success.html', context)
Exemplo n.º 4
0
def checkout(request):
    if request.method == 'POST':
        items_json = request.POST.get('itemsjson', "")
        amount = request.POST.get('amount', "")
        name = request.POST.get('name', "")
        email = request.POST.get('email', "")
        address = request.POST.get('address1', "") + "" + request.POST.get(
            'address2', "")
        city = request.POST.get('city', "")
        state = request.POST.get('state', "")
        zip = request.POST.get('zip', "")
        phone = request.POST.get('phone', "")
        order = Order(items_json=items_json,
                      name=name,
                      email=email,
                      address=address,
                      city=city,
                      state=state,
                      zip=zip,
                      phone=phone,
                      amount=amount)
        order.save()
        thank = True
        id = order.order_id
        return render(request, 'store/checkout.html', {
            'thank': thank,
            'id': id
        })
    return render(request, 'store/checkout.html')
Exemplo n.º 5
0
    def create(self, request):
        session_key = request.META['HTTP_SESSION_KEY']
        cart = get_object_or_404(Cart, session_key=session_key)
        data = request.data
        buyer = Buyer(name=data['name'],
                      surname=data['surname'],
                      email=data['email'],
                      phone=data['phone'],
                      address=data['address'])
        buyer.save()

        order = Order(cart=cart, buyer=buyer)
        order.save()

        # get all staff that have email
        staff = User.objects.filter(is_staff=True).exclude(email__exact='')

        emails = [user.email for user in staff]

        send_mail(
            "Новый заказ",
            "Новый заказ от {} {}. Посетите админку https://apimystore.artsmn.ml/admin/ .\n Order id: {}"
            .format(buyer.name, buyer.surname,
                    order.id), settings.EMAIL_HOST_USER, emails)

        serializer = OrderSerializer(order)
        return Response(serializer.data, 201)
Exemplo n.º 6
0
def cart(request):
    cart = request.session.get('cart', {})
    entries = [Entry(product=Product.objects.get(pk=pk),
                     quantity=cart[pk]) for pk in cart]
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            order = Order(customer=request.user)
            order.address = form.cleaned_data['address']
            order.save()
            for entry in entries:
                entry.order = order
            Entry.objects.bulk_create(entries)
            messages.add_message(request, 777, f'Thanks for shopping! Your order was created with ID: {order.pk}.')
            request.session['cart'] = {}
            return redirect('profile:profile')
    else:
        data = {'name': request.user.name,
                'phone': request.user.phone}
        form = OrderForm(initial=data)

    total_price = sum(entry.price for entry in entries)
    context = {
        'entries': entries,
        'total_price': total_price,
        'form': form,
        'cart': sum(request.session.get('cart', {}).values()),
    }
    return render(request, 'cart.html', context)
Exemplo n.º 7
0
Arquivo: tests.py Projeto: m3wolf/ert
 def test_from_email(self):
     order = Order(f_name="Homer",
                   l_name="Simpson",
                   email="*****@*****.**")
     self.assertEqual(
         order.from_email(),
         "Homer Simpson <*****@*****.**>"
     )
Exemplo n.º 8
0
def create(request):
    #set_day = request.POST['set_day'] 셋데이 여기서 빼고, 밑에 order=Order(set_day 여기서도 뺐다)
    pickuptime = request.POST['pickuptime']
    today_lineup = request.POST['today_lineup']
    order_quota = request.POST['order_quota']
    ordered_date = request.POST['orderd_date']
    order = Order(pickuptime=pickuptime, orderedate=timezone.now())
    orderlist = Orderlist(today_lineup=today_lineup, order_quota=order_quota)
    order.save()
    orderlist.save()
    #누구누구님안녕하세요 기능넣고, first_name order db로 넘기기
    return redirect('store:order_detail', order_id=order.id)
Exemplo n.º 9
0
def cart_form(request):
    if request.method == 'POST' and request.is_ajax():
        print(request)
        name = request.POST.get('field1')
        address = request.POST.get('location')
        email = request.POST.get('field2')
        message = request.POST.get('field3')
        phone = request.POST.get('field4')

        client = Client(name=name,
                        address=address,
                        email=email,
                        phone=phone,
                        message=message)
        client.save()

        products = {}
        items = []
        i = 0
        while request.POST.get('products[' + str(i) + '][id]') is not None:
            id = request.POST.get('products[' + str(i) + '][id]')
            amount = request.POST.get('products[' + str(i) + '][amount]')
            products[id] = amount
            i += 1
            item = OrderItems(product=Product.objects.get(pk=id),
                              amount=amount)
            item.save()
            items.append(item)

        order = Order(client=client)
        order.save()
        order.orderItems.set(items)

        subject = 'טופס הזמנה חדש של חקלתות'
        recipient_list = [
            '*****@*****.**',
        ]
        my_body = 'שם: {}\n כתובת: {}\n מייל: {}\n פאלפון: {}\n הערות: {}\n'.format(
            name, address, email, phone, message)
        my_body += '\nמוצרים:\n'
        for item in items:
            my_body += 'פריט: \t{} כמות: \t{}\n'.format(
                item.product.title, item.amount)
        email = EmailMessage(subject,
                             body=my_body,
                             from_email='MS-GLOBAL <*****@*****.**>',
                             to=recipient_list,
                             reply_to=['*****@*****.**'])
        mail_res = email.send(True)

    print(request)
    return home_view(request)
Exemplo n.º 10
0
 def post(self, request):
     is_valid = True
     # Validation on the submitted request
     if len(request.DATA['order_items']) == 0:
         # Failed due to empty order
         is_valid = False
         response_data = {
             'status': 'failed',
             'reason': 'order_items cannot be empty'
         }
     if is_valid:
         order = Order(**request.DATA['order_data'])
         order.save()
         # Create OrderItem instances from the submitted order
         order_items = request.DATA['order_items']
         for item in order_items:
             new_item = OrderItem()
             new_item.beer = Beer.objects.get(pk=item['beer']['id'])
             new_item.quantity = item['quantity']
             new_item.order = order
             new_item.save()
         # Send relevant emails
         order.notify_ert()
         order.send_confirmation()
         # Send API response
         response_data = {'status': 'success', 'order_id': order.id}
         response = Response(response_data)
     else:
         response = Response(response_data,
                             status=status.HTTP_400_BAD_REQUEST)
     return response
Exemplo n.º 11
0
def orderInfo(request):
    print(request.POST)
    if not request.session['loggedIn']:
        return redirect('store_front')
    else:
        with connection.cursor() as cursor:
            cursor.execute(
                "SELECT p.Name, p.Price, p.ID FROM store_product p, store_cart c, store_cart_Product_ID cp WHERE c.Customer_Email_id=%s AND c.id = cp.cart_id AND cp.product_id = p.id",
                [request.session['userName']])
            cartItems = cursor.fetchall()
            cursor.execute(
                "SELECT SUM(p.Price) FROM store_product p, store_cart c, store_cart_Product_ID cp WHERE c.Customer_Email_id=%s AND c.id = cp.cart_id AND cp.product_id = p.id",
                [request.session['userName']])
            totalPrice = cursor.fetchone()[0]
            cursor.execute("SELECT Address FROM store_customer WHERE Email = %s", [request.session['userName']])
            address = cursor.fetchone()[0]
        if request.method == 'POST' and 'placeOrder' in request.POST:
            print('working')
            newOrder = Order()
            newOrder.Total_Price = totalPrice
            newOrder.Shipping_Info = request.POST['shippingAddress']
            newOrder.Billing_Info = request.session['ccNum']
            request.session['ccNum'] = None
            newOrder.Placed_By = Customer.objects.get(pk=request.session['userName'])
            newOrder.save()
            for item in cartItems:
                newOrder.Product_ID.add(item[2])
            myCart = Cart.objects.get(Customer_Email=request.session['userName'])
            myCart.Product_ID.clear()
            return order(request, newOrder.Order_Number)
        return render(request, 'store/orderInfo.html', {'cartItems': cartItems,
                                                        'total': totalPrice,
                                                        'shippingAddress': address,
                                                        'creditCard': request.session['ccNum']})
Exemplo n.º 12
0
def confirmation(request):
    if request.method == "POST":
        #protection against refreshing or posts with empty cart
        if len(request.session['cart']) == 0:
            context = generate_cart_context(request)
            context[
                'alert_message'] = "You have to order something first before you can get a confirmation. 🤔"
            return render(request, 'cart.html', context=context)

        form = CheckoutForm(request.POST)
        # Check if the form is valid:
        if form.is_valid():
            order_obj = Order(
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                student_id=form.cleaned_data['student_id'],
                email=form.cleaned_data['email'],
                phone=form.cleaned_data['phone'],
                special_instructions=form.cleaned_data['special_instructions'],
                grand_total=0.0)
            order_obj.save()

            grand_total = 0
            for cart_id, cart_item in request.session['cart'].items():
                product_obj = Product.objects.get(id=cart_item['product_id'])
                material_obj = Material.objects.get(id=cart_item['material'])
                price = int(cart_item['quantity']) * product_obj.price
                grand_total += price

                product_instance = ProductInstance(product=product_obj,
                                                   material=material_obj,
                                                   quantity=int(
                                                       cart_item['quantity']),
                                                   total_price=price,
                                                   order=order_obj)
                product_instance.save()
            order_obj.grand_total = grand_total

            context = generate_cart_context(request)
            context["order"] = order_obj

            send_confirmation_email(context, form.cleaned_data['email'])

            request.session['cart'] = {}
            return render(request, 'confirmation.html', context=context)
    else:
        context = generate_cart_context(request)
        context[
            'alert_message'] = "You have to order something first before you can get a confirmation. 🤔"
        return render(request, 'cart.html', context=context)
Exemplo n.º 13
0
def order(request, pk):
    related_item = Item.objects.get(pk=pk)
    if request.FILES:
        image = request.FILES['image']
    else:
        image = None

    new_order = Order(item=related_item,
                      description=request.POST['placename'],
                      email=request.POST['email'],
                      phone=request.POST['phone'],
                      name=request.POST['name'],
                      image=image)
    new_order.save()
    request.session['from_order'] = True
    return redirect(reverse('landing:index'))
Exemplo n.º 14
0
    def post(self, request):
        address = request.POST.get('address')
        mobile = request.POST.get('mobile')
        customer = request.session.get('customer')
        cart = request.session.get('cart')
        products = Product.get_product_by_id(list(cart.keys()))
        print(address, mobile, customer, cart, products)

        for product in products:
            order = Order(customer=Costomer(id=customer),
                          product=product,
                          price=product.price,
                          address=address,
                          mobile=mobile,
                          qauntity=cart.get(str(product.id)))
            order.placeOrder()
        return redirect('cart')
Exemplo n.º 15
0
Arquivo: views.py Projeto: m3wolf/ert
 def post(self, request):
     is_valid = True
     # Validation on the submitted request
     if len(request.DATA['order_items']) == 0:
         # Failed due to empty order
         is_valid = False
         response_data = {
             'status': 'failed',
             'reason': 'order_items cannot be empty'
         }
     if is_valid:
         order = Order(**request.DATA['order_data'])
         order.save()
         # Create OrderItem instances from the submitted order
         order_items = request.DATA['order_items']
         for item in order_items:
             new_item = OrderItem()
             new_item.beer = Beer.objects.get(pk=item['beer']['id'])
             new_item.quantity = item['quantity']
             new_item.order = order
             new_item.save()
         # Send relevant emails
         order.notify_ert()
         order.send_confirmation()
         # Send API response
         response_data = {
             'status': 'success',
             'order_id': order.id
         }
         response = Response(response_data)
     else:
         response = Response(response_data,
                             status=status.HTTP_400_BAD_REQUEST)
     return response
Exemplo n.º 16
0
def place_order(request, product_id):  ## VTR1 Done.
    """
	Place order and update customer details.
	"""
    try:
        if user is None:
            return HttpResponseRedirect('/shop/login/')
    except:
        return HttpResponseRedirect('/shop/login/')

    customer = Customer.objects.get(customer_name=user.customer_name)
    product = Product.objects.get(pk=product_id)
    time_of_order = timezone.now()
    ## Decide mode of payment and take appropriate action
    if customer.store_credit >= product.price:
        customer.store_credit -= product.price
        payment_type = 1
    else:
        payment_type = 2
    ## Update purchase history and save instance
    customer.purchase_history += product.price
    customer.save()
    ## Create a new Order object
    order = Order(customer=customer,
                  product=product,
                  status=1,
                  status_change_time=time_of_order,
                  payment_type=payment_type)
    order.save()

    if payment_type == 1:
        payment_type = 'Paid from store credit'
    else:
        payment_type = 'Cash on delivery'
    context = {
        'product': product,
        'customer': customer,
        'time_of_order': time_of_order,
        'payment_type': payment_type,
        'user': user
    }
    return render(request, 'store/order_success.html', context)
Exemplo n.º 17
0
    def post(self, request):
        address = request.POST.get('address')
        phone = request.POST.get('phone')
        customer = request.session.get('customer')
        cart = request.session.get('cart')
        products = Product.get_products_by_id(list(cart.keys()))
        print(address, phone, customer, cart, products)

        for product in products:
            print(cart.get(str(product.id)))
            order = Order(customer=Customer(id=customer),
                          product=product,
                          price=product.price,
                          address=address,
                          phone=phone,
                          quantity=cart.get(str(product.id)))
            order.save()
        request.session['cart'] = {}

        return redirect('cart')
Exemplo n.º 18
0
 def get(self, request):
     customer_id = request.session.get('customer_id')
     if customer_id:
         orders = Order.get_orders(customer_id)
         data = dict()
         data['title'] = 'Orders'
         data['orders'] = orders
         return render(request, 'orders.html', data)
     else:
         return_url = request.META['PATH_INFO']
         return redirect(f'login?return_url={return_url}')
Exemplo n.º 19
0
 def get(self, request):
     # if customer is already logged in
     if request.session.get('customer_id'):
         # getting current customer_id from session
         customer_id = request.session.get('customer_id')
         cart = request.session.get('cart')
         # getting the objects 
         customer = Customer.objects.get(id = customer_id)
         products = Product.get_products_byId(list(cart.keys()))
         # setting values
         for product in products:
             order = Order(customer_name=customer,
             product=product, quantity=cart.get(str(product.id)), price = product.price, 
             address=customer.address, phone=customer.phone )
             # placing order
             order.place_order()
         # clearing the cart
         request.session['cart'] = {}
         return redirect('orders')
     else:
         return redirect('login')
Exemplo n.º 20
0
def process_payment(stripe_email, stripe_token, form):
    order = Order(
        state='S',
        from_first_name=form.cleaned_data['from_first_name'],
        from_last_name=form.cleaned_data['from_last_name'],
        from_email=stripe_email,
        stripe_tx=stripe_token,
        to_first_name=form.cleaned_data['to_first_name'],
        to_last_name=form.cleaned_data['to_last_name'],
        delivery_company_name=form.cleaned_data['delivery_company_name'],
        delivery_first=form.cleaned_data['delivery_first'],
        delivery_second=form.cleaned_data['delivery_second'],
        delivery_third=form.cleaned_data['delivery_third'],
        delivery_postcode=form.cleaned_data['delivery_postcode'],
        delivery_note=form.cleaned_data['delivery_note'],
    )

    try:
        # Create a charge: this will charge the user's card
        charge = stripe.Charge.create(amount=1600,
                                      currency='gbp',
                                      source=stripe_token,
                                      description='One succulent surprise')

        order.state = 'P'
    except stripe.error.CardError as e:
        # The card has been declined
        order.state = 'E'
    finally:
        order.save()

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

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

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

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

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

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

        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        signals.item_was_sold.send(sender=self.__class__,
                                   order=order,
                                   site=site,
                                   request=request)
        return HttpResponseRedirect(self.get_success_url())
Exemplo n.º 22
0
def create_order(request):
    try:
        address_id = request.data["address"]
        address = Address.objects.get(id=address_id)
    except Address.DoesNotExist:
        return Response({"error": "Address not found"},
                        status=status.HTTP_404_NOT_FOUND)

    if address.owner != request.user:
        return Response(status=status.HTTP_403_FORBIDDEN)

    # calculate the total price of all cart items
    cart_items = CartItem.objects.filter(owner=request.user)
    amount = 0.0
    for item in cart_items:
        price = item.product.price
        amount += price * item.count

    order = Order(owner=request.user,
                  shipping_address=address,
                  total_price=amount)

    order.save()

    # create individual order items
    for item in cart_items:
        order_item = OrderItem(item=item.product,
                               count=item.count,
                               order=order)
        order_item.save()

    # delete all cart items for the user
    for item in cart_items:
        item.delete()

    return Response(status=status.HTTP_201_CREATED)
Exemplo n.º 23
0
    def post(self, request):
        address = request.POST.get('address')
        phone = request.POST.get('phone')
        cart = request.session.get('cart')
        products = Product.getProductById(list(cart.keys()))
        customer = request.session.get('customer')

        for product in products:

            newOrder = Order(
                product=product,
                customer=Customer(id=customer),
                quantity=cart[str(product.id)],
                price=product.price,
                address=address,
                phone=phone,
            )
            newOrder.save()
            print(newOrder.id)

            OrderEmail.delay(order_id=newOrder.id)

        request.session['cart'] = {}
        return redirect('order')
Exemplo n.º 24
0
    def handle(self, *args, **options):
        Product.objects.all().delete()

        now = timezone.now()

        Product(
            pk=1,
            name='Mineral Water Strawberry',
            description=
            'Natural-flavored strawberry with an anti-oxidant kick.',
            price=1.00,
            photo='products/mineralwater-strawberry.jpg',
        ).save()
        Product(
            pk=2,
            name='Mineral Water Raspberry',
            description='Flavoured with raspberry, loaded with anti-oxidants.',
            price=2.00,
            photo='products/mineralwater-raspberry.jpg',
            sale_start=now + timedelta(days=20),
            sale_end=None,
        ).save()
        Product(
            pk=3,
            name='Vitamin A 10,000 IU (125 caplets)',
            price=3.00,
            description=
            'Vitamin A is essential for normal and night vision, and helps maintain healthy skin and mucous membranes.',
            sale_start=now - timedelta(days=10),
            sale_end=None,
            photo='products/vitamin-a.jpg',
        ).save()
        Product(
            pk=4,
            name='Vitamin B-Complex (100 caplets)',
            price=3.00,
            description=
            'Contains a combination of essential B vitamins that help convert food to energy.',
            sale_start=now,
            sale_end=now + timedelta(days=10),
            photo='products/vitamin-bcomplex.jpg',
        ).save()

        Order.objects.all().delete()

        for i in range(1, 11):
            Order(pk=i, product_id=i % 4 + 1,
                  quantity=random.randint(1, 20)).save()
Exemplo n.º 25
0
 def get_context_data(self):
     context = super(OrderDetailView, self).get_context_data()
     context['cancelled_order_count'] = Order.get_cancelled_order_count(
         self.request, user=self.request.user)
     context['awaiting_order_count'] = Order.get_awaiting_order_count(
         self.request, user=self.request.user)
     context['confirmed_order_count'] = Order.get_confirmed_order_count(
         self.request, user=self.request.user)
     context['total_order_count'] = Order.get_total_order_count(
         self.request, user=self.request.user)
     context['delivered_order_count'] = Order.get_delivered_order_count(
         self.request, user=self.request.user)
     context['processing_order_count'] = Order.get_processing_order_count(
         self.request, user=self.request.user)
     return context
Exemplo n.º 26
0
def checkout(request):
    if request.method == "GET":
        form = CheckoutForm()
        cart = request.session.get('cart')

        if cart is None:
            cart = []

        for c in cart:
            size_str = c.get('size')
            tshirt_id = c.get('tshirt')
            size_obj = SizeVarient.objects.get(size=size_str, tshirt=tshirt_id)
            c['size'] = size_obj
            c['tshirt'] = size_obj.tshirt
        context = {'form': form, 'cart': cart}

        return render(request,
                      template_name="store/checkout.html",
                      context=context)
    else:
        form = CheckoutForm(request.POST)
        user = None
        print("user 11", user)
        if request.user.is_authenticated:
            print("user 12", user)
            user = request.user
        if form.is_valid():
            print("user 13", user)
            # payment
            cart = request.session.get('cart')
            if cart is None:
                cart = []
            for c in cart:
                size_str = c.get('size')
                tshirt_id = c.get('tshirt')
                size_obj = SizeVarient.objects.get(size=size_str,
                                                   tshirt=tshirt_id)
                c['size'] = size_obj
                c['tshirt'] = size_obj.tshirt
            shipping_addres = form.cleaned_data.get('shipping_addres')
            contact = form.cleaned_data.get('contact')
            payment_method = form.cleaned_data.get('payment_method')
            total = cal_total_payable_amount(cart)

            print(shipping_addres, contact, payment_method, total)

            order = Order()
            order.shipping_addres = shipping_addres
            order.contact = contact
            order.payment_method = payment_method
            order.total = total
            order.order_status = "PENDING"
            order.user = user
            order.save()

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

            # payment gateway
            response = api.payment_request_create(
                amount=order.total,
                purpose='Payment for tshirt',
                send_email=True,
                buyer_name=f'{user.first_name} {user.last_name}',
                email=user.email,
                redirect_url="http://127.0.0.1:8000/validate_payment")
            # print('response', response)
            print('request_id', response['payment_request']['id'])
            print('request_longurl', response['payment_request']['longurl'])

            payment_id = (response['payment_request']['id'])
            url = response['payment_request']['longurl']

            payment = Payment()
            payment.order = order
            payment.payment_request_id = payment_id
            payment.save()
            return redirect(url)

        else:
            return redirect('/checkout/')
Exemplo n.º 27
0
 def get(self, request):
     customer = request.session.get('customer')
     orders = Order.get_orders_by_customer(customer)
     print(orders)
     return render(request, 'templates/orders.html', {'orders': orders})
Exemplo n.º 28
0
 def create_cart(uid):
     o = Order(paid=False)
     o.save()
     os = Orders(order_id=o.id, user_id=uid)
     os.save()
     return o
Exemplo n.º 29
0
def checkout(request):
    # get Request
    if request.method == 'GET':
        form = CheckForm()
        cart = request.session.get('cart')
        if cart is None:
            cart = []

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

        print(cart)

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

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

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

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

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

            payment = Payment()
            payment.order = order
            payment.payment_request_id = payment_request_id
            payment.save()
            return redirect(url)
        else:
            return redirect('/checkout/')
Exemplo n.º 30
0
def checkOutView(request, coupon_id):
    total = 0
    counter = 0
    cart_items = None
    discount_price = None
    new_total = None
    add_coupon = False
    coupon = None

    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))  #ดึงตะกร้า
        cart_items = CartItem.objects.filter(
            cart=cart, active=True)  #ดึงข้อมูลสินค้าในตะกร้า
        for item in cart_items:
            total += (item.product.price * item.quantity)
            counter += (item.quantity)
    except Exception as e:
        pass

    form = CheckOutForm(request.POST)

    if request.method == 'POST':

        if 'confirm' in request.POST:
            print('Uppppppppppppppppppppppppppppppppp')
            if coupon_id == 0:
                new_total = total

            else:
                coupon = Coupon.objects.get(id=coupon_id)
                new_total = total - coupon.discount
                add_coupon = True

        else:
            print('Downnnnnnnnnnnnnnnnnnnnnnnnnnnnnn')
            if coupon_id == 0:
                new_total = total

            else:
                coupon = Coupon.objects.get(id=coupon_id)
                new_total = total - coupon.discount
                add_coupon = True
            form = CheckOutForm(request.POST)
            if form.is_valid():
                now = timezone.now()
                data = Order()

                data.first_name = form.cleaned_data['first_name']
                data.last_name = form.cleaned_data['last_name']
                data.phone = form.cleaned_data['phone']
                data.user_id = request.user.username
                data.address = form.cleaned_data.get('address')
                data.city = form.cleaned_data.get('city')
                data.district = form.cleaned_data.get('district')
                data.subdistrict = form.cleaned_data.get('subdistrict')
                data.postcode = form.cleaned_data.get('postcode')
                data.total = new_total
                data.status = 'รอชำระเงิน'
                if coupon_id != 0:
                    data.code = coupon.code
                data.save()

                for item in cart_items:
                    order_item = OrderItem.objects.create(
                        product=item.product.name,
                        quantity=item.quantity,
                        price=item.product.price,
                        order=data)
                    order_item.save()
                    #ลดจำนวนstock
                    product = Product.objects.get(id=item.product.id)
                    product.stock = int(item.product.stock -
                                        order_item.quantity)
                    product.save()
                    item.delete()
                order = Order.objects.get(id=data.id)
                return redirect(order.get_url())

    else:
        form = CheckOutForm()
        new_total = total

    return render(
        request, "checkout.html",
        dict(cart_items=cart_items,
             total=total,
             counter=counter,
             form=form,
             new_total=new_total,
             coupon=coupon,
             add_coupon=add_coupon,
             coupon_id=coupon_id))
def checkout(request):
    if request.method == 'GET':     #for get Request
        form = CheckForm()
        cart=request.session.get('cart')
        if cart is None:
            cart=[]
        
        for c in cart:
            size_str = c.get('size')
            tshirt_id = c.get('tshirt')
            size_obj=SizeVariant.objects.get(size=size_str , tshirt=tshirt_id)   #now in cart list ,size is replaced by its object
            c['size']=size_obj
            c['tshirt']=size_obj.tshirt   #replacing in cart list , tshirt is id ,inplace of id tshirt object is stored

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

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

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

        if not instance.exchangeable and validated_data.get('retreat'):
            raise serializers.ValidationError({
                'non_field_errors': [
                    _("This reservation is not exchangeable. Please contact us "
                      "to make any changes to this reservation.")
                ]
            })

        user = instance.user
        payment_token = validated_data.pop('payment_token', None)
        single_use_token = validated_data.pop('single_use_token', None)
        need_transaction = False
        need_refund = False
        amount = 0
        profile = PaymentProfile.objects.filter(owner=user).first()
        instance_pk = instance.pk
        current_retreat: Retreat = instance.retreat
        coupon = instance.order_line.coupon
        coupon_value = instance.order_line.coupon_real_value
        order_line = instance.order_line
        request = self.context['request']

        if not self.context['request'].user.is_staff:
            validated_data.pop('is_present', None)

        if not instance.is_active:
            raise serializers.ValidationError({
                'non_field_errors':
                [_("This reservation has already been canceled.")]
            })

        with transaction.atomic():
            # NOTE: This copy logic should probably be inside the "if" below
            #       that checks if a retreat exchange is done.
            # Create a copy of the reservation. This copy keeps track of
            # the exchange.
            canceled_reservation = instance
            canceled_reservation.pk = None
            canceled_reservation.save()

            instance = Reservation.objects.get(id=instance_pk)

            canceled_reservation.is_active = False
            canceled_reservation.cancelation_reason = 'U'
            canceled_reservation.cancelation_action = 'E'
            canceled_reservation.cancelation_date = timezone.now()
            canceled_reservation.save()

            # Update the reservation
            instance = super(ReservationSerializer, self).update(
                instance,
                validated_data,
            )

            # Update retreat seats
            free_seats = current_retreat.places_remaining
            if current_retreat.reserved_seats or free_seats == 1:
                current_retreat.add_wait_queue_place(user)

            if validated_data.get('retreat'):
                # Validate if user has the right to reserve a seat in the new
                # retreat
                new_retreat = instance.retreat
                old_retreat = current_retreat

                user_waiting = new_retreat.wait_queue.filter(user=user)

                if not new_retreat.can_order_the_retreat(user):
                    raise serializers.ValidationError({
                        'non_field_errors': [
                            _("There are no places left in the requested "
                              "retreat.")
                        ]
                    })
                if user_waiting:
                    user_waiting.delete()

            if (self.context['view'].action == 'partial_update'
                    and validated_data.get('retreat')):
                if order_line.quantity > 1:
                    raise serializers.ValidationError({
                        'non_field_errors': [
                            _("The order containing this reservation has a "
                              "quantity bigger than 1. Please contact the "
                              "support team.")
                        ]
                    })
                days_remaining = current_retreat.start_time - timezone.now()
                days_exchange = timedelta(
                    days=current_retreat.min_day_exchange)
                respects_minimum_days = (days_remaining >= days_exchange)
                new_retreat_price = validated_data['retreat'].price
                if current_retreat.price < new_retreat_price:
                    # If the new retreat is more expensive, reapply the
                    # coupon on the new orderline created. In other words, any
                    # coupon used for the initial purchase is applied again
                    # here.
                    need_transaction = True
                    amount = (validated_data['retreat'].price -
                              order_line.coupon_real_value)
                    if not (payment_token or single_use_token):
                        raise serializers.ValidationError({
                            'non_field_errors': [
                                _("The new retreat is more expensive than "
                                  "the current one. Provide a payment_token or "
                                  "single_use_token to charge the balance.")
                            ]
                        })
                if current_retreat.price > new_retreat_price:
                    # If a coupon was applied for the purchase, check if the
                    # real cost of the purchase was lower than the price
                    # difference.
                    # If so, refund the real cost of the purchase.
                    # Else refund the difference between the 2 retreats.
                    need_refund = True
                    price_diff = (current_retreat.price -
                                  validated_data['retreat'].price)
                    real_cost = order_line.cost
                    amount = min(price_diff, real_cost)
                if current_retreat == validated_data['retreat']:
                    raise serializers.ValidationError({
                        'retreat': [
                            _("That retreat is already assigned to this "
                              "object.")
                        ]
                    })
                if not respects_minimum_days:
                    raise serializers.ValidationError({
                        'non_field_errors':
                        [_("Maximum exchange date exceeded.")]
                    })
                if need_transaction and (single_use_token and not profile):
                    # Create external profile
                    try:
                        create_profile_res = create_external_payment_profile(
                            user)
                    except PaymentAPIError as err:
                        raise serializers.ValidationError({
                            'message': err,
                            'detail': err.detail
                        })
                    # Create local profile
                    profile = PaymentProfile.objects.create(
                        name="Paysafe",
                        owner=user,
                        external_api_id=create_profile_res.json()['id'],
                        external_api_url='{0}{1}'.format(
                            create_profile_res.url,
                            create_profile_res.json()['id']))
                # Generate a list of tuples containing start/end time of
                # existing reservations.
                start = validated_data['retreat'].start_time
                end = validated_data['retreat'].end_time
                active_reservations = Reservation.objects.filter(
                    user=user,
                    is_active=True,
                ).exclude(pk=instance.pk)

                for reservation in active_reservations:
                    for date in reservation.retreat.retreat_dates.all():
                        latest_start = max(
                            date.start_time,
                            start,
                        )
                        shortest_end = min(
                            date.end_time,
                            end,
                        )
                        if latest_start < shortest_end:
                            raise serializers.ValidationError({
                                'non_field_errors': [
                                    _("This reservation overlaps with another "
                                      "active reservations for this user.")
                                ]
                            })
                if need_transaction:
                    order = Order.objects.create(
                        user=user,
                        transaction_date=timezone.now(),
                        authorization_id=1,
                        settlement_id=1,
                    )
                    new_order_line = OrderLine.objects.create(
                        order=order,
                        quantity=1,
                        content_type=ContentType.objects.get_for_model(
                            Retreat),
                        object_id=validated_data['retreat'].id,
                        coupon=coupon,
                        coupon_real_value=coupon_value,
                    )
                    tax = round(amount * Decimal(TAX_RATE), 2)
                    amount *= Decimal(TAX_RATE + 1)
                    amount = round(amount * 100, 2)
                    retreat = validated_data['retreat']

                    # Do a complete refund of the previous retreat
                    try:
                        refund_instance = refund_retreat(
                            canceled_reservation, 100,
                            "Exchange retreat {0} for retreat "
                            "{1}".format(str(current_retreat),
                                         str(validated_data['retreat'])))
                    except PaymentAPIError as err:
                        if str(err) == PAYSAFE_EXCEPTION['3406']:
                            raise serializers.ValidationError({
                                'non_field_errors': [
                                    _("The order has not been charged yet. "
                                      "Try again later.")
                                ],
                                'detail':
                                err.detail
                            })
                        raise serializers.ValidationError({
                            'message': str(err),
                            'detail': err.detail
                        })

                    if payment_token and int(amount):
                        # Charge the order with the external payment API
                        try:
                            charge_response = charge_payment(
                                int(round(amount)), payment_token,
                                str(order.id))
                        except PaymentAPIError as err:
                            raise serializers.ValidationError({
                                'message':
                                err,
                                'detail':
                                err.detail
                            })

                    elif single_use_token and int(amount):
                        # Add card to the external profile & charge user
                        try:
                            card_create_response = create_external_card(
                                profile.external_api_id, single_use_token)
                            charge_response = charge_payment(
                                int(round(amount)),
                                card_create_response.json()['paymentToken'],
                                str(order.id))
                        except PaymentAPIError as err:
                            raise serializers.ValidationError({
                                'message':
                                err,
                                'detail':
                                err.detail
                            })
                    charge_res_content = charge_response.json()
                    order.authorization_id = charge_res_content['id']
                    order.settlement_id = charge_res_content['settlements'][0][
                        'id']
                    order.reference_number = charge_res_content[
                        'merchantRefNum']
                    order.save()
                    instance.order_line = new_order_line
                    instance.save()

                if need_refund:
                    tax = round(amount * Decimal(TAX_RATE), 2)
                    amount *= Decimal(TAX_RATE + 1)
                    amount = round(amount * 100, 2)
                    retreat = validated_data['retreat']

                    refund_instance = Refund.objects.create(
                        orderline=order_line,
                        refund_date=timezone.now(),
                        amount=amount / 100,
                        details="Exchange retreat {0} for "
                        "retreat {1}".format(str(current_retreat),
                                             str(validated_data['retreat'])),
                    )

                    try:
                        refund_response = refund_amount(
                            order_line.order.settlement_id, int(round(amount)))
                        refund_res_content = refund_response.json()
                        refund_instance.refund_id = refund_res_content['id']
                        refund_instance.save()
                    except PaymentAPIError as err:
                        if str(err) == PAYSAFE_EXCEPTION['3406']:
                            raise serializers.ValidationError({
                                'non_field_errors': [
                                    _("The order has not been charged yet. "
                                      "Try again later.")
                                ],
                                'detail':
                                err.detail
                            })
                        raise serializers.ValidationError({
                            'message': str(err),
                            'detail': err.detail
                        })

                    new_retreat = retreat
                    old_retreat = current_retreat

        # Send appropriate emails
        # Send order confirmation email
        if need_transaction:
            items = [{
                'price':
                new_order_line.content_object.price,
                'name':
                "{0}: {1}".format(str(new_order_line.content_type),
                                  new_order_line.content_object.name),
            }]

            merge_data = {
                'STATUS':
                "APPROUVÉE",
                'CARD_NUMBER':
                charge_res_content['card']['lastDigits'],
                'CARD_TYPE':
                PAYSAFE_CARD_TYPE[charge_res_content['card']['type']],
                'DATETIME':
                timezone.localtime().strftime("%x %X"),
                'ORDER_ID':
                order.id,
                'CUSTOMER_NAME':
                user.first_name + " " + user.last_name,
                'CUSTOMER_EMAIL':
                user.email,
                'CUSTOMER_NUMBER':
                user.id,
                'AUTHORIZATION':
                order.authorization_id,
                'TYPE':
                "Achat",
                'ITEM_LIST':
                items,
                'TAX':
                round(
                    (new_order_line.cost - current_retreat.price) *
                    Decimal(TAX_RATE),
                    2,
                ),
                'DISCOUNT':
                current_retreat.price,
                'COUPON': {
                    'code': _("Échange")
                },
                'SUBTOTAL':
                round(new_order_line.cost - current_retreat.price, 2),
                'COST':
                round((new_order_line.cost - current_retreat.price) *
                      Decimal(TAX_RATE + 1), 2),
            }

            Order.send_invoice([order.user.email], merge_data)

        # Send refund confirmation email
        if need_refund:
            merge_data = {
                'DATETIME': timezone.localtime().strftime("%x %X"),
                'ORDER_ID': order_line.order.id,
                'CUSTOMER_NAME': user.first_name + " " + user.last_name,
                'CUSTOMER_EMAIL': user.email,
                'CUSTOMER_NUMBER': user.id,
                'TYPE': "Remboursement",
                'NEW_RETREAT': new_retreat,
                'OLD_RETREAT': old_retreat,
                'SUBTOTAL': old_retreat.price - new_retreat.price,
                'COST': round(amount / 100, 2),
                'TAX': round(Decimal(tax), 2),
            }

            plain_msg = render_to_string("refund.txt", merge_data)
            msg_html = render_to_string("refund.html", merge_data)

            try:
                response_send_mail = send_mail(
                    "Confirmation de remboursement",
                    plain_msg,
                    settings.DEFAULT_FROM_EMAIL,
                    [user.email],
                    html_message=msg_html,
                )

                EmailLog.add(user.email, 'refund', response_send_mail)
            except Exception as err:
                additional_data = {
                    'title': "Confirmation de remboursement",
                    'default_from': settings.DEFAULT_FROM_EMAIL,
                    'user_email': user.email,
                    'merge_data': merge_data,
                    'template': 'refund'
                }
                Log.error(source='SENDING_BLUE_TEMPLATE',
                          message=err,
                          additional_data=json.dumps(additional_data))
                raise

        # Send exchange confirmation email
        if validated_data.get('retreat'):
            merge_data = {
                'DATETIME': timezone.localtime().strftime("%x %X"),
                'CUSTOMER_NAME': user.first_name + " " + user.last_name,
                'CUSTOMER_EMAIL': user.email,
                'CUSTOMER_NUMBER': user.id,
                'TYPE': "Échange",
                'NEW_RETREAT': new_retreat,
                'OLD_RETREAT': old_retreat,
            }
            if len(new_retreat.pictures.all()):
                merge_data['RETREAT_PICTURE'] = "{0}{1}".format(
                    settings.MEDIA_URL,
                    new_retreat.pictures.first().picture.url)

            plain_msg = render_to_string("exchange.txt", merge_data)
            msg_html = render_to_string("exchange.html", merge_data)

            try:
                response_send_mail = send_mail(
                    "Confirmation d'échange",
                    plain_msg,
                    settings.DEFAULT_FROM_EMAIL,
                    [user.email],
                    html_message=msg_html,
                )
                EmailLog.add(user.email, 'exchange', response_send_mail)
            except Exception as err:
                additional_data = {
                    'title': "Confirmation d'échange",
                    'default_from': settings.DEFAULT_FROM_EMAIL,
                    'user_email': user.email,
                    'merge_data': merge_data,
                    'template': 'exchange'
                }
                Log.error(source='SENDING_BLUE_TEMPLATE',
                          message=err,
                          additional_data=json.dumps(additional_data))
                raise

            send_retreat_confirmation_email(instance.user, new_retreat)

        return Reservation.objects.get(id=instance_pk)
Exemplo n.º 33
0
 def get_queryset(self):
     return Order.filter_order_based_on_query(self.request,
                                              user=self.request.user)
Exemplo n.º 34
0
def completeOrder(request):
    request.session.set_expiry(0)
    cart = request.session['cart']
    ctx = {'cart': cart}
    order = Order()
    order.first_name = request.POST['first_name']
    order.last_name = request.POST['last_name']
    order.address = request.POST['address']
    order.city = request.POST['city']
    order.payment_method = request.POST['payment']
    order.payment_data = request.POST['payment_data']
    order.items = genItemsList(cart)
    order.fulfilled = False
    order.save()
    request.session['cart'] = []
    return render(request, 'store/complete_order.html', ctx)
Exemplo n.º 35
0
def braintree(request):
    if request.method == 'POST':
        import braintree
        braintree.Configuration.configure(braintree.Environment.Sandbox,
            merchant_id="twhx5c5qb42dvm9d",
            public_key="8bfdmym6wk589c2z",
            private_key="d08f06ddb29099de67f02f51519793da")
        # setup transaction using customer info    
        result = braintree.Transaction.sale({
            "amount": "%0.2f" % (request.session['to_pay']), # TODO: plus shipping?
            "credit_card": {
                "number": request.POST['number'],
                "cvv": request.POST['cvv'],
                "expiration_month": request.POST['month'],
                "expiration_year": request.POST['year']
            },
            "options": {
                "submit_for_settlement": True
            }
        })

        # Check stock
        for item in request.session['cart']:
                product = Product.objects.get(slug=item)
                if product.stock < request.session['cart'][item]: # IMPORTANT - payment fails if stock has already been sold
                    message = 'Error taking payment: Stock Error'
                    orderid = 'FAIL'
                    context = {'message':message, 'orderid':orderid}
                    return render(request, 'store/payment_result.html', context)
          
        if result.is_success: # Payment taken here
            # Create order in db
            order = Order(
                name = request.POST['name'], 
                email = request.POST['email'],
                address1 = request.POST['address1'], 
                address2 = request.POST['address2'], 
                address3 = request.POST['address3'], 
                address4 = request.POST['address4'],
                postcode = request.POST['postcode'],
                total_payment = request.session['to_pay'],
            )
            order.save()

            # Create orderdetails for every item
            for item in request.session['cart']:
                current_item = Product.objects.get(slug=item)
                orderdetail = OrderDetail(
                    order = order,
                    product = current_item,
                    quantity = request.session['cart'][item],
                    price_per_unit = current_item.price,
                )
                orderdetail.save()
            
            # reduce stock levels
            for item in request.session['cart']:
                product = Product.objects.get(slug=item)
                product.stock -= request.session['cart'][item]
                product.save()
            
            # clear cart, to_pay and count
            request.session['cart'] = {}
            request.session['to_pay'] = 0
            request.session['count'] = 0
            # TODO: Email customer order number and details here

            # return the payment result
            message = 'Payment taken successfully!'
            orderid = 'Order ID: ' + str(order.id)
        else:
            message = 'Error taking payment'
            orderid = 'FAIL'
        context = {'message':message, 'orderid':orderid}
        return render(request, 'store/payment_result.html', context)

    # initial load of page
    else:
        to_pay = request.session['to_pay']
        form = PaymentForm()
        context = {'form':form, 'to_pay':to_pay, 'count':request.session.get('count',0)}
        return render(request, 'store/payment.html', context)
Exemplo n.º 36
0
    def save(self, cart):
        first_name = self.cleaned_data.get('first_name')
        last_name = self.cleaned_data.get('last_name')
        street = self.cleaned_data.get('street')
        house_number = self.cleaned_data.get('house_number')
        flat_number = self.cleaned_data.get('flat_number')
        zip_code = self.cleaned_data.get('zip_code')
        phone_number = self.cleaned_data.get('phone_number')
        city = self.cleaned_data.get('city')

        order = Order()
        order.first_name = first_name
        order.last_name = last_name
        order.street = street
        order.house_number = house_number
        order.flat_number = flat_number
        order.zip_code = zip_code
        order.phone_number = phone_number
        order.city = city
        order.user = self.user
        order.save()

        for item in cart:
            order_item = OrderItem()
            order_item.order = order
            order_item.product = item['product']
            order_item.price = item['price']
            order_item.quantity = item['quantity']
            order_item.save()