Example #1
0
    def test_OrderForm_(self):
        invalid_data = {
            'order_number': '',
            'user_profile': '',
            'full_name': '',
            'email': '',
            'phone_number': '',
            'street_address1': '',
            'street_address2': '',
            'town_or_city': '',
            'postcode': '',
            'county': '',
            'country': ''
        }

        form = OrderForm(data=invalid_data)
        self.assertFalse(form.is_valid())
        self.assertTrue(form.errors)
        self.assertIn('full_name', form.errors.keys())
        self.assertIn('email', form.errors.keys())
        self.assertIn('phone_number', form.errors.keys())
        self.assertIn('street_address1', form.errors.keys())
        self.assertIn('town_or_city', form.errors.keys())
        self.assertIn('postcode', form.errors.keys())
Example #2
0
 def test_email_address_required(self):
     form = OrderForm({'email': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('email', form.errors.keys())
     self.assertEqual(form.errors['email'][0], 'This field is required.')
Example #3
0
def checkout(request):
    """ A view to render checkout page """

    public_key = settings.STRIPE_PUBLIC_KEY
    secret_key = settings.STRIPE_SECRET_KEY
    if request.method == 'POST':
        bag = request.session.get('bag', {})

        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'country': request.POST['country'],
            'postcode': request.POST['postcode'],
            'town_or_city': request.POST['town_or_city'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'county': request.POST['county'],
        }

        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_bag = json.dumps(bag)
            order.save()
            for workshop_id, quantity in bag.items():
                try:
                    workshop = Workshop.objects.get(id=workshop_id)
                    if isinstance(quantity, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            workshop=workshop,
                            quantity=quantity,
                        )
                        order_line_item.save()
                except Workshop.DoesNotExist:
                    messages.error(request, (
                        "One of the products in your bag wasn't"
                        "found in our database."
                        "Please message us for assistance!")
                    )
                    order.delete()
                    return redirect(reverse('booking'))

            request.session['save_info'] = 'save-info' in request.POST
            return redirect(reverse('checkout_success',
                                    args=[order.order_number]))
        else:
            messages.error(request, "There was an error with your form. \
                Check your information, please.")
    else:
        bag = request.session.get('bag', {})
        if not bag:
            messages.info(request, "Your booking is empty")
            return redirect(reverse('workshops'))

        current_bag = booking_contents(request)
        total = current_bag['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(initial={
                    'full_name': profile.full_name,
                    'email': profile.email_address,
                    'phone_number': profile.phone_number,
                    'street_address1': profile.street_address1,
                    'street_address2': profile.street_address2,
                    'postcode': profile.postcode,
                    'town_or_city': profile.town_or_city,
                    'county': profile.county,
                    'country': profile.country,
                })
            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    if not public_key:
        messages.warning(request, 'Stripe public key is missing. \
                Check your environment, maybe it is there sleeping.')

    template = 'checkout/checkout.html'

    context = {
        'order_form': order_form,
        'stripe_public_key': public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
 def test_full_name_is_required(self):
     form = OrderForm({'full_name': 'Test name'})
     self.assertFalse(form.is_valid())
 def test_phone_number_is_required(self):
     form = OrderForm({'phone_number': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('phone_number', form.errors.keys())
     self.assertEqual(form.errors['phone_number'][0],
                      'This field is required.')
 def test_town_or_city_is_required(self):
     form = OrderForm({'town_or_city': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('town_or_city', form.errors.keys())
     self.assertEqual(form.errors['town_or_city'][0],
                      'This field is required.')
 def test_postal_code_is_required(self):
     form = OrderForm({'postcode': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('postcode', form.errors.keys())
     self.assertEqual(form.errors['postcode'][0], 'This field is required.')
Example #8
0
def checkout(request):
    ''' render checkout form and complete order and payment with user provided details '''
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':

        form_data = {
            'first_name': request.POST['first_name'],
            'last_name': request.POST['first_name'],
            'email_address': request.POST['email_address'],
            'phone_number': request.POST['phone_number'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'town_or_city': request.POST['town_or_city'],
            'postcode': request.POST['postcode'],
            'country': request.POST['country'],
        }
        current_basket = basket_content(request)
        total = current_basket['total']
        order_form = OrderForm(form_data)

        if order_form.is_valid():
            order = order_form.save()
            order.total = total
            order.save()

            if request.user.is_authenticated:

                basket_items = BasketItem.objects.filter(
                    basket__owner=request.user)
                for basket_item in basket_items:
                    order_item = OrderItem(order=order, product=basket_item.product,
                                           quantity=basket_item.quantity, colour=basket_item.colour)
                    order_item.save()

                if 'save' in request.POST:
                    profile = get_object_or_404(Profile, owner=request.user)
                    profile_form = ProfileForm(form_data, instance=profile)
                    if profile_form.is_valid():
                        profile_form.save()

            else:
                basket = request.session.get('basket', {})

                for item in basket:
                    product = Product.objects.get(pk=basket[item]['product'])
                    quantity = basket[item]['quantity']
                    colour = None
                    if Colour.objects.filter(pk=basket[item]['colour']).exists():
                        colour = Colour.objects.get(pk=basket[item]['colour'])

                    order_item = OrderItem(
                        order=order, product=product, quantity=quantity, colour=colour)
                    order_item.save()

            return redirect(reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(
                request, 'There is an error in your form, please check your data')
            return redirect(reverse('checkout'))

    else:

        if request.user.is_authenticated:
            if BasketItem.objects.filter(basket__owner=request.user).exists():
                basket = Basket.objects.get(owner=request.user)
            else:
                basket = None

            # if details were saved in profile, display them in the form
            if Profile.objects.filter(owner=request.user).exists():
                profile = Profile.objects.get(owner=request.user)

                order_form = OrderForm(initial={
                    'first_name': profile.first_name,
                    'last_name': profile.first_name,
                    'email_address': profile.email_address,
                    'phone_number': profile.phone_number,
                    'street_address1': profile.street_address1,
                    'street_address2': profile.street_address2,
                    'town_or_city': profile.town_or_city,
                    'postcode': profile.postcode,
                    'country': profile.country,
                    })
        else:
            basket = request.session.get('basket', {})
            order_form = OrderForm()

        if not basket:
            messages.error(
                request, "There's nothing in your basket at the moment")
            return redirect(reverse('basket'))

        current_basket = basket_content(request)
        total = current_basket['total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

    
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, 'checkout.html', context)
 def test_street_address1_is_required(self):
     form = OrderForm({'street_address1': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('street_address1', form.errors.keys())
     self.assertEqual(form.errors['street_address1'][0],
                      'This field is required.')
Example #10
0
 def test_full_name_required(self):
     form = OrderForm({'full_name': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('full_name', form.errors.keys())
     self.assertEqual(form.errors['full_name'][0],
                      'This field is required.')
 def test_correct_message_for_empty_form(self):
     form = OrderForm({'form': ''})
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors['first_name'], [u'This field is required.'])
Example #12
0
def checkout(request):
    '''
    function to load items currently in the cart
    and load the payment forms if there are donations
    in the cart. Stripe will check payments and process
    them accordingly
    '''

    # checking if anything is in the cart
    cartcontent = request.session.get('cart', {})
    # if nothing is in the cart redirect to donation page
    if not cartcontent:
        messages.warning(request, f'Your Cart has no donations!! ')
        return redirect(reverse('donations'))

    user = request.user
    # if user fills in forms on checkout
    if request.method == "POST":
        order_form = OrderForm(request.POST)
        payment_form = MakePaymentForm(request.POST)
        # check if forms are valid
        if order_form.is_valid() and payment_form.is_valid():
            # add current date and user to form and save
            order = order_form.save(commit=False)
            order.date = timezone.now()
            order.user = user
            order.save()
            # get cart content once checkout details are submitted correctly
            cart = request.session.get('cart', {})
            total = 0
            # finding cart donation types and calculating overall price
            for id, quantity in cart.items():
                donation = get_object_or_404(Donation, pk=id)
                total += quantity * donation.price
                # adding order to db
                order_line_item = OrderLineItem(order=order,
                                                donation=donation,
                                                quantity=quantity)
                order_line_item.save()

            try:
                # processing stripe payment
                customer = stripe.Charge.create(
                    amount=int(total * 100),
                    currency="EUR",
                    description=request.user.email,
                    card=payment_form.cleaned_data['stripe_id'],
                )
            # display card errors if any
            except stripe.error.CardError:
                messages.error(request, "Your card was declined!")

            # if payment is successful empty cart content and inform user
            if customer.paid:
                messages.success(request, f'You have successfully paid')
                request.session['cart'] = {}
                return redirect(reverse('donations'))
            else:
                messages.error(request, "Unable to take payment")

        else:
            print(payment_form.errors)
            messages.error(request,
                           "We were unable to take a payment with that card!")

    else:
        # loading payment forms
        payment_form = MakePaymentForm()
        order_form = OrderForm()

    return render(
        request, "checkout/checkout.html", {
            'order_form': order_form,
            'payment_form': payment_form,
            'publishable': settings.STRIPE_PUBLISHABLE
        })
Example #13
0
 def test_item_country_is_required(self):
     """ test country field is required """
     form = OrderForm({'country': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('country', form.errors.keys())
     self.assertEqual(form.errors['country'][0], 'This field is required.')
Example #14
0
def checkout(request):
    """
    Creates order from basket items, takes payment through Stripe and
    emails user receipt
    """
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY
    if request.method == 'POST':
        basket = request.session.get('basket', {})
        form_data = {
            'fullname': request.POST['fullname'],
            'phone_number': request.POST['phone_number'],
            'address_line1': request.POST['address_line1'],
            'address_line2': request.POST['address_line2'],
            'town_city': request.POST['town_city'],
            'postcode': request.POST['postcode'],
            'country': request.POST['country'],
        }
        order_form = OrderForm(form_data)

        if order_form.is_valid():
            order = order_form.save(commit=False)
            order.order_user = request.user
            order.save()
            for id, quantity in basket.items():
                try:
                    product = Products.objects.get(pk=id)
                    order_item = OrderItem(order=order,
                                           product=product,
                                           quantity=quantity)
                    order_item.save()
                    del request.session['basket']
                    del request.session['product_count']
                    request.session.modified = True

                    context = {
                        'order': order,
                    }
                    from_email = os.environ.get('EMAIL_USER')
                    user = request.user
                    header = "Tartan Thom Receipt"
                    html_message = render_to_string('checkout/receipt.html',
                                                    context)
                    plain_message = strip_tags(html_message)
                    send_mail(header,
                              plain_message,
                              from_email, [user.email],
                              html_message=html_message,
                              fail_silently=False)

                except Products.DoesNotExist:
                    order.delete()
            return redirect(
                reverse('checkout:checkout_success',
                        args=[order.order_number]))
        else:
            messages.error(request,
                           "Please review the details in the order form")
    else:
        basket = request.session.get('basket', {})
        current_contents = basket_contents(request)
        grand_total = current_contents['grand_total']
        stripe_total = round(grand_total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(amount=stripe_total,
                                             currency=settings.STRIPE_CURRENCY)
        order_form = OrderForm()
        context = {
            'order_form': order_form,
            'stripe_public_key': stripe_public_key,
            'client_secret': intent.client_secret,
        }

    return render(request, 'checkout/checkout.html', context)