Пример #1
0
def clear_cart(request):
    if request.is_ajax():
        cart = Cart(request)
        cart.clear()
        return HttpResponse('cart was destroyed.')
    else:
        return HttpResponseRedirect('/')
Пример #2
0
def submit_single(request, shipping, items, final_amount, coupon_amount):
	print('submit_single:', shipping.contact)

	item = items[0]
	order = item.product
	order.shipping = shipping
	order.status = 'OR'
	order.amount = float(order.amount) - (coupon_amount / 100.0);
	order.coupon = request.POST.get('coupon_code', '')

	order.save()

	mail_order_confirmation(shipping.contact, order.meshu, order)

	# send a mail to ifttt that creates an svg in our dropbox for processing
	mail_ordered_svg(order)

	current_cart = Cart(request)
	current_cart.clear()

	return render(request, 'meshu/notification/ordered.html', {
		'view': 'paid',
		'order': order,
		'meshu': order.meshu
	})
Пример #3
0
def thankyou(request):
    context = get_common_context(request)
    
    cart = Cart(request)
    cart.clear()   
    
    return render_to_response('common/thankyou.html', context, context_instance=RequestContext(request))
Пример #4
0
def index(request):
    context = get_common_context(request)
    
    cart = Cart(request)
    cart.clear()   
    
    return render_to_response('common/default.html', context, context_instance=RequestContext(request))
Пример #5
0
def get_cart(request):

    cart = Cart(request)

    if request.user.is_authenticated():
        try:
            customer = Customer.objects.get(user=request.user)
        except:
            customer = None
    else:
        customer = None

    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=customer)
        order_form = OrderForm(request.POST)
        if form.is_valid():

            # SAVE CUSTOMER
            new_customer = form.save(commit=False)
            if request.user.is_authenticated():
                new_customer.user = request.user
            new_customer.save()

            if order_form.is_valid():

                # SAVE ORDER
                new_order = order_form.save(commit=False)
                new_order.customer = new_customer

                new_order.cust_name = new_customer.name
                new_order.cust_email = new_customer.email
                new_order.cust_phone = new_customer.phone
                new_order.cust_city = new_customer.city
                new_order.cust_postcode = new_customer.postcode
                new_order.cust_address = new_customer.address

                new_order.summary = cart.summary()
                new_order.save()
                new_order.number = new_order.get_number(new_order.id)
                new_order.save()

                # SAVE CART TO ORDER DETAIL
                for item in cart:
                    new_item = OrderDetail()
                    new_item.order = new_order
                    new_item.product = item.product
                    new_item.price = item.unit_price
                    new_item.quantity = item.quantity
                    new_item.total_price = item.total_price
                    new_item.save()
                cart.clear()

                return direct_to_template(request, 'fshop/order_thanks.html',{'object':new_order})

    else:
        form = CustomerForm(instance=customer)
        order_form = OrderForm()

    return direct_to_template(request, 'fshop/cart_detail.html', {'cart':cart, 'form':form, 'order_form':order_form})
Пример #6
0
def clear_cart(request):

    cart = Cart(request)
    try:
        cart.clear()
    except:
        pass
    return HttpResponseRedirect(reverse('cart_detail'))
Пример #7
0
def clear_cart(request):

    cart = Cart(request)
    try:
        cart.clear()
    except:
        pass
    return HttpResponseRedirect('/checkout/')
Пример #8
0
def clear_cart(request):
    cart = Cart(request)
    cart.clear()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))


#   cart = [{'item1': "g", 'item2': 2, 'item3': 100}]
# return render(request, 'cart.html', {'cart': cart})
Пример #9
0
def cart(request, clear=False, template='events/cart.html'):
    cart = CartManager(request)
    if clear:
        cart.clear()
        return redirect('home')
    context = {
        'cart' : cart,
        'STRIPE_PUBLIC_KEY' : settings.STRIPE_PUBLIC_KEY
    }
    return render_to_response(template, context,
                              context_instance=RequestContext(request))
Пример #10
0
def buy_cart(request):
    cart = Cart(request)
    url = reverse("index")
    if cart.is_empty():
        request.session['status'] = "Error: Cart empty!"
        return HttpResponseRedirect(url)

    paypal_payments = Payments(request)
    payment = paypal_payments.buy(cart)
    if payment.error:
        request.session['status'] = "Error: %s" % payment.error['details']
    else:
        request.session[
            'status'] = "Success: Cart paid with PayPal. Payment ID: %s" % payment.id
        cart.clear()
    return HttpResponseRedirect(url)
Пример #11
0
def checkout(request):
    if request.method == 'POST':
        cart = Cart(request)

        form = CheckoutForm(request.POST)
        if form.is_valid():
            try:
                if 'email' in request.POST:
                    update_email(request.user, request.POST.get('email'))

                customer = get_customer(request.user)

                customer.update_card(request.POST.get("stripeToken"))

                product = cart.items()[0].product
                customer.subscribe(product.plan)

                cart.clear()
                return redirect("order_confirmation")

            except stripe.StripeError as e:
                try:
                    error = e.args[0]
                except IndexError:
                    error = "unknown error"

                return render_to_response('godjango_cart/checkout.html', {
                        'cart': Cart(request),
                        'publishable_key': settings.STRIPE_PUBLIC_KEY,
                        'error': error
                    },
                    context_instance=RequestContext(request))
        else:
            return render_to_response('godjango_cart/checkout.html', {
                    'cart': Cart(request),
                    'publishable_key': settings.STRIPE_PUBLIC_KEY,
                    'error': "Problem with your card please try again"
                },
                context_instance=RequestContext(request))
    else:
        return render_to_response('godjango_cart/checkout.html', {
                'cart': Cart(request),
                'publishable_key': settings.STRIPE_PUBLIC_KEY
            },
            context_instance=RequestContext(request))
Пример #12
0
def buy_cart(request):
    cart = Cart(request)
    paypal_payments = Payments(request)
    payment_id = paypal_payments.buy(cart)
    if payment_id == -1:
        return render(request, 'index.html', {
            'cart': cart,
            'status': "Error Buying the Cart! Please try again!"
        })
        #url = reverse(request.META.get('HTTP_REFERER'), kwargs={'status' : "Error Buying the Cart! Please try again! Reason: "})
        #return HttpResponseRedirect(url)
        #return render(request, 'error.html')
    else:
        cart.clear()
        return render(request, 'index.html', {
            'cart': cart,
            'status': payment_id
        })
Пример #13
0
def submit_multiple(request, shipping, items, final_amount, discount_cents, coupon_cents):
	print('submit_multiple:', shipping.contact)

	discount_per = float(((discount_cents + coupon_cents) / Cart(request).count())/100.0)
	print('discount per:', discount_per)

	orders = []
	for item in items:
		order = item.product
		order.shipping = shipping
		order.status = 'OR'
		order.coupon = request.POST.get('coupon_code', '')

		# reduce the order amount by coupon / volume discounts
		order.amount = float(order.amount) - discount_per

		order.save()
		orders.append(order)

		# if there is more than one of this necklace/pendant/whatever,
		# spoof new orders of it. using this method here:
		# https://docs.djangoproject.com/en/1.4/topics/db/queries/#copying-model-instances
		if item.quantity > 1:
			for x in range(0, item.quantity-1):
				order.pk = None
				order.save()
				orders.append(order)

		# send a mail to ifttt that creates an svg in our dropbox for processing
		mail_ordered_svg(order)

	current_cart = Cart(request)
	current_cart.clear()

	mail_multiple_order_confirmation(shipping.contact, orders, final_amount)

	return render(request, 'meshu/notification/ordered_multiple.html', {
		'orders': orders,
		'view': 'paid'
	})
Пример #14
0
def orders_list(request, tmpl, action=None):
    msg_ok = msg_err = None
    if action == 'validate':
        cart = Cart(request)
        if not cart.has_gcs_ckecked():
            return HttpResponseRedirect('/resa/cart/uncheckedgcs/')
        if not cart.is_valid():
            return HttpResponseRedirect('/resa/cart/invalid/')
        elif not cart.empty():
            order = Order(user=request.user, creation_date=date.now(), donation = cart.donation)
            order.save_confirm(cart)
            cart.clear()
            cart.save(request)
            msg_ok = _(u"Order successfully confirmed")

    pending_orders = request.user.order_set.filter(payment_date__isnull=True)
    validated_orders = request.user.order_set.filter(payment_date__isnull=False)
    return tmpl, {
        'pending_orders': pending_orders,
        'validated_orders': validated_orders,
        'msg_err': msg_err, 'msg_ok': msg_ok,
        'user_obj': request.user,
        'currency': settings.CURRENCY, 'currency_alt': settings.CURRENCY_ALT,
    }
Пример #15
0
def manage_cart(request, tmpl, user_id=None, action=None, product_id=None):
    user = None
    if user_id:
        try:
            user = User.objects.get(id=user_id)
        except:
            user = None
    msg_ok = msg_err = products = cart = None
    products = None
    if user:
        cart = Cart(request, user.id)
        if request.user.is_staff:
            products = Article.objects.all().order_by('order')
        else:
            products = Article.objects.filter(enabled=True).order_by('order')
        if action == 'add':
            product_id = int(request.POST.get('cart_add'))
            if cart.add(product_id, 1):
                msg_ok = _(u"Product successfully added to cart")
            else:
                msg_err = _(u"Error while adding product to cart")
        elif action == 'del':
            if cart.delete(int(product_id)):
                msg_ok = _(u"Product successfully removed from cart")
            else:
                msg_err = _(u"Error while removing product from cart")
        elif action == 'update':
            update = True
            for k,v  in request.POST.iteritems():
                product_id = 0
                try:
                    quantity = int(v)
                except:
                    quantity = 0
                if k.startswith('product_'):
                    product_id = int(k[8:])
                    update = update and cart.update(product_id, quantity)
            if update:
                msg_ok = _(u"Product(s) successfully updated")
            else:
                msg_err = _(u"Error while updating product(s)")
        elif action == 'validate':
            valid = cart.is_valid()
            if not valid and request.user.is_staff:
                valid = request.POST.get('force') == '1'
            if not valid:
                msg_err = _(u"Unable to confirm this order, one (or more) product(s) in the cart exceed the available quantity")
            else:
                order = Order(user=user, creation_date=date.now())
                order.save_confirm(cart)
                cart.clear()
                msg_ok = _(u"Order successfully confirmed")
        cart.save(request)
    return tmpl, {
        'user_obj': user,
        'products': products,
        'cart': cart,
        'msg_err': msg_err, 'msg_ok': msg_ok,
        'is_admin': request.user.is_staff,
        'currency': settings.CURRENCY, 'currency_alt': settings.CURRENCY_ALT,
    }
Пример #16
0
def productClear(request):
    cart = Cart(request)
    cart.clear()
    return redirect(pedidos)
Пример #17
0
def cart_empty(request):
	current_cart = Cart(request)
	current_cart.clear()

	return HttpResponseRedirect("/cart/view")
Пример #18
0
def clear_cart(request):
    kw=get_kwrgs(request)
    cart = Cart(request)
    cart.clear()
    return render(request, 'shop/cart.html', kw)
Пример #19
0
def clear_cart(request):
    cart=Cart(request)
    cart.clear()
    return get_cart(request)
Пример #20
0
def get_cart(request, product_id, location_form_class=LocationForm):
    """Clear shopping cart and add new book_copy with product_id to it."""
    
    to_location = get_location(request.session)
    # set location form if no location is detected
    if request.method == "POST":
        location_form = location_form_class(request.POST)
        if location_form.is_valid():
            location_form.save(request)
            return HttpResponseRedirect(request.path)
    elif to_location:
        location_form = location_form_class(initial={'location': to_location.id})
    else:
        location_form = location_form_class()
    
    # get and clear cart, if not clear
    cart_errors = []
    cart = Cart(request)
    cart.clear()
    
    book_copy = Book_Copy.objects.get(pk=product_id)
    try:
        cart.add(product=book_copy, unit_price=str(book_copy.price), quantity=1)
    except ItemInAnotherCart:
        cart_errors.append("Ouch! Someone beat you to this book. Try again in a few minutes; perhaps they won't buy it, afterall.")
    
    from_location = book_copy.owner.profile.postal_code.location
    
    # Get shipping price if we already calculated it for the item
    #    to ship from the specified location to it's destination
    shipping = None
    try:
        shipping = Shipping.objects.get(object_id=book_copy.id,
                                        from_location=from_location,
                                        to_location=to_location)
    except Shipping.DoesNotExist:
        if to_location:
            shipping = Shipping(item=book_copy,
                                from_location=from_location,
                                to_location=to_location)
            shipping.save()
    
    if shipping:
        try:    
            cart.add(shipping, str(shipping.price), 1)
        except ItemInAnotherCart:
            pass
    
    # do paypal form after all the items have been added
    current_site = Site.objects.get_current()
    
    form = None
    if not cart_errors and not shipping:
        cart_errors.append("Please specify your city at the top of the page, so we can calculate your shipping costs.")
    elif not cart_errors and shipping:
        paypal_dict = {
            "cmd": "_cart",
            "currency_code":"CAD",
            "tax":"0.00",
            "amount_1": book_copy.price,
            "shipping_1": shipping.price,
            "no_note": "0",
            "no_shipping": "2",
            "upload": 1,
            "item_number_1": book_copy.id,
            #truncate to 127 chars, papal limit 
            "item_name_1": book_copy.book.title[:126],
            "quantity_1": 1,
            "custom": book_copy.id,
            "return_url": current_site.domain + reverse('paypal_success'),
            "notify_url": current_site.domain + reverse('paypal-ipn'), #defined by paypal module
            "cancel_return": current_site.domain + reverse('paypal_cancel')               
        } 

        form = PayPalPaymentsForm(initial=paypal_dict)    
    
    extra_context = {'form': form,
                    'location_form': location_form,
                    'location': to_location,
                    'book_copy': book_copy,
                    'cart_errors': cart_errors}
    context = RequestContext(request, dict(cart=Cart(request)))
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response('cart/checkout.html', context)
Пример #21
0
def clear_cart(request):
    cart = Cart(request)
    cart.clear()
    request.session['status'] = "Cart cleared!"
    url = reverse("index")
    return HttpResponseRedirect(url)
Пример #22
0
def checkout(request):
    # import pdb; pdb.set_trace()
    cart=Cart(request)
    if cart.count() == 0:
        return HttpResponseRedirect('/my-cart')

    profile = Profile.objects.get(user__username=request.user)
    form = DeliveryAddress(request.POST or None, instance=profile)
    delivery_form = DeliveryServiceForm(request.POST or None)
    tot_weight = request.session['total_weight']

    if form.is_valid() and delivery_form.is_valid():        
        delivery_cost = delivery_form.cleaned_data['service']
        tot_vat = request.POST.get('tot_vat')
        # import pdb; pdb.set_trace()
        # order data
        order = Order()
        order.user = request.user
        order.amount = float(cart.summary()) + float(delivery_cost.cost) + float(tot_vat)
        order.vat = float(tot_vat)
        order.status = 'NEW'
        order.order_notes = request.POST.get('notes')
        order.save()
        # order detail data
        for ca in cart:
            orderdetail = OrderDetail()
            orderdetail.order = order
            orderdetail.product = ca.product
            orderdetail.weight = ca.product.weight
            orderdetail.surcharge = ca.product.surcharge
            orderdetail.price = ca.unit_price
            orderdetail.qty = ca.quantity
            orderdetail.amount = ca.total_price
            orderdetail.save()
        # order delivery data
        orderdelivery = OrderDelivery ()
        orderdelivery.order = order
        orderdelivery.first_name = form.cleaned_data['first_name']
        orderdelivery.last_name = form.cleaned_data['last_name']
        orderdelivery.business_name = form.cleaned_data['business_name']
        orderdelivery.address_line1 = form.cleaned_data['address_line1']
        orderdelivery.address_line2 = form.cleaned_data['address_line2']
        orderdelivery.city = form.cleaned_data['city']
        orderdelivery.state = form.cleaned_data['state']
        orderdelivery.postcode = form.cleaned_data['postcode']
        orderdelivery.country = form.cleaned_data['country']
        orderdelivery.telephone = form.cleaned_data['telephone']
        orderdelivery.service = delivery_cost.title
        orderdelivery.cost = delivery_cost.cost
        orderdelivery.weight = tot_weight
        orderdelivery.save()
        cart.clear()
        messages.success(request, "Your order was complete.")
        return HttpResponseRedirect('/orderreview/'+ order.order_no)

    try:        
        check_band = PostageCountry.objects.get(country=profile.country)        
        band = check_band.band        
        request.session['vat'] = check_band.vat
    except:
        band = ''    
        
    delivery_form.fields['service'] = forms.ModelChoiceField(required=True, queryset=PostageRate.objects.all().filter(band=band,active=True,weight_start__lte=tot_weight,weight_to__gte=tot_weight), widget=forms.Select(attrs={'class': 'form-control'}))

    data = {'form':form,'delivery_form':delivery_form}
    return render_to_response('order/checkout.html', data, context_instance=RequestContext(request, processors=[custom_proc]))
Пример #23
0
def get_cart(request, product_id, location_form_class=LocationForm):
    """Clear shopping cart and add new book_copy with product_id to it."""

    to_location = get_location(request.session)
    # set location form if no location is detected
    if request.method == "POST":
        location_form = location_form_class(request.POST)
        if location_form.is_valid():
            location_form.save(request)
            return HttpResponseRedirect(request.path)
    elif to_location:
        location_form = location_form_class(
            initial={'location': to_location.id})
    else:
        location_form = location_form_class()

    # get and clear cart, if not clear
    cart_errors = []
    cart = Cart(request)
    cart.clear()

    book_copy = Book_Copy.objects.get(pk=product_id)
    try:
        cart.add(product=book_copy,
                 unit_price=str(book_copy.price),
                 quantity=1)
    except ItemInAnotherCart:
        cart_errors.append(
            "Ouch! Someone beat you to this book. Try again in a few minutes; perhaps they won't buy it, afterall."
        )

    from_location = book_copy.owner.profile.postal_code.location

    # Get shipping price if we already calculated it for the item
    #    to ship from the specified location to it's destination
    shipping = None
    try:
        shipping = Shipping.objects.get(object_id=book_copy.id,
                                        from_location=from_location,
                                        to_location=to_location)
    except Shipping.DoesNotExist:
        if to_location:
            shipping = Shipping(item=book_copy,
                                from_location=from_location,
                                to_location=to_location)
            shipping.save()

    if shipping:
        try:
            cart.add(shipping, str(shipping.price), 1)
        except ItemInAnotherCart:
            pass

    # do paypal form after all the items have been added
    current_site = Site.objects.get_current()

    form = None
    if not cart_errors and not shipping:
        cart_errors.append(
            "Please specify your city at the top of the page, so we can calculate your shipping costs."
        )
    elif not cart_errors and shipping:
        paypal_dict = {
            "cmd": "_cart",
            "currency_code": "CAD",
            "tax": "0.00",
            "amount_1": book_copy.price,
            "shipping_1": shipping.price,
            "no_note": "0",
            "no_shipping": "2",
            "upload": 1,
            "item_number_1": book_copy.id,
            #truncate to 127 chars, papal limit
            "item_name_1": book_copy.book.title[:126],
            "quantity_1": 1,
            "custom": book_copy.id,
            "return_url": current_site.domain + reverse('paypal_success'),
            "notify_url": current_site.domain +
            reverse('paypal-ipn'),  #defined by paypal module
            "cancel_return": current_site.domain + reverse('paypal_cancel')
        }

        form = PayPalPaymentsForm(initial=paypal_dict)

    extra_context = {
        'form': form,
        'location_form': location_form,
        'location': to_location,
        'book_copy': book_copy,
        'cart_errors': cart_errors
    }
    context = RequestContext(request, dict(cart=Cart(request)))
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response('cart/checkout.html', context)