示例#1
0
def voucher_check(request):
    try:
        request.session['voucher']
        return JsonResponse({'success': False})
    except KeyError:
        cart = get_cart(request)
        code = request.POST.get('voucher_code', None)

        if code:
            voucher = Voucher.objects.get(code=code)
            value = voucher.get_value()
            if voucher.active:
                if voucher.percentage:
                    margin = int(cart.net_total * value)
                    cart.discount_total += margin
                    cart.net_total -= margin
                else:
                    cart.net_total -= value
                    cart.discount_total += value
            cart.save()
            request.session['cart'] = cart
            request.session['voucher'] = voucher
            return JsonResponse({
                'success': True, 
                'gross': cart.gross_total, 
                'discount': cart.discount_total, 
                'net': cart.net_total, 
                'voucher_name': voucher.name,
                'voucher_value': voucher.get_display_value(),
            })
        return JsonResponse({'success': False})
示例#2
0
def voucher_reset(request):
    try:
        cart = get_cart(request)
        voucher = request.session['voucher']
        value = voucher.get_value()
        if voucher.percentage:
            total = int(cart.net_total / float(1 - value))
            cart.discount_total -= int(total * float(value))
            cart.net_total = total
        else:
            cart.net_total += value
            cart.discount_total -= value

        cart.save()
        request.session['cart'] = cart
        del request.session['voucher']

        return JsonResponse({
            'success': True,
            'gross': cart.gross_total, 
            'discount': cart.discount_total,
            'net': cart.net_total,
        })
    except KeyError:
        return JsonResponse({'success': False })
示例#3
0
def product_page(request, product_id):
    # get cart data
    from cart.views import get_cart
    cart = get_cart(request)
    urls_cart = request.build_absolute_uri('/api/cart/' + str(cart.id) + '/')
    urls_product = request.build_absolute_uri('/api/products/' +
                                              str(product_id) + '/')

    if request.user.is_authenticated:
        username = request.user.get_username()
    else:
        username = '******'

    #find product and give it to template
    main_product = Product.objects.get(id=product_id)
    main_image = ProductImage.find_main_product_image(product_id)
    other_images = ProductImage.find_product_images(product_id)

    return render(
        request, 'products/product.html', {
            'product': main_product,
            'main_image': main_image,
            'other_images': other_images,
            'cart': cart,
            'urls_cart': urls_cart,
            'urls_product': urls_product,
            'username': username
        })
示例#4
0
def context_proc(request):
    cart = get_cart(request)
    items_count = 0
    for item in cart.item_set.all():
        items_count += item.quantity

    return {'cart_items_count' : items_count}
示例#5
0
def cart(request):
    cart = get_cart(request)
    cart_total_price = sum(Decimal(item['price']) * item['quantity'] 
                            for item in cart.values())

    return {
        'cart_total_price': cart_total_price
    }
示例#6
0
def paypal(request):
    try:
        order = request.session['order']
    except KeyError:
        raise Http404
    if order.user != request.user:
        raise Http404
    cart = get_cart(request)
    items = CartItem.objects.filter(cart=cart)
    
    return render(request, 'order/paypal.html', {'order': order, 'items': items, 'debug': settings.DEBUG})
示例#7
0
def index(request):
    cart = get_cart(request)
    items = CartItem.objects.filter(cart=cart)
    if request.method == 'POST':
        voucher_code = request.POST.get('voucher_code', None)
        form = OrderForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            order.discount_total = cart.discount_total
            order.gross_total = cart.gross_total
            order.net_total = cart.net_total
            order.user = request.user
            order.voucher_code = voucher_code
            order.order_id = ''
            order.billing_post_code = request.POST['billing_zip']
            order.billing_county = request.POST['billing_county']
            order.billing_district = request.POST['billing_district']
            order.shipping_post_code = request.POST['shipping_zip']
            order.shipping_county = request.POST['shipping_county']
            order.shipping_district = request.POST['shipping_district']
            order.save()
            request.session.save()
            request.session['order'] = order
            
            if order.payment_method == 0: 
                return redirect('order-paypal')
            else:
                return redirect('order-success')
    else:
        profile = request.user.profile
        form = OrderForm(initial={
                'billing_recipient': request.user.get_name(),
                'billing_phone' : profile.phone,
                'billing_address': profile.address,
                'billing_country': profile.country,
                'payment_method': 0,
                'reciept_type': 0,
                'dispatch_time': 0,
            }
        )
    try:
        voucher = request.session['voucher']
    except KeyError:
        voucher = None

    return render(request, 'order/index.html', {'cart': cart, 'form': form, 'items': items, 'voucher': voucher})
示例#8
0
def order_create(request):
    cart = get_cart(request)
    cart_qty = sum(item['quantity'] for item in cart.values())
    transport_cost = 500

    if request.method == 'POST':
        order_form = OrderCreateForm(request.POST)
        if order_form.is_valid():
            cf = order_form.cleaned_data
            transport = cf['transport']

            if transport == 'Самовывоз':
                transport_cost = 0
            
            order = order_form.save(commit=False)
            order.transport_cost = Decimal(transport_cost)
            order.save()

            product_ids = cart.keys()
            products = Product.objects.filter(id__in=product_ids)

            for product in products:
                cart_item = cart[str(product.id)]
                OrderItem.objects.create(
                    order=order,
                    product=product,
                    price=cart_item['price'],
                    quantity=cart_item['quantity']
                )
            cart_clear(request)
            # This method send workers task to celery
            order_created.delay(order.id)

            return render(
                request,
                'order_created.html',
                {'order': order}
            )
    else:
        order_form = OrderCreateForm()
    return render(request,
                  'order_create.html',
                  {'cart': cart,
                   'order_form': order_form,
                   'transport_cost': transport_cost})
示例#9
0
def get_cereal_by_id(request, id):
    """ This function renders the cereal details page of a clicked cereal on the catalog."""
    if request.method == 'POST':
        if request.POST.get('quantity') == '':
            quantity = 1
        else:
            quantity = request.POST.get('quantity', default=1)

        if request.POST['buyproduct'] == 'Buy now':
            return redirect('buy-single-item', cereal_id=id, quantity=quantity)
        else:
            return redirect('add-to-cart', cereal_id=id, quantity=quantity)
    context = {'cereal': get_object_or_404(Cereal, pk=id)}
    if request.user.is_authenticated:
        cart_json = get_cart(request)
        cart_obj = json.loads(cart_json.content)
        context['data'] = cart_obj['data']
    return render(request, 'cereal/cereal_details.html', context)
示例#10
0
def index(request):
    products = Product.objects.all
    cart = get_cart(request)

    if 'product_id' in request.POST:
        id = request.POST['product_id']
        product = Product.objects.get(id=id)

        try:
            quantity = int(request.POST['select_quantity'])
        except:
            quantity = 1

        add_to_cart(request, product=product, quantity=quantity, unit_price=product.price)
        product_name = product.name

    else:
        pass

    return render_to_response('index.html', RequestContext(request, locals()));
示例#11
0
def get_shipping(request, country_id):
    country_id = int(country_id)
    if country_id > 0:
        if request.is_ajax():
            return JsonResponse({'success': True, 'shipping': settings.SHIPPING_OVERSEAS_COST})
        return settings.SHIPPING_OVERSEAS_COST
    else:
        cart = get_cart(request)
        if settings.SHIPPING_FREE_ITEM_COUNT:
            if cart.items.count() > settings.SHIPPING_FREE_ITEM_COUNT:
                if request.is_ajax():
                    return JsonResponse({'success': True, 'shipping': 0})
                return 0
        if settings.SHIPPING_FREE_MINIMUM_PURCHASE:
            if cart.net_total > settings.SHIPPING_FREE_MINIMUM_PURCHASE:
                if request.is_ajax():
                    return JsonResponse({'success': True, 'shipping': 0})
                return 0
        if request.is_ajax():
            return JsonResponse({'success': True, 'shipping': settings.SHIPPING_DEFAULT_COST})
        return settings.SHIPPING_DEFAULT_COST
示例#12
0
def success(request):
    from order.utils import generate_order_pdf
    from django.template.loader import render_to_string
    from django.core import mail
    from django.core.mail import EmailMultiAlternatives, EmailMessage
    from django.contrib.auth.models import Group
    try:
        order = request.session['order']
    except KeyError:
        raise Http404
    if order.user != request.user:
        raise Http404

    cart = get_cart(request)
    cart = archive_cart(cart)
    order.cart = cart.id
    order.save()
    del request.session['cart']
    voucher = request.session['voucher'] if 'voucher' in request.session else None

    items = ArchivedCartItem.objects.filter(archived_cart=cart)
    for item in items:
        order_item = OrderItem()
        order_item.order = order
        order_item.product = item.product
        order_item.quantity = item.quantity
        order_item.discount_total = item.discount_total
        order_item.gross_total = item.gross_total
        order_item.net_total = item.net_total
        order_item.save()
        #Update sold figure
        item.product.sold += item.quantity
        item.product.save()

    order.status = 1
    order.save()

    pdf = generate_order_pdf(request.get_host(), order, voucher)

    subject = _('EMPOR Order Confirmation')
    html_content = render_to_string('order/email.html', {
        'order': order, 
        'items': items,
        'voucher': voucher,
        'STATIC_URL': settings.STATIC_URL, 
        'host': request.get_host()
    })
    text_content = render_to_string('order/email.txt', {
        'order': order,
        'voucher': voucher,
        'items': items,
        'host': request.get_host()
    })

    connection = mail.get_connection()
    connection.open()

    message = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL, [order.user.email])
    message.attach_alternative(html_content, 'text/html')
    filename = order.order_id
    message.attach(filename.encode('utf-8'), pdf, 'application/pdf')

    group = Group.objects.get(name='Service').user_set.only('email')
    subject = 'EMPOR - 新訂單 %s' % order.order_id
    group_email = [ user.email for user in group ]
    notification = EmailMessage(subject, html_content, settings.DEFAULT_FROM_EMAIL, group_email)
    notification.content_subtype = 'html'
    
    connection.send_messages([message, notification])
    connection.close()

    if 'voucher' in request.session:
        del request.session['voucher']
    return redirect('order-thankyou')
示例#13
0
def order_create(request):
    cart = get_cart(request)
    cart_qty = sum(item['quantity'] for item in cart.values())
    transport_cost = round((3.99 + (cart_qty // 10) * 1.5), 2)

    if request.method == 'POST':
        order_form = OrderCreateForm(request.POST)
        if order_form.is_valid():
            cf = order_form.cleaned_data
            transport = cf['transport']

            if transport == 'Recipient pickup':
                transport_cost = 0

            order = order_form.save(commit=False)
            if request.user.is_authenticated:
                order.user = request.user
            order.transport_cost = Decimal(transport_cost)
            order.save()

            product_ids = cart.keys()
            products = Product.objects.filter(id__in=product_ids)

            for product in products:
                cart_item = cart[str(product.id)]
                OrderItem.objects.create(order=order,
                                         product=product,
                                         price=cart_item['price'],
                                         quantity=cart_item['quantity'])

            customer = stripe.Customer.create(
                email=cf['email'], source=request.POST['stripeToken'])

            charge = stripe.Charge.create(customer=customer,
                                          amount=int(order.get_total_cost() *
                                                     100),
                                          currency='usd',
                                          description=order)

            cart_clear(request)

            order_created.delay(order.id)

            return render(request, 'order_created.html', {'order': order})

    else:
        order_form = OrderCreateForm()
        if request.user.is_authenticated:
            initial_data = {
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email,
                'telephone': request.user.profile.phone_number,
                'address': request.user.profile.address,
                'postal_code': request.user.profile.postal_code,
                'city': request.user.profile.city,
                'country': request.user.profile.country,
            }
            order_form = OrderCreateForm(initial=initial_data)

    return render(request, 'order_create.html', {
        'cart': cart,
        'order_form': order_form,
        'transport_cost': transport_cost
    })
示例#14
0
def cereal_catalog(request):
    """Testing a different approach"""
    if 'search_filter' in request.GET:
        search_filter = request.GET['search_filter']

        # If an authorized user is searching, his search query is saved to the database
        if search_filter != "":
            if request.user.is_authenticated:
                new_search_entry = Search(search_query=search_filter,
                                          search_date=datetime.now(),
                                          user=request.user)
                new_search_entry.save()

        order_by = request.GET['order_by']

        filter_str = request.GET['filters']
        if filter_str == '':
            filters = CerealCategory.objects.all()
        else:
            filters = filter_str.split(',')

        cereals = cereal_objects_to_json(
            Cereal.objects.filter(
                category__in=filters,
                name__icontains=search_filter).order_by(order_by))

        # Makes sure there are no duplicates, this could probably be done in the query
        unique_cereals = []
        for cereal in cereals:
            if cereal not in unique_cereals:
                unique_cereals.append(cereal)
        cereals = unique_cereals

        return JsonResponse({'data': cereals})

    if 'search_history' in request.GET:
        searches = [{
            'search_query': search.search_query
        } for search in Search.objects.filter(user=request.user)]
        searches.reverse()
        return JsonResponse({'data': searches[:6]})

    # What is returned when there is no query in the url
    # If the user is authenticated, his search history is returned along with the cereals and categories
    context = {
        'cereals': Cereal.objects.all().order_by('name'),
        'categories': CerealCategory.objects.all(),
    }

    if request.user.is_authenticated:
        cart_json = get_cart(request)
        cart_obj = json.loads(cart_json.content)
        context['data'] = cart_obj['data']
        searches = [{
            'search_query': y.search_query
        } for y in Search.objects.filter(user=request.user)]
        searches.reverse()
        context['searches'] = searches[:6]
        return render(request, 'cereal/index.html', context)
    # If user is not authenticated, only categories and cereals are returned
    else:
        return render(request, 'cereal/index.html', context)