Ejemplo n.º 1
0
def empty_cart(request):
	cart = Cart(request.session)
	cart.clear()
	html = new_cart_html(request,1)
	cart_contents_qty = cart_contents_empty(request)
	payload = update_cart_status_and_prepare_payload(request, html, cart_contents_qty)
	return HttpResponse(json.dumps(payload), content_type="application/json")
Ejemplo n.º 2
0
def charge(request):
    cart = Cart(request.session)
    if cart.unique_count > 0:
        if request.method == "POST":
            form = SalePaymentForm(request.POST or None)
            if form.is_valid(): # charges the card
                template = get_template('tinbox/order-response-email.html')
                context = Context({'cart': cart, 'total': cart.total, 'shipping_cost': form.cleaned_data.get("shipping"), 'name' : form.cleaned_data.get("name") })
                content = template.render(context)
                cart.clear()
                form_email = form.cleaned_data.get("email")
                form_name = form.cleaned_data.get("name")
                subject = 'Tinbox Solutions - Order Successfully Processed'
                from_email = settings.EMAIL_HOST_USER
                to_email = [form_email]
                msg = EmailMultiAlternatives(subject, "", from_email, to=to_email)
                msg.attach_alternative(content, "text/html")
                msg.send()
                return HttpResponseRedirect('/shopping/thank-you')
            else:
                t = form.determineShippingFormField(1, cart.total)
                return render_to_response("tinbox/charge.html", RequestContext( request, {'form': form, 'turnaround_cost' : t.turnaround_cost, 'turnaround' : t.turnaround} ) )
        else:
            form = SalePaymentForm()
            t = form.determineShippingFormField(1, cart.total)
        return render_to_response("tinbox/charge.html", RequestContext( request, {'form': form, 'turnaround_cost' : t.turnaround_cost, 'turnaround' : t.turnaround} ) )

    else:
        return render(request, 'tinbox/show-cart.html', {"empty": True})
Ejemplo n.º 3
0
def pago(request):
	if request.method == "POST":
		cart = Cart(request.session)
		if not cart.is_empty:
			#
			#	Guardo el pedido
			# ===========================
			
			# creo un pedido con los datos del cliente y el restaurante
			restaurante =cart.items[0].product.restaurante
			cliente = Cliente.objects.get(user=request.user) #falta el cliente
			pedido = Pedido (restaurante=restaurante, cliente=cliente)
			pedido.save()
			
			#aado platos al pedido
			for item in cart.items:
				plato = item.product
				Detalle_pedido(plato=plato, pedido=pedido, cantidad=item.quantity).save()
						
			

			if request.POST.get('pago') == "Paypal":
				return paypal_create(request)
			elif request.POST.get('pago') == "Efectivo":
				cart.clear() #Se vacia el carrito
				return HttpResponseRedirect(reverse('pago_exitoso'))
Ejemplo n.º 4
0
def add_single(request):
	cart = Cart(request.session)
	plato = Plato.objects.get(id=request.GET.get('product_id'))

	if cart.products:
		if plato.restaurante.id != cart.products[0].restaurante.id:
			cart.clear()		
	cart.add(plato, price=plato.precio)
	return platilla_cesta(request);
Ejemplo n.º 5
0
def checkout_page(request):
    errors = []
    cart = Cart(request.session)
    freight_only = any([item.product.product.freight_only for item in cart.items])
    cost_total = cart.total
    if cart.is_empty:
        return redirect(reverse('store'))
    else:
        if request.POST:
            cart_list = [v for k, v in cart.cart_serializable.items()]
            cal_price = reduce(lambda x, y: x + y, [i['quantity'] * int(i['price']) for i in cart_list])
            delivery = request.POST.get('delivery')
            try:
                shopper = PersonalInfo.objects.get(id=request.user.personalinfo.id)
                if cart.total == cal_price and delivery is not None:
                    order = PurchaseOrder.objects.create(
                        number=0,
                        buyer=shopper,
                        order_time=datetime.now(),
                        freight=0 if cart.total > 1500 else
                        60 if delivery.isdigit() else 90,
                        ship_method='FML' if delivery.isdigit() else 'KTJ',
                        address=delivery,
                        total=cart.total,
                        buyer_notes=request.POST.get('shopper_notes'),
                        order_notes=cart_list
                    )
                    order.number = float(datetime.now().strftime('%y%m%d%H%M%S')) + float(order.id)
                    order.total = order.total + order.freight

                    # 更改為預購模式!
                    for d in cart_list:
                        item = get_object_or_404(Item, id=d['product_pk'])
                        order.sold_goods.add(item)
                        item.pre_order += d['quantity']
                        # print ('id={} / 存貨={} / 售貨={} / 總售貨={}'.format(
                        #     item.id, item.stock,
                        #     item.sold, item.total_sold
                        # ))
                        item.save()
                    order.save()
                    cart.clear()
                    return HttpResponseRedirect(reverse('checkout:orderinfo'))
                else:
                    errors.append('資料有誤 或 尚未填寫,請重新整理再次一次')
            except Exception as e:
                print ('%s (%s)' % (e, type(e)))
    context = {
        'title': '結帳清單',
        'errors': errors,
        'cost_total': cost_total,
        'freight_only': freight_only,
    }
    return render(request, 'checkout/checkout-page.html', context)
Ejemplo n.º 6
0
def clear_cart(request):
    if request.is_ajax():
        cart = Cart(request.session)
        cart.clear()
        return render_to_response('mcat_order/cart.html',
                                   context_instance=RequestContext(request),
                                   content_type="application/xhtml+xml"
                                   )
    else:
        if settings.DEBUG:
            print("Not ajax request")
        raise Http404
Ejemplo n.º 7
0
 def dispatch(self, request, *args, **kwargs):
     self.customer = get_object_or_404(Customer, user=self.request.user)
     #~ create the order
     cart = Cart(request.session)
     if cart.count == 0:
         messages.warning(self.request, _(u'The cart is empty: order cancelled'))
         return super(PostOrderView, self).dispatch(request, *args, **kwargs)
     order = Order.objects.create(customer=self.customer, total=cart.total)
     for item in cart.items:
         #~ get the product
         OrderedProduct.objects.create(product=item.product, order=order, quantity=item.quantity, price_per_unit=item.product.price)
     
     cart.clear()
     return super(PostOrderView, self).dispatch(request, *args, **kwargs)
def paypal_return(request):

    # Get cart session and create vars
    cart = Cart(request.session)
    cartlist = cart.cart_serializable
    paypal = cart.paypal_form.initial

    # Find item and quantity ordered in nested dictionaries and save to orders db
    for item, v in cartlist.iteritems():
        if 'quantity' in v:
            order_entry = Order(user=request.user, invoice=paypal['invoice'], items=int(item), quantities=v['quantity'])
            order_entry.save()

    # Clear cart after making order
    cart.clear()

    return render(request, 'paypal/paypal_return.html')
Ejemplo n.º 9
0
def confirmar_pedido(request):
    if request.method == 'POST':
        # UF
        uf = Uf.objects.get(sigla=request.POST.get('uf'))
        # Cidade
        cidade = uf.cidade_set.get(nome=request.POST.get('cidade'))
        # Endereço
        endereco = Endereco()
        endereco.logradouro = request.POST.get('logradouro')
        endereco.complemento = request.POST.get('complemento')
        endereco.bairro = request.POST.get('bairro')
        endereco.cep = request.POST.get('cep')
        endereco.cidade = cidade;
        endereco.save()
        # Cliente
        cliente = Cliente()
        cliente.endereco = endereco
        cliente.nome = request.POST.get('nome')
        cliente.telefone = request.POST.get('telefone')
        cliente.email = request.POST.get('email')
        cliente.save()
        # Pedido
        pedido = Pedido()
        pedido.cliente = cliente
        # Carrinho de compras
        carrinho = Cart(request.session)
        pedido.valor_total = carrinho.total
        pedido.save()
        # Item pedido
        for item in carrinho.items:
            print item
            item_pedido = ItemPedido()
            item_pedido.pedido = pedido
            item_pedido.produto = item.product
            item_pedido.quantidade = item.quantity
            item_pedido.preco_unitario = item.price
            item_pedido.preco_total = item.price * item.quantity
            item_pedido.save()
        pedido.save()
        carrinho.clear()
        template = loader.get_template('loja/efetuar-pagamento.html')
        context = RequestContext(request, {'cliente': cliente})
        return HttpResponse(template.render(context))
    else:
        return HttpResponseServerError()
Ejemplo n.º 10
0
class OrderCreate(View):
    def dispatch(self, request, *args, **kwargs):
        self.cart = Cart(request.session)
        return super(OrderCreate, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        form = OrderCreateForm()
        return render(request, 'orders/order_form.html', {
            'cart': self.cart,
            'form': form
        })

    def post(self, request, *args, **kwargs):
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            if self.cart.coupon():
                order.coupon = self.cart.coupon()
                order.discount = self.cart.coupon().discount
            order.save()

            for item in self.cart.items:
                OrderItem.objects.create(order=order,
                                         product=item.product,
                                         price=item.price,
                                         quantity=item.quantity)
                #substract from stock
                product_ = Product.objects.get(pk=item.product.id)
                if product_.stock < item.quantity:
                    messages.error(
                        request,
                        "It appears that there is no enough product of %s" %
                        product_.name)
                    messages.info(request, "Please update your cart")
                    return redirect(reverse('shop:product_list'))
                product_.stock -= item.quantity
                product_.save()

            self.cart.clear()
            request.session['order_id'] = order.id

            return redirect(reverse('payment:process'))
        else:
            return render(request, 'orders/order_form.html', {'form': form})
Ejemplo n.º 11
0
def approval(request):
    User = get_user_model()
    user = get_object_or_404(User, pk=request.user.pk)
    cart = Cart(request.session)
    order_items = []
    for item in cart.items:
        cart_item = item.product.menu_name
        cart_quantity = item.quantity
        order_items.append('{}_{}'.format(cart_item, cart_quantity))

    order_list = OrderList.objects.create(
        user=user,
        store=get_object_or_404(Store, pk=request.session['store_pk']),
        order_condition=1,
        order_location=request.COOKIES['adr'] + ' ' + request.COOKIES['dadr'],
        order_name='/'.join(order_items),  # 유저이름 + 가게이름: 의미 없는 문자열
        order_price=cart.total  # 장바구니의 총 가격
    )

    cart.clear()
    URL = 'https://kapi.kakao.com/v1/payment/approve'
    headers = {
        "Authorization":
        "KakaoAK " + "965c38ccc1d83d33c9577c0b870eb506",  # 변경불가
        "Content-type":
        "application/x-www-form-urlencoded;charset=utf-8",  # 변경불가
    }
    params = {
        "cid": "TC0ONETIME",  # 변경불가. 실제로 사용하려면 카카오와 가맹을 맺어야함. 현재 코드는 테스트용 코드
        "tid": request.session['tid'],  # 결제 요청시 세션에 저장한 tid
        "partner_order_id": request.session['order_id'],  # 주문번호
        "partner_user_id": "{}".format(user),  # 유저 아이디
        "pg_token": request.GET.get("pg_token"),  # 쿼리 스트링으로 받은 pg토큰
    }

    res = requests.post(URL, headers=headers, params=params)
    amount = res.json()['amount']['total']
    res = res.json()
    context = {
        'res': res,
        'amount': amount,
    }
    return render(request, 'kakaopay/approval.html', context)
Ejemplo n.º 12
0
def checkout(request):
    if request.method == 'POST':
        cart = Cart(request.session)
        order = Order(
            date=timezone.now(),
            customer=request.user,
            total_price=cart.total,
            city=request.POST.get('city'),
            address=request.POST.get('address'),
        )
        order.save()
        for item in cart.items:
            sub_order = SubOrder(
                product=item.product,
                quantity=item.quantity,
                order=order,
            )
            sub_order.save()
        cart.clear()
        return HttpResponse(request)
    return render(request, 'goods/checkout.html')
Ejemplo n.º 13
0
def receipt(request):
    '''
    a receipt provided to show order has been made successfully . also send the owner an sms
    '''
    cart = Cart(request.session)

    # customer = get_object_or_404(Profile, user=request.user)
    products = ', '.join(i.product.name for i in cart.items)

    message = "Dear "+ 'budaboss'.upper() +", your order "+products+" KES:"+str( cart.total ) + \
        " ,has been processed ! Kindly , authorize cashout ."

    print(message)
    # customer_number = '254'+str(customer.phone_number)
    customer_number = str(729309658)

    send_receipt(message, customer_number)

    copy = cart
    cart.clear()
    return render(request, 'auto/receipt.html', locals())
Ejemplo n.º 14
0
def order_create(request):
	cart = Cart(request.session)
	if request.method == 'POST':
		form = OrderCreateForm(request.POST)
		if form.is_valid():
			order = form.save(commit=False)
			order.placed_by_user = request.user
			order.save()
			for item in cart.items:
				OrderItem.objects.create(order=order,
											product=item.product,
											price=item.price,
											quantity=item.quantity)
				old_quantity = soap_client.service.findByIsbn(item.product.isbn).quantity
				new_quantity = old_quantity - item.quantity
				soap_client.service.updateQuantity(item.product.isbn, new_quantity)
			cart.clear()
			context={'order': order}	
			return render(request, 'orders/created.html', context)
	else:
		form = OrderCreateForm()
		return render(request, 'orders/create.html', {'cart': cart, 'form': form})	
Ejemplo n.º 15
0
 def post(self, request):
     forms = {}
     user = MyUser.objects.get(id=request.user.id)
     for key in request.POST.keys():
         forms[key] = request.POST.get(key, '')
     cart = Cart(request.session)
     o = Order(status='P',
               total=cart.total,
               address=forms['address_line_1'],
               postcode=forms['postalcode'],
               name_oncard=forms['card-name'],
               card_number=forms['card-number'],
               expire_date=forms['exp-month'],
               expire_year=forms['exp-year'],
               card_cvc=forms['cvc'],
               member_id=user)
     temp = ContentFile(json.dumps(cart.cart_serializable))
     file_name = str(o.id) + ".json"
     o.product_list.save(file_name, temp)
     o.save()
     cart.clear()
     return redirect('/member/')
Ejemplo n.º 16
0
def checkout(request):
    user_profile = UserProfile.objects.filter(user__id=request.user.id).first()
    if request.method == 'GET':
        cart = Cart(request.session)
        form = AddressForm()
        return render(
            request, 'checkout.html', {
                'form': form,
                "nav_on": True,
                "cart": cart,
                'money': user_profile.money
            })
    elif request.method == 'POST':
        form = AddressForm(request.POST)
        if form.is_valid():
            cart = Cart(request.session)

            order = Order.objects.create(
                customer_id=user_profile.id,
                address=form.cleaned_data['address'],
                total=cart.total,
                frozen=user_profile.money < cart.total)
            for item in cart.items:
                order_item = OrderItem.objects.create(order=order,
                                                      item=item.product,
                                                      quantity=item.quantity,
                                                      subtotal=item.subtotal)
            if not order.frozen:
                user_profile.update(cart.total)
                user_profile.save()
            cart.clear()
            return render(
                request, 'order_success.html', {
                    'address': order.address,
                    'order_no': order.id,
                    'frozen': order.frozen,
                    'nav_on': True
                })
Ejemplo n.º 17
0
 def get(self, request, *args, **kwargs):
     try:
         payment = Payment.objects.get(pk=kwargs['payment_id'], user=self.request.user)
     except Payment.DoesNotExist:
         raise Http404
     if payment.status == PaymentStatus.PREAUTH:
         try:
             payment.capture()
         except Exception as e:
             pass
     if payment.status != PaymentStatus.CONFIRMED:
         return redirect(reverse('checkout-payment-error', args=[payment.pk]))
     order = payment.order
     order.is_completed = True
     order.save()
     cart = Cart(self.request.session)
     cart.clear()
     try:
         order_cart = OrderCart.objects.get(session_key=request.session.session_key)
         order_cart.delete()
     except OrderCart.DoesNotExist:
         pass
     currentSite = get_current_site(request)
     subject = 'About your order at %(site)s' % {'site': currentSite.name}
     html = get_template('email/shopping/new_order.html')
     txt = get_template('email/shopping/new_order.txt')
     d = RequestContext(request, {"full_name": request.user.full_name, "order": order,
                                  "domain": currentSite.domain, "protocol": request.scheme})
     html = html.render(d)
     plaintext = txt.render(d)
     send_mail(subject, plaintext, settings.GENERIC_EMAIL_FROM, [request.user.email], fail_silently=True, html_message=html)
     mail_managers("New order at %s" % currentSite.name, "A new order with code %s has been placed. "
                                                         "Please access "
                                                         "the backend to check the order details" % order.order_code,
                   fail_silently=False, html_message=html)
     del request.session['order_in_session']
     return redirect(reverse('orders'))
     return super().get(request, *args, **kwargs)
Ejemplo n.º 18
0
    def post(self, request, *args, **kwargs):
        action = request.POST.get('action')
        delete = action == 'delete'
        clear = action == 'clear'

        cart = Cart(request.session)
        product = Product.objects.filter(
            pk=request.POST.get('product')).first()
        quantity = request.POST.get('quantity', 1)

        if delete:
            if cart.is_empty is False:
                cart.remove(product)
        elif clear:
            if cart.is_empty is False:
                cart.clear()
        else:
            cart.add(product, product.price, quantity)

        if cart.is_empty:
            return redirect('product_list')

        return super().get(request, *args, **kwargs)
Ejemplo n.º 19
0
 def get_context_data(self, **kwargs):
     '''Hooks into request lifecycle and processes the order'''
     # Get cart from the current session
     cart = Cart(self.request.session)
     if not cart.products:
         raise SuspiciousOperation("Cart is empty")
     # Create order for each author
     orders = []
     for product in cart.products:
         # Save new instance of product to the database
         product.order_copy = True
         # Backup reference to images from photoseries
         if isinstance(product, Photoseries):
             original_images = product.images.all()
         product.pk = None
         product.save()
         # Set reference to images again
         if isinstance(product, Photoseries):
             product.images.set(original_images)
             product.save()
         # Check if order for seller exists
         existing_order = [
             order for order in orders if order.seller == product.owner
         ]
         if len(existing_order) != 1:
             order = Order()
             order.buyer = auth.get_user(self.request)
             order.seller = product.owner
             orders.append(order)
             order.save()
         else:
             order = existing_order[0]
         # Put product inside order
         if isinstance(product, Photo):
             order.photos.add(product)
         else:
             order.photoseries.add(product)
         order.save()
         # 4. Versende für jede Order zwei Mails
         # 4.1 Bestätigungsmail
         buyer = User.objects.get(id=order.buyer_id)
         send_mail(
             'Order Confirmation',
             'Your order was confirmed. The owner will contact you for the payment.',
             settings.EMAIL_HOST_USER, [buyer.email],
             fail_silently=True,
             auth_user=settings.EMAIL_HOST_USER,
             auth_password=settings.EMAIL_HOST_PASSWORD)
         # 4.2 Mail mit Info für den Verkäufer
         send_mail(
             'New Order',
             'You got a new order. Please login to accept the incoming order',
             settings.EMAIL_HOST_USER, [order.seller.email],
             fail_silently=True,
             auth_user=settings.EMAIL_HOST_USER,
             auth_password=settings.EMAIL_HOST_PASSWORD)
     # Show success message to user
     context = super(checkoutView, self).get_context_data(**kwargs)
     context['orders'] = orders
     cart.clear()
     return context
Ejemplo n.º 20
0
def clear(request):
    cart = Cart(request.session)
    cart.clear()
    return render(request, 'carts/redirect.html')
Ejemplo n.º 21
0
def customer_logout(request):
    cart = Cart(request.session)
    cart.clear()
    logout(request)
    return redirect('customer:customer_login')
Ejemplo n.º 22
0
def clear(request):
	"""
	清空商品
	"""
	cart = Cart(request.session)
	cart.clear()
Ejemplo n.º 23
0
def newCart(request):
    restaurant = request.GET.get('dr')
    cart = Cart(request.session)
    request.session['restaurant_cart'] = restaurant
    cart.clear()
    return HttpResponse("New cart created")
Ejemplo n.º 24
0
def clear(request):
    cart = Cart(request.session)
    cart.clear()
    return HttpResponseRedirect('/shopping/cart')
Ejemplo n.º 25
0
def empty_cart(request):
    cart = Cart(request.session)
    cart.clear()
    return redirect("pos:cart")
Ejemplo n.º 26
0
def cart_clear(request):
    cart = Cart(request.session)
    cart.clear()
    messages.success(request, 'Cart Cleared')
    return redirect('customer:index')
Ejemplo n.º 27
0
def checkout(request):
    cart = Cart(request.session)
    total_count = cart.count
    order_list = []
    coffee_count = 0
    for item in cart.items:
        order_list.extend([item.product.title, item.quantity])
        if item.product.category == 'COFFEE':
            coffee_count += item.quantity
    if coffee_count > 4:
        if cart.total < 25000:
            total_cost = cart.total + 2500
            if request.method == 'POST':
                right_discount_code = request.POST.get("right_discount_code")
                if right_discount_code == '0752':
                    discount = 1000
                    total_cost = cart.total + 2500 - discount
                    form = PostForm(request.POST)
                    if form.is_valid():
                        checkout = form.save(commit=False)
                        checkout.total_product = order_list
                        checkout.total_price = total_cost
                        checkout.save()
                        cart.clear()
                        return redirect('email', email=checkout.email)
                    else:
                        stop_btn = True
                        ctx = {
                            'form': form,
                            'cart': cart,
                            'coffee_count': coffee_count,
                            'total_cost': total_cost,
                            'discount': discount,
                            'right_discount_code': right_discount_code,
                            'stop_btn': stop_btn,
                        }
                        return render(request, 'checkout.html', ctx)
                else:
                    total_cost = cart.total + 2500
                    form = PostForm(request.POST)
                    if form.is_valid():
                        checkout = form.save(commit=False)
                        checkout.total_product = order_list
                        checkout.total_price = total_cost
                        checkout.save()
                        cart.clear()
                        return redirect('email', email=checkout.email)
                    else:
                        ctx = {
                            'form': form,
                            'cart': cart,
                            'coffee_count': coffee_count,
                            'total_cost': total_cost,
                        }
                        return render(request, 'checkout.html', ctx)
            else:
                form = PostForm()
                ctx = {
                    'form': form,
                    'cart': cart,
                    'coffee_count': coffee_count,
                    'total_cost': total_cost,
                }
                return render(request, 'checkout.html', ctx)
        else:
            total_cost = cart.total
            if request.method == 'POST':
                right_discount_code = request.POST.get("right_discount_code")
                if right_discount_code == '0752':
                    discount = 1000
                    total_cost = cart.total - discount
                    form = PostForm(request.POST)
                    if form.is_valid():
                        checkout = form.save(commit=False)
                        checkout.total_product = order_list
                        checkout.total_price = total_cost
                        checkout.save()
                        cart.clear()
                        return redirect('email', email=checkout.email)
                    else:
                        stop_btn = True
                        ctx = {
                            'form': form,
                            'cart': cart,
                            'coffee_count': coffee_count,
                            'total_cost': total_cost,
                            'discount': discount,
                            'right_discount_code': right_discount_code,
                            'stop_btn': stop_btn,
                        }
                        return render(request, 'checkout.html', ctx)
                else:
                    form = PostForm(request.POST)
                    if form.is_valid():
                        checkout = form.save(commit=False)
                        checkout.total_product = order_list
                        checkout.total_price = total_cost
                        checkout.save()
                        cart.clear()
                        return redirect('email', email=checkout.email)
                    else:
                        ctx = {
                            'form': form,
                            'cart': cart,
                            'coffee_count': coffee_count,
                            'total_cost': total_cost,
                        }
                        return render(request, 'checkout.html', ctx)
            else:
                form = PostForm()
                ctx = {
                    'form': form,
                    'cart': cart,
                    'total_cost': total_cost,
                }
                return render(request, 'checkout.html', ctx)
    else:
        return redirect('cart')
Ejemplo n.º 28
0
def clear_cart(request):
    if request.method == 'POST':
        if request.is_ajax():
            cart = Cart(request.session)
            cart.clear()
            return JsonResponse({'message': 'cleared cart'})
Ejemplo n.º 29
0
def clear(request):
    cart = Cart(request.session)
    cart.clear()
    assert cart.count == 0
    return HttpResponse()
Ejemplo n.º 30
0
def clear(request):
    cart = Cart(request.session)
    cart.clear()
    return HttpResponse()
Ejemplo n.º 31
0
def clear(request):
    cart = Cart(request.session)
    cart.clear()
    assert cart.count == 0
    return HttpResponse()
Ejemplo n.º 32
0
def empty(request):
    cart= Cart(request.session)
    cart.clear()
    return HttpResponseRedirect('/tohfa/')
Ejemplo n.º 33
0
def clear(request):
    cart = Cart(request.session)
    product = Product.objects.all()
    cart.clear()
    return redirect('shopping-cart-show')
Ejemplo n.º 34
0
def esvaziar_carrinho(request):
    carrinho = Cart(request.session)
    carrinho.clear()
    return carrinho_ver(request)
Ejemplo n.º 35
0
def clear(request):
    cart = Cart(request.session)
    cart.clear()
    return redirect(reverse('cart:shopping-cart-show'))
Ejemplo n.º 36
0
class CartTests(TestCase):

    def setUp(self):
        engine = import_module(settings.SESSION_ENGINE)
        self.session = engine.SessionStore()
        self.session.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = self.session.session_key

        self.factory = RequestFactory()

        self.cart = Cart(self.session)

        self.deer = Product.objects.create(
            name='deer',
            price=10.0,
            custom_id=1,
        )
        self.moose = Product.objects.create(
            name='moose',
            price=20.0,
            custom_id=2,
        )
        self.ticket = Ticket.objects.create(
            name='Clint Mansell',
            price=25.0,
            custom_id=6,
        )

    def show_response(self):
        """
        Utility method to return a response from the `show` view.
        """
        request = self.factory.get(reverse('carton-tests-show'))
        request.session = self.session

        return show(request)

    def test_product_is_added(self):
        """
        Can a product be added to the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.session.save()

        self.assertContains(self.show_response(), '1 deer for $10.0')

    def test_multiple_products_are_added(self):
        """
        Can multiple products be added to the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, '1 deer for $10.0')
        self.assertContains(response, '1 moose for $20.0')

    def test_stale_item_is_removed_from_cart(self):
        """
        Are items which are not in the database kept out of the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, 'deer')
        self.assertContains(response, 'moose')

        self.deer.delete()

        response = self.show_response()

        self.assertNotContains(response, 'deer')
        self.assertContains(response, 'moose')

    def test_quantity_increases(self):
        """
        Do multiple calls to `add` increase the quantity in the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.deer, 10.00, 2)
        self.session.save()

        self.assertContains(self.show_response(), '3 deer')

    def test_items_are_counted_properly(self):
        """
        Are items in the cart counted correctly?
        """
        self.cart.add(self.deer, 10.00, 2)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, 'items count: 3')
        self.assertContains(response, 'unique count: 2')

    def test_products_are_removed_all_together(self):
        """
        Can all products of a single type be removed?
        """
        self.cart.add(self.deer, 10.00, 3)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        self.cart.remove(self.deer)

        response = self.show_response()

        self.assertNotContains(response, 'deer')
        self.assertContains(response, 'moose')

    def test_single_product_is_removed(self):
        """
        Can a single instance of a product be removed?
        """
        self.cart.add(self.deer, 10.00, 3)
        self.session.save()

        self.cart.remove_single(self.deer)

        self.assertContains(self.show_response(), '2 deer')

    def test_quantity_is_overwritten(self):
        """
        Can an items quantity be changed?
        """
        self.cart.add(self.deer, 10.00, 3)
        self.session.save()

        self.cart.set_quantity(self.deer, 4)

        self.assertContains(self.show_response(), '4 deer')

    def test_cart_items_are_cleared(self):
        """
        Can a cart be entirely cleared?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.moose, 20.00, 1)
        self.cart.clear()
        self.session.save()

        response = self.show_response()

        self.assertNotContains(response, 'deer')
        self.assertNotContains(response, 'moose')

    @override_settings(CART_PRODUCT_LOOKUP={'price__gt': 1})
    def test_custom_product_filter_are_applied(self):
        """
        We modify the cart queryset to exclude some products. We
        should not be able to add excluded products to the cart.
        """
        exclude = Product.objects.create(
            name='EXCLUDED',
            price=0.99,
            custom_id=100,
        )

        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(exclude, exclude.price, 1)
        self.session.save()

        response = self.show_response()

        self.assertNotContains(response, 'EXCLUDE')
        self.assertContains(response, 'deer')

    def test_get_model_product_path(self):
        """
        Is a string with the full, correct import path returned for a
        model?
        """
        self.assertEqual(
            self.cart.get_product_model_path(self.deer),
            'carton.tests.models.Product',
        )

    def test_different_product_models(self):
        """
        Does the cart work with different models?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.ticket, 25.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, '1 deer for $10.0')
        self.assertContains(response, '1 Clint Mansell for $25.0')
Ejemplo n.º 37
0
    def post(self, request, *args, **kwargs):
        print(request.POST)

        cart = Cart(request.session)

        products = [
            OrderProduct(
                product=item.product,
                price=item.price,
                quantity=item.quantity
            ) for item in cart.items
        ]
        new_order = Order(owner=request.user)

        ### PagSeguro Begin
        api = PagSeguroApiTransparent()
        api.set_sender_hash(request.POST['sender-hash'])

        sender = {
            'name': 'Joãozinho do CITi', 
            'area_code': 81, 
            'phone': 21268430, 
            'email': settings.PAGSEGURO_TEST_BUYER_EMAIL, 
            'cpf': '10683924443'
        }
        api.set_sender(**sender)

        shipping = {
            'street': 'Av. Jornalista Aníbal Fernandes', 
            'number': 1, 
            'complement': 'Centro de Informática', 
            'district': 'Cidade Universitária', 
            'postal_code': '01452002', 
            'city': 'Recife', 
            'state': 'PE', 
            'country': 'BRA',
            'cost': Decimal('0.00')
        }
        api.set_shipping(**shipping)

        if 'bank-slip' in request.POST:
            # Boleto bancário
            api.set_payment_method('boleto')
        elif 'credit-card' in request.POST:
            # Cartão de crédito
            api.set_payment_method('creditcard')

            installments = 1
            installment_amount = cart.total # Deve ser o valor da parcela obtida no browser

            data = {
                'quantity': installments, 
                'value': installment_amount, 
                'name': 'Joãozinho do CITi', 
                'birth_date': '10/02/1995', 
                'cpf': '10683924443', 
                'area_code': 81, 
                'phone': 21268430
            }
            api.set_creditcard_data(**data)

            billing = {
                'street': 'Av. Jornalista Aníbal Fernandes', 
                'number': 1, 
                'complement': 'Centro de Informática', 
                'district': 'Cidade Universitária', 
                'postal_code': '01452002', 
                'city': 'Recife', 
                'state': 'PE', 
                'country': 'BRA',
            }
            api.set_creditcard_billing_address(**billing)

            api.set_creditcard_token(request.POST['card-token'])
        
        for p in products:
            api.add_item(p.to_pagseguro())

        checkout = api.checkout()

        if checkout['success']:
            print(checkout)
        ### PagSeguro End

        new_order.save()
        for p in products:
            p.save()
            new_order.products.add(p);
        
        cart.clear()
        return HttpResponseRedirect(reverse_lazy('core:index'))
Ejemplo n.º 38
0
class CartTests(TestCase):
    def setUp(self):
        engine = import_module(settings.SESSION_ENGINE)
        self.session = engine.SessionStore()
        self.session.save()
        self.client.cookies[
            settings.SESSION_COOKIE_NAME] = self.session.session_key

        self.factory = RequestFactory()

        self.cart = Cart(self.session)

        self.deer = Product.objects.create(
            name='deer',
            price=10.0,
            custom_id=1,
        )
        self.moose = Product.objects.create(
            name='moose',
            price=20.0,
            custom_id=2,
        )
        self.ticket = Ticket.objects.create(
            name='Clint Mansell',
            price=25.0,
            custom_id=6,
        )

    def show_response(self):
        """
        Utility method to return a response from the `show` view.
        """
        request = self.factory.get(reverse('carton-tests-show'))
        request.session = self.session

        return show(request)

    def test_product_is_added(self):
        """
        Can a product be added to the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.session.save()

        self.assertContains(self.show_response(), '1 deer for $10.0')

    def test_multiple_products_are_added(self):
        """
        Can multiple products be added to the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, '1 deer for $10.0')
        self.assertContains(response, '1 moose for $20.0')

    def test_stale_item_is_removed_from_cart(self):
        """
        Are items which are not in the database kept out of the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, 'deer')
        self.assertContains(response, 'moose')

        self.deer.delete()

        response = self.show_response()

        self.assertNotContains(response, 'deer')
        self.assertContains(response, 'moose')

    def test_quantity_increases(self):
        """
        Do multiple calls to `add` increase the quantity in the cart?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.deer, 10.00, 2)
        self.session.save()

        self.assertContains(self.show_response(), '3 deer')

    def test_items_are_counted_properly(self):
        """
        Are items in the cart counted correctly?
        """
        self.cart.add(self.deer, 10.00, 2)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, 'items count: 3')
        self.assertContains(response, 'unique count: 2')

    def test_products_are_removed_all_together(self):
        """
        Can all products of a single type be removed?
        """
        self.cart.add(self.deer, 10.00, 3)
        self.cart.add(self.moose, 20.00, 1)
        self.session.save()

        self.cart.remove(self.deer)

        response = self.show_response()

        self.assertNotContains(response, 'deer')
        self.assertContains(response, 'moose')

    def test_single_product_is_removed(self):
        """
        Can a single instance of a product be removed?
        """
        self.cart.add(self.deer, 10.00, 3)
        self.session.save()

        self.cart.remove_single(self.deer)

        self.assertContains(self.show_response(), '2 deer')

    def test_quantity_is_overwritten(self):
        """
        Can an items quantity be changed?
        """
        self.cart.add(self.deer, 10.00, 3)
        self.session.save()

        self.cart.set_quantity(self.deer, 4)

        self.assertContains(self.show_response(), '4 deer')

    def test_cart_items_are_cleared(self):
        """
        Can a cart be entirely cleared?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.moose, 20.00, 1)
        self.cart.clear()
        self.session.save()

        response = self.show_response()

        self.assertNotContains(response, 'deer')
        self.assertNotContains(response, 'moose')

    @override_settings(CART_PRODUCT_LOOKUP={'price__gt': 1})
    def test_custom_product_filter_are_applied(self):
        """
        We modify the cart queryset to exclude some products. We
        should not be able to add excluded products to the cart.
        """
        exclude = Product.objects.create(
            name='EXCLUDED',
            price=0.99,
            custom_id=100,
        )

        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(exclude, exclude.price, 1)
        self.session.save()

        response = self.show_response()

        self.assertNotContains(response, 'EXCLUDE')
        self.assertContains(response, 'deer')

    def test_get_model_product_path(self):
        """
        Is a string with the full, correct import path returned for a
        model?
        """
        self.assertEqual(
            self.cart.get_product_model_path(self.deer),
            'carton.tests.models.Product',
        )

    def test_different_product_models(self):
        """
        Does the cart work with different models?
        """
        self.cart.add(self.deer, 10.00, 1)
        self.cart.add(self.ticket, 25.00, 1)
        self.session.save()

        response = self.show_response()

        self.assertContains(response, '1 deer for $10.0')
        self.assertContains(response, '1 Clint Mansell for $25.0')
Ejemplo n.º 39
0
def clear_cart(request):
    cart = Cart(request.session)
    cart.clear()
    return HttpResponseRedirect('/')