Beispiel #1
0
 def post(self, request):
     if request.POST.get('email'):
         name = request.POST.get('name')
         phone = request.POST.get('phone')
         email = request.POST.get('email')
         customer = Customer(name=name, phone=phone, email=email)
         customer.save()
         qrcode_path = customer.qrcode_create()
         customer.qrcode = qrcode_path
         customer.save()
         order = Order(customer=customer, )
         order.save()
         cart = request.session.get('cart')
         if cart:
             for product_id, quantity in cart.items():
                 cart = Cart(product_id=product_id,
                             quantity=quantity,
                             order=order,
                             complete=True)
                 cart.save()
             del request.session['cart']
             request.session.save()
     cart = order.cart_set.all()
     context = {'cart': cart, 'order': order}
     return render(request, 'shop/order.html', context)
Beispiel #2
0
def order(request):
    if request.method == 'GET':
        beers = Card.objects.all()
        context = {'beers': beers}
        return render(request, 'order_page.html', context)
    elif request.method == 'POST' and 'back' in request.POST:
        return redirect('main_page')
    elif request.method == 'POST' and 'confirm' in request.POST:
        name = request.POST.get('name_1')
        address = request.POST.get('address')
        if not name or not address:
            beers = Card.objects.all()
            context = {'beers': beers, 'valid': 'Please, fill in your name and address'}
            return render(request, 'order_page.html', context)
        else:
            customer = Customer(name=name, address=address)
            customer.save()
            all_card = Card.objects.all()
            for orders in all_card:
                Order.objects.create(beer=orders.beer, value=orders.value, customer=customer)
            card = Card.objects.all()
            card.delete()
            return render(request, 'succ_page.html')
    else:
        id_del = request.POST.get('id')
        all_card = Card.objects.get(id=id_del)
        all_card.delete()
        beers = Card.objects.all()
        context = {'beers': beers}
        return render(request, 'order_page.html', context)
Beispiel #3
0
def results(request):
    if request.method == 'POST': # Submitted the purchase form:
        form = PurchaseForm(request.POST)
        print 'GOT POST'

        if not request.user.is_authenticated():
            errors = form._errors.setdefault("loggedin", ErrorList())
            errors.append("Please log in before ordering")

        elif form.is_valid(): # TODO if form is not valid because no items in cart, say so! item_list is hidden field so user cannot see error.
            hasError = False
            user_email = request.user.username # form.cleaned_data['email']
            email_html = '<p>Name: ' + form.cleaned_data['name'] + '<br />Email: ' + user_email + '<br />Address: ' + form.cleaned_data['living_group'] + '<br />Room number: ' + form.cleaned_data['room_number'] + '<br />Phone number: ' + form.cleaned_data['phone_number'] + '</p><p><b>Delivery date: Saturday, April 6, 2013</b></p><p><b>Order:</b></p>'

            cart_items = json.loads(form.cleaned_data['items_list'])
            cart_total = 0

            print 'cart items: ', cart_items

            for cart_item_id in cart_items:
                # make sure JSON output in cart_item_id form field is int as saved by browser, on chrome is. Otherwise would need to cast.
                qty = cart_items[cart_item_id]
                item = ShopItem.objects.get(pk=cart_item_id)
                cart_total += (item.item_price * qty)
                email_html += '<p>' + str(qty) + 'x ' + item.item_name + ' @ ' + pretty_price(item.item_price) + ' = ' + pretty_price(item.item_price * qty) + ' </p>'


            email_html += '<p>Order total: ' + pretty_price(cart_total) + '</p>'
            # Should also check cart matches the one saved in databse.

            card_dictionary = {
                'number': form.cleaned_data['card_number'],
                'exp_month': form.cleaned_data['card_expiration_month'],
                'exp_year': form.cleaned_data['card_expiration_year'],
                'cvc': form.cleaned_data['card_cvc'],
                'address_zip': form.cleaned_data['card_zip'],
            }

            # process order immediately
            """
            charge = stripe.Charge.create(
                amount=cart_total,
                currency='usd',
                card=card_dictionary,
                description='SnapShop order for ' + form.cleaned_data['name'],
                )
            """

            useCard = False
            if form.cleaned_data['payment_choices'] == 'use_old':
                try:
                    customer = Customer.objects.get(user=request.user)
                    try:
                        card = CreditCard.objects.get(cc_owner=customer)
                        # TODO increase balance from Stripe

                    except CreditCard.DoesNotExist:
                        hasError = True
                        errors = form._errors.setdefault("username", ErrorList())
                        errors.append("An error ocurred in retreiving your saved card. Please re-enter the information below.")

                except Customer.DoesNotExist:
                    hasError = True
                    errors = form._errors.setdefault("username", ErrorList())
                    errors.append("An error ocurred in retreiving your saved card. Please re-enter the information below.")
            else: # payment_choices == 'save_new' or 'no_save'
                # Try only creating customer: should account for customer already created, and save in DB.
                # Catching errors in: https://stripe.com/docs/api?lang=python
                try:
                    stripe_customer = stripe.Customer.create(
                                # use SnapShop username?
                                description="Customer " + form.cleaned_data['name'],
                                card=card_dictionary,
                                account_balance=cart_total,
                                email=user_email, #request.user.username
                            )
                    print stripe_customer
                except stripe.CardError, e:
                    print e
                    errors = form._errors.setdefault("card_number", ErrorList())
                    errors.append("Card error: " + e.message)
                    hasError = True
                except stripe.StripeError, e:
                    print e
                    errors = form._errors.setdefault("card_number", ErrorList())
                    errors.append("A stripe error has ocurred. Please contact the site administrator")
                    hasError = True
                if not hasError:
                    try:
                        our_customer = Customer.objects.get(user=request.user)
                    except Customer.DoesNotExist:
                        our_customer = Customer(stripe_token=stripe_customer.id, phone_number='', delivery_time=datetime.datetime(2013, 03, 16), user=request.user)
                        our_customer.save()

                    # TODO will this create duplicate credit card entries
                    if form.cleaned_data['payment_choices'] == 'save_new':
                        card_number = form.cleaned_data['card_number']
                        our_card = CreditCard(cc_stub=card_number[-4:], cc_type=0, cc_owner=our_customer)
                        our_card.save()

            if not hasError:
                # Send email to us - admins
                admin_msg = EmailMessage('New Snapshop order!', email_html, '*****@*****.**', ['*****@*****.**', '*****@*****.**'])
                admin_msg.content_subtype = 'html'
                admin_msg.send(fail_silently=False)

                # Senc copy of email to customer
                user_msg = EmailMessage('Thank you for your SnapShop order!', email_html, '*****@*****.**', [user_email])
                user_msg.content_subtype = 'html'
                user_msg.send(fail_silently=True)
                return HttpResponseRedirect('/thanks/')
Beispiel #4
0
    def post(self, request):
        email = request.POST['email']
        fname = request.POST['fname']
        lname = request.POST['lname']
        phone = request.POST['phone']
        house = request.POST['house']
        street = request.POST['street']
        state = request.POST['state']
        city = request.POST['city']
        pin = request.POST['pin']
        pass1 = request.POST['pass1']
        pass2 = request.POST['pass2']
        uname = email
        print(uname, fname, lname, email, phone, pass1)

        values = {
            'email': email,
            'fname': fname,
            'lname': lname,
            'phone': phone,
            'house': house,
            'street': street,
            'state': state,
            'city': city,
            'pin': pin,
        }

        # Form Validations
        if User.objects.filter(email=email):
            messages.success(request, "E-mail Already Registered!!!")
            return render(request, 'signup.html', values)
        if len(fname) > 10 and len(lname) > 10:
            messages.success(request, "First or Last Name too long!!!")
            return render(request, 'signup.html', values)
        if not fname.isalpha() or not lname.isalpha():
            messages.warning(request, "Name must contain only letters.")
            return render(request, 'signup.html', values)
        if len(str(phone)) != 10:
            messages.warning(request, "Phone number must contain 10 digits.")
            return render(request, 'signup.html', values)
        if len(pass1) < 5:
            messages.warning(
                request,
                "Password too short!!! It must have atleast 5 characters.")
            return render(request, 'signup.html', values)
        if pass1 != pass2:
            messages.warning(request, "Passwords don't match!!!")
            return render(request, 'signup.html', values)

        new_user = User.objects.create_user(
            uname,
            email=email,
            password=pass1,
            first_name=fname.capitalize(),
            last_name=lname.capitalize(),
        )
        new_user.save()

        customer = Customer(
            user=new_user,
            phone=phone,
            house_no=house,
            street=street.capitalize(),
            state=state.capitalize(),
            city=city.capitalize(),
            pin=pin,
        )
        customer.save()

        user = authenticate(request, username=email, password=pass1)
        if user is not None:
            login(request, user)

        messages.success(request, "Account Created Successfully!!!")
        return redirect('ShopHome')