Beispiel #1
0
def shipping_rate(context, **kwargs):
    """Return the shipping rate for a country & shipping option name.
    """
    settings = Configuration.for_site(context["request"].site)
    code = kwargs.get('code', None)
    name = kwargs.get('name', None)
    return get_shipping_cost(settings, code, name)
Beispiel #2
0
def get_shipping_cost_kwargs(request, country=None):
    country_code = request.query_params.get('country_code', None)
    if country:
        if country_code is not None:
            raise utils.InvalidShippingCountry(
                "Cannot specify country and country_code")
        country_code = country

    destination = request.query_params.get('destination', None)
    if destination:
        try:
            destination = models.Address.objects.get(pk=destination)
        except models.Address.DoesNotExist:
            raise utils.InvalidShippingDestination("Address not found")
    elif not country_code:
        raise utils.InvalidShippingCountry("No country code supplied")

    if not country_code:
        country_code = destination.country.pk

    bid = basket_id(request)
    option = request.query_params.get('shipping_rate_name', 'standard')
    settings = Configuration.for_site(request.site)

    return dict(country_code=country_code,
                destination=destination,
                basket_id=bid,
                settings=settings,
                name=option)
Beispiel #3
0
def shipping_cost(request):
    """ Returns the shipping cost for a given country
    If the shipping cost for the given country has not been set, it will
    fallback to the default shipping cost if it has been enabled in the app
    settings
    """
    try:
        code = request.query_params.get('country_code')
    except AttributeError:
        return Response(data={"message": "No country code supplied"},
                        status=status.HTTP_400_BAD_REQUEST)

    option = request.query_params.get('shipping_rate_name', 'standard')
    try:
        settings = Configuration.for_site(request.site)
        data = utils.get_shipping_cost(settings, code, option)
        response = Response(data=data, status=status.HTTP_200_OK)
    except utils.InvalidShippingRate:
        response = Response(
            data={"message": "Shipping option {} is invalid".format(option)},
            status=status.HTTP_400_BAD_REQUEST)
    except utils.InvalidShippingCountry:
        response = Response(
            data={"message": "Shipping to {} is not available".format(code)},
            status=status.HTTP_400_BAD_REQUEST)

    return response
Beispiel #4
0
 def test_basket_rate(self):
     # this tests that we get a basket rate that is just tied to the basket and nothing else
     # (i.e. this basket qualifies for free shipping or something like that)
     result = get_shipping_cost(Configuration(),
                                name='98d17c43-7e20-42bd-b603-a4c83c829c5a',
                                basket_id=self.bid)
     self.assertEqual(result["rate"], 99)
     self.assertEqual(result["description"],
                      '313037e1-644a-4570-808a-f9ba82ecfb34')
Beispiel #5
0
 def test_get_shipping_cost_kwargs_only_country(self):
     request = RequestFactory().get('/')
     api_request = upgrade_to_api_request(request)
     result = get_shipping_cost_kwargs(api_request, country=self.country.pk)
     self.assertEqual(result['country_code'], self.country.pk)
     self.assertEqual(result['destination'], None)
     self.assertEqual(result['basket_id'], basket_id(api_request))
     self.assertEqual(result['settings'],
                      Configuration.for_site(api_request.site))
     self.assertEqual(result['name'], 'standard')
Beispiel #6
0
 def test_address_rate(self):
     # this tests that we get a rate tied to a particular address
     result = get_shipping_cost(
         Configuration(),
         name='72991859-dc0b-463e-821a-bf8b04aaed2c',
         destination=self.address,
     )
     self.assertEqual(result["rate"], 95)
     self.assertEqual(result["description"],
                      '78b03c47-b20f-4f91-8161-47340367fb34')
Beispiel #7
0
 def get_context(self):
     settings = Configuration.for_request(self.request)
     sales = stats.sales_for_time_period(*stats.current_month())
     return {
         'total': "{}{}".format(settings.currency_html_code,
                                sum(order.total for order in sales)),
         'text': 'In sales this month',
         'url': '/admin/orders/order/',
         'icon': 'icon-tick'
     }
Beispiel #8
0
 def create_payment(self, request, amount, description=''):
     try:
         currency = Configuration.for_site(request.site).currency
         charge = stripe.Charge.create(
             amount=int(math.ceil(amount * 100)),  # Amount in pence
             currency=currency.lower(),
             source=request.data['token'],
             description=description)
         return charge.id
     except stripe.error.CardError as error:
         raise PaymentError(error)
Beispiel #9
0
    def get(self, request, *args, **kwargs):
        order_info = OrderItem.objects.filter(
            order__order_id=str(self.kwargs['pk'])).select_related('order')
        invoice_prefix = Configuration.for_site(request.site).invoice_prefix
        inv_data = {
            'invoice': order_info,
            'invoice_prefix': invoice_prefix,
        }
        pdf = render_to_pdf('invoice/invoice.html', inv_data)

        return HttpResponse(pdf, content_type='application/pdf')
Beispiel #10
0
 def test_get_shipping_cost_kwargs_with_destination(self):
     destination = AddressFactory()
     request = RequestFactory().get('/', {'destination': destination.pk})
     api_request = upgrade_to_api_request(request)
     result = get_shipping_cost_kwargs(api_request)
     self.assertEqual(result['country_code'], destination.country.pk)
     self.assertEqual(result['destination'], destination)
     self.assertEqual(result['basket_id'], basket_id(api_request))
     self.assertEqual(result['settings'],
                      Configuration.for_site(api_request.site))
     self.assertEqual(result['name'], 'standard')
Beispiel #11
0
 def test_basket_address_rate(self):
     # this tests that we get a rate tied to a particular basket and a particular address
     result = get_shipping_cost(
         Configuration(),
         name='8e721550-594c-482b-b512-54dc1744dff8',
         basket_id=self.bid,
         destination=self.address,
     )
     self.assertEqual(result["rate"], 97)
     self.assertEqual(result["description"],
                      'eacb446d-eb17-4ea7-82c1-ac2f62a53a7d')
Beispiel #12
0
 def test_get_shipping_cost_kwargs_only_country_known_iso(self):
     request = RequestFactory().get('/')
     api_request = upgrade_to_api_request(request)
     country = Country.objects.create(iso='ZZ',
                                      name_official='foo',
                                      name='foo')
     result = get_shipping_cost_kwargs(api_request, country=country.pk)
     self.assertEqual(result['country_code'], 'ZZ')
     self.assertEqual(result['destination'], None)
     self.assertEqual(result['basket_id'], basket_id(api_request))
     self.assertEqual(result['settings'],
                      Configuration.for_site(api_request.site))
     self.assertEqual(result['name'], 'standard')
Beispiel #13
0
 def create_payment(self, request, amount, description=''):
     try:
         currency = Configuration.for_request(request).currency
         charge = stripe.Charge.create(
             amount=int(math.ceil(amount * 100)),  # Amount in pence
             currency=currency.lower(),
             source=request.POST.get('stripeToken'),
             description=description
         )
         return charge.id
     except stripe.error.CardError as error:
         raise PaymentError(error.user_message)
     except Exception as e:
         raise PaymentError('An unexpected error occured, please try again')
Beispiel #14
0
 def test_get_shipping_cost_kwargs_country_code_and_shipping_rate_name(
         self):
     request = RequestFactory().get('/', {
         'country_code': 'US',
         'shipping_rate_name': 'foo'
     })
     api_request = upgrade_to_api_request(request)
     result = get_shipping_cost_kwargs(api_request)
     self.assertEqual(result['country_code'], 'US')
     self.assertEqual(result['destination'], None)
     self.assertEqual(result['basket_id'], basket_id(api_request))
     self.assertEqual(result['settings'],
                      Configuration.for_site(api_request.site))
     self.assertEqual(result['name'], 'foo')
Beispiel #15
0
    def __init__(self, *args, **kwargs):
        site = kwargs.pop('site', None)
        super(AddressForm, self).__init__(*args, **kwargs)

        # Edit the country field to only contain
        # countries specified for shipping
        all_countries = True
        if site:
            settings = Configuration.for_site(site)
            all_countries = settings.default_shipping_enabled
        if all_countries:
            queryset = Country.objects.all()
        else:
            queryset = Country.objects.exclude(shippingrate=None)
        self.fields['country'] = ModelChoiceField(queryset)
Beispiel #16
0
 def create_payment(self, request, amount, description=''):
     config = Configuration.for_site(request.site)
     nonce = request.POST.get('payment_method_nonce')
     result = self.gateway.transaction.sale({
         "amount": str(amount),
         "payment_method_nonce": nonce,
         "merchant_account_id": config.currency,
         "options": {
             "paypal": {
                 "description": description
             }
         }
     })
     if not result.is_success:
         raise PaymentError(result.message)
     return result.transaction.order_id
def currency(request):
    config = Configuration.for_request(request)
    return {
        'currency_html_code': config.currency_html_code,
        'currency': config.currency
    }
Beispiel #18
0
def create_order(email,
                 request,
                 addresses=None,
                 shipping_address=None,
                 billing_address=None,
                 shipping_option=None,
                 capture_payment=False):
    """
    Create an order from a basket and customer infomation
    """
    basket_items, _ = get_basket_items(request)
    if addresses:
        # Longclaw < 0.2 used 'shipping_name', longclaw > 0.2 uses a consistent
        # prefix (shipping_address_xxxx)
        try:
            shipping_name = addresses['shipping_name']
        except KeyError:
            shipping_name = addresses['shipping_address_name']

        shipping_country = addresses['shipping_address_country']
        if not shipping_country:
            shipping_country = None
        shipping_address, _ = Address.objects.get_or_create(
            name=shipping_name,
            line_1=addresses['shipping_address_line1'],
            city=addresses['shipping_address_city'],
            postcode=addresses['shipping_address_zip'],
            country=shipping_country)
        shipping_address.save()
        try:
            billing_name = addresses['billing_name']
        except KeyError:
            billing_name = addresses['billing_address_name']
        billing_country = addresses['shipping_address_country']
        if not billing_country:
            billing_country = None
        billing_address, _ = Address.objects.get_or_create(
            name=billing_name,
            line_1=addresses['billing_address_line1'],
            city=addresses['billing_address_city'],
            postcode=addresses['billing_address_zip'],
            country=billing_country)
        billing_address.save()
    else:
        shipping_country = shipping_address.country

    ip_address = get_real_ip(request)
    if shipping_country and shipping_option:
        site_settings = Configuration.for_site(request.site)
        shipping_rate = get_shipping_cost(site_settings,
                                          shipping_address.country.pk,
                                          shipping_option)['rate']
    else:
        shipping_rate = Decimal(0)

    order = Order(email=email,
                  ip_address=ip_address,
                  shipping_address=shipping_address,
                  billing_address=billing_address,
                  shipping_rate=shipping_rate)
    order.save()

    # Create the order items & compute total
    total = 0
    for item in basket_items:
        total += item.total()
        order_item = OrderItem(product=item.variant,
                               quantity=item.quantity,
                               order=order)
        order_item.save()

    if capture_payment:
        desc = 'Payment from {} for order id #{}'.format(email, order.id)
        try:
            transaction_id = GATEWAY.create_payment(request,
                                                    total + shipping_rate,
                                                    description=desc)
            order.payment_date = timezone.now()
            order.transaction_id = transaction_id
            # Once the order has been successfully taken, we can empty the basket
            destroy_basket(request)
        except PaymentError:
            order.status = order.FAILURE

        order.save()

    return order
Beispiel #19
0
 def test_multiple_shipping_cost(self):
     sr = ShippingRateFactory(countries=[self.country])
     sr2 = ShippingRateFactory(countries=[self.country])
     result = get_shipping_cost(Configuration(), self.country.pk, sr.name)
     self.assertEqual(result["rate"], sr.rate)
Beispiel #20
0
 def test_default_shipping_cost(self):
     ls = Configuration(default_shipping_enabled=True)
     result = get_shipping_cost(ls)
     self.assertEqual(ls.default_shipping_rate, result["rate"])