Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add function for calulcation taxes

Maciej Korycinskia89f8ee41c6e
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index 483efd74ca..0c6cc6d377 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -1,5 +1,6 @@
"""Checkout-related forms and fields."""
from datetime import date
+from decimal import Decimal
from typing import Any
from django import forms
@@ -9,7 +10,9 @@ from django.utils.encoding import smart_text
from django.utils.safestring import mark_safe
from django.utils.translation import npgettext_lazy, pgettext_lazy
from django_countries.fields import LazyTypedChoiceField
-from prices import TaxedMoney
+from prices import Money, TaxedMoney
+
+from saleor.core.taxes.interface import apply_taxes_to_shipping, get_subtotal_gross
from ..core.exceptions import InsufficientStock
from ..core.taxes import display_gross_prices
@@ -291,16 +294,17 @@ class ShippingMethodChoiceField(forms.ModelChoiceField):
prices.
"""
- taxes = None
+ shipping_address = None
widget = forms.RadioSelect()
def label_from_instance(self, obj):
"""Return a friendly label for the shipping method."""
- price = TaxedMoney(net=obj.price, gross=obj.price)
if display_gross_prices():
- price = price.gross
+ price = apply_taxes_to_shipping(
+ obj.price, shipping_address=self.shipping_address
+ ).gross
else:
- price = price.net
+ price = obj.price
price_html = format_money(price)
label = mark_safe("%s %s" % (obj.name, price_html))
return label
@@ -319,16 +323,16 @@ class CheckoutShippingMethodForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
discounts = kwargs.pop("discounts")
- taxes = kwargs.pop("taxes")
super().__init__(*args, **kwargs)
- country_code = self.instance.shipping_address.country.code
+ shipping_address = self.instance.shipping_address
+ country_code = shipping_address.country.code
qs = ShippingMethod.objects.applicable_shipping_methods(
- price=self.instance.get_subtotal(discounts, taxes).gross,
+ price=get_subtotal_gross(self.instance, discounts).gross,
weight=self.instance.get_total_weight(),
country_code=country_code,
)
self.fields["shipping_method"].queryset = qs
- self.fields["shipping_method"].taxes = taxes
+ self.fields["shipping_method"].shipping_address = shipping_address
if self.initial.get("shipping_method") is None:
shipping_methods = qs.all()
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 6553f9875a..c5321b3beb 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -659,11 +659,11 @@ def get_checkout_context(
context = {
"checkout": checkout,
- "checkout_are_taxes_handled": True, # bool(taxes),
+ "checkout_are_taxes_handled": True, # bool(taxes), #FIXME
"checkout_lines": [
(line, line.get_total(discounts, taxes)) for line in checkout
],
- "checkout_shipping_price": shipping_price, # checkout.get_shipping_price(taxes),
+ "checkout_shipping_price": shipping_price,
"checkout_subtotal": checkout_subtotal,
"checkout_total": checkout_total,
"shipping_required": checkout.is_shipping_required(),
@@ -840,13 +840,13 @@ def get_taxes_for_checkout(checkout, default_taxes):
return default_taxes
-def is_valid_shipping_method(checkout, taxes, discounts):
+def is_valid_shipping_method(checkout, discounts):
"""Check if shipping method is valid and remove (if not)."""
if not checkout.shipping_method:
return False
valid_methods = ShippingMethod.objects.applicable_shipping_methods(
- price=checkout.get_subtotal(discounts, taxes).gross,
+ price=get_subtotal_gross(checkout, discounts).gross,
weight=checkout.get_total_weight(),
country_code=checkout.shipping_address.country.code,
)
@@ -901,7 +901,7 @@ def _process_shipping_data_for_order(checkout, shipping_price):
"shipping_address": shipping_address,
"shipping_method": checkout.shipping_method,
"shipping_method_name": smart_text(checkout.shipping_method),
- "shipping_price": shipping_price, # checkout.get_shipping_price(taxes),
+ "shipping_price": shipping_price,
"weight": checkout.get_total_weight(),
}
@@ -997,7 +997,7 @@ def clean_checkout(checkout: Checkout, taxes, discounts):
raise ValidationError("Shipping method is not set")
if not checkout.shipping_address:
raise ValidationError("Shipping address is not set")
- if not is_valid_shipping_method(checkout, taxes, discounts):
+ if not is_valid_shipping_method(checkout, discounts):
raise ValidationError(
"Shipping method is not valid for your shipping address"
)
diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.py
index ef248a1d8a..c8d5b7b4c9 100644
--- a/saleor/checkout/views/__init__.py
+++ b/saleor/checkout/views/__init__.py
@@ -71,12 +71,11 @@ def checkout_shipping_method(request, checkout):
"""Display the shipping method selection step."""
discounts = request.discounts
taxes = get_taxes_for_checkout(checkout, request.taxes)
- is_valid_shipping_method(checkout, request.taxes, discounts)
+ is_valid_shipping_method(checkout, discounts)
form = CheckoutShippingMethodForm(
request.POST or None,
discounts=discounts,
- taxes=taxes,
instance=checkout,
initial={"shipping_method": checkout.shipping_method},
)
diff --git a/saleor/checkout/views/summary.py b/saleor/checkout/views/summary.py
index e85e5a97dc..276664cf60 100644
--- a/saleor/checkout/views/summary.py
+++ b/saleor/checkout/views/summary.py
@@ -6,8 +6,6 @@ from django.utils.translation import pgettext
from ...account.models import Address
from ...core import analytics
from ...core.exceptions import InsufficientStock
-
-# FIXME This should be taken from taxes module
from ...core.taxes.errors import TaxError
from ...discount.models import NotApplicable
from ..forms import CheckoutNoteForm
diff --git a/saleor/checkout/views/validators.py b/saleor/checkout/views/validators.py
index fc25009a1a..462768bbcb 100644
--- a/saleor/checkout/views/validators.py
+++ b/saleor/checkout/views/validators.py
@@ -54,7 +54,7 @@ def validate_shipping_method(view):
@wraps(view)
def func(request, checkout):
- if not is_valid_shipping_method(checkout, request.taxes, request.discounts):
+ if not is_valid_shipping_method(checkout, request.discounts):
return redirect("checkout:shipping-method")
return view(request, checkout)
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index e35d4db23e..320c7f86b9 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -167,7 +167,7 @@ def taxes(get_response):
"""Assign tax rates for default country to `request.taxes`."""
def middleware(request):
- request.taxes = None
+ request.taxes = None # FIXME
return get_response(request)
return middleware
diff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/taxes/avatax/__init__.py
index 910265d501..e6349d448f 100644
--- a/saleor/core/taxes/avatax/__init__.py
+++ b/saleor/core/taxes/avatax/__init__.py
@@ -1,6 +1,6 @@
import json
from datetime import date
-from typing import Any, Dict, List
+from typing import Any, Dict, List, Optional
from urllib.parse import urljoin
import requests
@@ -11,7 +11,7 @@ from requests.auth import HTTPBasicAuth
from .. import charge_taxes_on_shipping
common_carrier_code = "FR020100" # FIXME
-cache_key = "avatax_checkout_id"
+cache_key = "avatax_request_id_" # FIXME
class TransactionType:
@@ -35,8 +35,6 @@ def api_post_request(
try:
auth = HTTPBasicAuth(username, password)
response = requests.post(url, auth=auth, data=json.dumps(data))
- print(auth)
- print(response.content)
except requests.exceptions.RequestException:
return {}
return response.json()
@@ -81,7 +79,44 @@ def checkout_needs_new_fetch(data, checkout_token: str) -> bool:
return False
-def get_lines_data(checkout: "Checkout", discounts=None) -> List[Dict[str, str]]:
+def taxes_need_new_fetch(data: Dict[str, Any], taxes_token: str) -> bool:
+ """We store the response from avatax. If object doesn't exist in cache or
+ something has changed, then we fetch data from avatax."""
+ taxes_cache_key = cache_key + taxes_token
+ cached_data = cache.get(taxes_cache_key)
+
+ if not cached_data:
+ return True
+
+ cached_request_data, _ = cached_data
+ if data != cached_request_data:
+ return True
+ return False
+
+
+def append_line_to_data(
+ data: List[Dict[str, str]],
+ quantity: int,
+ amount: str,
+ tax_code: str,
+ item_code: str,
+ description: str = None,
+):
+ data.append(
+ {
+ "quantity": quantity,
+ "amount": amount,
+ "taxCode": tax_code,
+ # FIXME Should fetch taxcode from somewhere and save inside variant/product
+ "itemCode": item_code,
+ "description": description[:2000] if description else "",
+ }
+ )
+
+
+def get_checkout_lines_data(
+ checkout: "Checkout", discounts=None
+) -> List[Dict[str, str]]:
data = []
lines = checkout.lines.prefetch_related(
"variant__product__category",
@@ -90,47 +125,69 @@ def get_lines_data(checkout: "Checkout", discounts=None) -> List[Dict[str, str]]
)
for line in lines:
description = line.variant.product.description
-
- data.append(
- {
- "quantity": line.quantity,
- "amount": str(line.get_total(discounts).net.amount),
- "taxCode": "PC040156", # FIXME Should fetch taxcode from somewhere and save inside variant/product
- "itemCode": line.variant.sku,
- "description": description[:2000] if description else None,
- }
+ append_line_to_data(
+ data=data,
+ quantity=line.quantity,
+ amount=str(line.get_total(discounts).net.amount),
+ tax_code="PC040156", # FIXME Should fetch taxcode from somewhere and save inside variant/product
+ item_code=line.variant.sku,
+ description=description,
)
if charge_taxes_on_shipping() and checkout.shipping_method:
- data.append(
- {
- "quantity": 1,
- "amount": str(checkout.shipping_method.price.amount),
- "taxCode": common_carrier_code,
- "itemCode": "Shipping",
- }
+ append_line_to_data(
+ data,
+ quantity=1,
+ amount=str(checkout.shipping_method.price.amount),
+ tax_code=common_carrier_code,
+ item_code="Shipping",
+ )
+ return data
+
+
+def get_order_lines_data(order: "Order", discounts=None) -> List[Dict[str, str]]:
+ data = []
+ lines = order.lines.prefetch_related(
+ "variant__product__category",
+ "variant__product__collections",
+ "variant__product__product_type",
+ )
+ for line in lines:
+ append_line_to_data(
+ data=data,
+ quantity=line.quantity,
+ amount=line.variant.get_price(discounts),
+ tax_code="PC040156",
+ item_code=line.variant.sku,
+ description=line.variant.product.description,
+ )
+ if order.is_shipping_required():
+ append_line_to_data(
+ data,
+ quantity=1,
+ amount=str(order.shipping_method.price.amount),
+ tax_code=common_carrier_code,
+ item_code="Shipping",
)
return data
def generate_request_data(
- checkout: "Checkout",
- transaction_token=None,
- transaction_type=TransactionType.ORDER,
+ transaction_type: str,
+ lines: List[Dict[str, Any]],
+ transaction_token: str,
+ address: Dict[str, str],
+ customer_code: Optional[int],
+ customer_email: str,
commit=False,
- discounts=None,
):
-
- address = checkout.shipping_address or checkout.billing_address
- lines = get_lines_data(checkout, discounts)
-
data = {
"companyCode": settings.AVATAX_COMPANY_NAME,
"type": transaction_type,
"lines": lines,
- "code": transaction_token or str(checkout.token),
+ "code": transaction_token,
"date": str(date.today()),
- "customerCode": checkout.user.id if checkout.user else None,
+ "customerCode": customer_code,
# 'salespersonCode'
# 'customerUsageType'
# 'entityUseCode'
@@ -147,12 +204,12 @@ def generate_request_data(
"postalCode": "92614",
},
"shipTo": {
- "line1": address.street_address_1,
- "line2": address.street_address_2,
- "city": address.city,
- "region": address.country_area,
- "country": address.country.code,
- "postalCode": address.postal_code,
+ "line1": address.get("street_address_1"),
+ "line2": address.get("street_address_2"),
+ "city": address.get("city"),
+ "region": address.get("country_area"),
+ "country": address.get("country"),
+ "postalCode": address.get("postal_code"),
},
},
# parameters
@@ -163,25 +220,65 @@ def generate_request_data(
"commit": commit,
# batchCode
"currencyCode": settings.DEFAULT_CURRENCY,
- "email": checkout.email,
+ "email": customer_email,
}
+ return {"createTransactionModel": data}
+
+
+def generate_request_data_from_checkout(
+ checkout: "Checkout",
+ transaction_token=None,
+ transaction_type=TransactionType.ORDER,
+ commit=False,
+ discounts=None,
+):
+
+ address = checkout.shipping_address or checkout.billing_address
+ lines = get_checkout_lines_data(checkout, discounts)
+ data = generate_request_data(
+ transaction_type=transaction_type,
+ lines=lines,
+ transaction_token=transaction_token or str(checkout.token),
+ address=address.as_data(),
+ customer_code=checkout.user.id if checkout.user else None,
+ customer_email=checkout.email,
+ commit=commit,
+ )
return data
-def get_checkout_tax_data(checkout: "Checkout", discounts) -> Dict[str, Any]:
- checkout_cache_key = cache_key + str(checkout.token)
- data = generate_request_data(checkout, discounts=discounts)
- if checkout_needs_new_fetch(data, str(checkout.token)):
- transaction_url = urljoin(get_api_url(), "transactions/create")
+def get_cached_response_or_fetch(data, token_in_cache):
+ """Try to find response in cache. Return cached response if requests data are
+ the same. Fetch new data in other cases"""
+ data_cache_key = cache_key + token_in_cache
+ if taxes_need_new_fetch(data, token_in_cache):
+ transaction_url = urljoin(get_api_url(), "transactions/createoradjust")
print("HIT TO API")
response = api_post_request(transaction_url, data)
if response and "error" not in response:
- cache.set(
- checkout_cache_key,
- (data, response),
- settings.AVATAX_CHECKOUT_CACHE_TIME,
- )
+ cache.set(data_cache_key, (data, response), settings.AVATAX_CACHE_TIME)
else:
- _, response = cache.get(checkout_cache_key)
+ _, response = cache.get(data_cache_key)
+
+ return response
+
+
+def get_checkout_tax_data(checkout: "Checkout", discounts) -> Dict[str, Any]:
+ data = generate_request_data_from_checkout(checkout, discounts=discounts)
+ return get_cached_response_or_fetch(data, str(checkout.token))
+
+def get_order_tax_data(order: "Order", discounts, commit=False) -> Dict[str, Any]:
+ address = order.shipping_address or order.billing_address
+ lines = get_order_lines_data(order, discounts=discounts)
+ data = generate_request_data(
+ transaction_type=TransactionType.INVOICE,
+ lines=lines,
+ transaction_token=order.token,
+ address=address.as_data(),
+ customer_code=order.user.id if order.user else None,
+ customer_email=order.user_email,
+ commit=commit,
+ )
+ response = get_cached_response_or_fetch(data, "order_%s" % order.token)
return response
diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.py
index 62b5039108..b41bb9f101 100644
--- a/saleor/core/taxes/avatax/interface.py
+++ b/saleor/core/taxes/avatax/interface.py
@@ -12,9 +12,13 @@ from ..errors import TaxError
from . import (
TransactionType,
api_post_request,
+ common_carrier_code,
generate_request_data,
+ generate_request_data_from_checkout,
get_api_url,
+ get_cached_response_or_fetch,
get_checkout_tax_data,
+ get_order_tax_data,
validate_checkout,
)
@@ -92,7 +96,7 @@ def postprocess_order_creation_with_taxes(order: "Order"):
discounts = Sale.objects.active(date.today()).prefetch_related(
"products", "categories", "collections"
)
- data = generate_request_data(
+ data = generate_request_data_from_checkout(
checkout,
transaction_token=str(order.token),
transaction_type=TransactionType.INVOICE,
@@ -103,3 +107,27 @@ def postprocess_order_creation_with_taxes(order: "Order"):
# FIXME errors for users (?)
if not response or "error" in response:
raise TaxError(response.get("error", {}).get("message", ""))
+
+
+def get_line_total_gross(checkout_line: "CheckoutLine", discounts):
+ checkout = checkout_line.checkout
+ taxes_data = get_checkout_tax_data(checkout, discounts)
+
+ for line in taxes_data.get("lines", []):
+ if line.get("itemCode") == checkout_line.variant.sku:
+ tax = Decimal(line.get("tax", "0.0"))
+ net = checkout_line.get_total(discounts).net
+ return Money(amount=net.amount + tax, currency=net.currency)
+
+ return checkout_line.get_total(discounts).gross
+
+
+def get_order_line_total_gross(order_line: "OrderLine", discounts):
+ order = order_line.order
+ taxes_data = get_order_tax_data(order, discounts)
+ for line in taxes_data.get("lines", []):
+ if line.get("itemCode") == order_line.variant.sku:
+ tax = Decimal(line.get("tax", "0.0"))
+ net = order_line.variant.get_total(discounts).net
+ return Money(amount=net.amount + tax, currency=net.currency)
+ return order_line.variant.get_total(discounts).gross
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
index b5c403084c..a68bdd78c1 100644
--- a/saleor/core/taxes/interface.py
+++ b/saleor/core/taxes/interface.py
@@ -2,14 +2,13 @@ from collections import defaultdict
from decimal import Decimal
from django.conf import settings
-from prices import TaxedMoney
-
-from . import ZERO_TAXED_MONEY
-from .vatlayer import interface as vatlayer_interface
-from .avatax import interface as avatax_interface
+from prices import Money, TaxedMoney
from ...checkout.models import Checkout
from ...discount.models import SaleQueryset
+from . import ZERO_TAXED_MONEY
+from .avatax import interface as avatax_interface
+from .vatlayer import interface as vatlayer_interface
def get_total_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
@@ -54,3 +53,58 @@ def get_lines_with_taxes(checkout: Checkout, discounts):
return avatax_interface.get_lines_with_taxes(checkout, discounts)
return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
+
+
+def apply_taxes_to_shipping(price: Money, shipping_address: "Address") -> TaxedMoney:
+ """Apply taxes for shiping methods that user can use during checkout"""
+
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.apply_taxes_to_shipping(price, shipping_address)
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ # FIXME
+ pass
+ return TaxedMoney(net=price, gross=price)
+
+
+def get_tax_rate_type_choices():
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.get_tax_rate_type_choices()
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return []
+ return []
+
+
+def get_line_total_gross(checkout_line: "CheckoutLine", discounts):
+ if settings.VATLAYER_ACCESS_KEY:
+ return checkout_line.get_total(discounts) # FIXME
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return avatax_interface.get_line_total_gross(checkout_line, discounts)
+ return checkout_line.get_total(discounts)
+
+
+def get_order_line_total_gross(order_line: "OrderLine", discounts):
+ if settings.VATLAYER_ACCESS_KEY:
+ return order_line.variant.get_price(
+ discounts
+ ) # FIXME unit_price or total_price ?
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return avatax_interface.get_order_line_total_gross(order_line, discounts)
+ return order_line.variant.get_price(discounts) # FIXME unit_price or total_price ?
+
+
+def apply_taxes_to_variant(variant: "ProductVariant", price: Money, country: "Country"):
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.apply_taxes_to_variant(variant, price, country)
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return TaxedMoney(
+ net=price, gross=price
+ ) # FIXME for know we don't know how to get product prices
+ return TaxedMoney(net=price, gross=price)
+
+
+def apply_taxes_to_product(product: "Product", price: Money, country: "Country"):
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.apply_taxes_to_product(product, price, country)
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return TaxedMoney(net=price, gross=price)
+ return TaxedMoney(net=price, gross=price)
diff --git a/saleor/core/taxes/vatlayer/interface.py b/saleor/core/taxes/vatlayer/interface.py
index 9bf1aa3e91..921f9dd4e3 100644
--- a/saleor/core/taxes/vatlayer/interface.py
+++ b/saleor/core/taxes/vatlayer/interface.py
@@ -1,12 +1,20 @@
from collections import defaultdict
from decimal import Decimal
-from django_prices_vatlayer.utils import get_tax_rate
+from django_countries.fields import Country
+from django_prices_vatlayer.utils import get_tax_rate, get_tax_rate_types
from prices import TaxedMoney
+from ....core import TaxRateType # FIXME this should be placed in VatLayer module
from ....discount.models import SaleQueryset
from ....discount.utils import calculate_discounted_price
-from . import get_taxed_shipping_price, get_taxes_for_address
+from . import (
+ DEFAULT_TAX_RATE_NAME,
+ apply_tax_to_price,
+ get_taxed_shipping_price,
+ get_taxes_for_address,
+ get_taxes_for_country,
+)
def get_total_gross(checkout: "Checkout", discounts: SaleQueryset) -> TaxedMoney:
@@ -49,3 +57,33 @@ def get_lines_with_taxes(checkout: "Checkout", discounts):
lines_taxes[line.variant.sku] = price.amount * tax_rate
return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
+
+
+def apply_taxes_to_shipping(price: "Money", shipping_address: "Address"):
+ taxes = get_taxes_for_country(shipping_address.country)
+ return get_taxed_shipping_price(price, taxes)
+
+
+def get_tax_rate_type_choices():
+ rate_types = get_tax_rate_types() + [DEFAULT_TAX_RATE_NAME]
+ translations = dict(TaxRateType.CHOICES)
+ choices = [
+ (rate_name, translations.get(rate_name, "---------"))
+ for rate_name in rate_types
+ ]
+ # sort choices alphabetically by translations
+ return sorted(choices, key=lambda x: x[1])
+
+
+def apply_taxes_to_variant(variant: "ProductVariant", price, country: "Country"):
+ taxes = get_taxes_for_country(country)
+ tax_rate = variant.product.tax_rate or variant.product.product_type.tax_rate
+ return apply_tax_to_price(taxes, tax_rate, price)
+
+
+def apply_taxes_to_product(product: "Product", price: "Money", country: "Country"):
+ taxes = None
+ if country:
+ taxes = get_taxes_for_country(country)
+ tax_rate = product.tax_rate or product.product_type.tax_rate
+ return apply_tax_to_price(taxes, tax_rate, price)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index ce9af47999..c15c5c9262 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -16,6 +16,8 @@ from faker.providers import BaseProvider
from measurement.measures import Weight
from prices import Money
+from saleor.core.taxes.vatlayer import get_taxed_shipping_price, get_taxes_for_country
+
from ...account.models import Address, User
from ...account.utils import store_user_address
from ...checkout import AddressType
@@ -401,6 +403,7 @@ def create_fake_order(discounts, taxes):
shipping_method = ShippingMethod.objects.order_by("?").first()
shipping_price = shipping_method.price
+ shipping_price = get_taxed_shipping_price(shipping_price, taxes)
order_data.update(
{"shipping_method_name": shipping_method.name, "shipping_price": shipping_price}
)
@@ -439,7 +442,7 @@ def create_users(how_many=10):
def create_orders(how_many=10):
- taxes = None
+ taxes = get_taxes_for_country(Country(settings.DEFAULT_COUNTRY))
discounts = Sale.objects.active(date.today()).prefetch_related(
"products", "categories", "collections"
)
diff --git a/saleor/core/views.py b/saleor/core/views.py
index 8f6a8a961d..a4a00c7f05 100644
--- a/saleor/core/views.py
+++ b/saleor/core/views.py
@@ -20,7 +20,7 @@ def home(request):
products_with_availability(
products,
discounts=request.discounts,
- taxes=request.taxes,
+ country=request.country,
local_currency=request.currency,
)
)
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 3ade133564..bb6ae53e0b 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -633,7 +633,7 @@ class AddVariantToOrderForm(forms.Form):
variant = self.cleaned_data.get("variant")
quantity = self.cleaned_data.get("quantity")
line = add_variant_to_order(
- self.order, variant, quantity, self.discounts, self.taxes
+ self.order, variant, quantity, self.discounts, self.taxes # FIXME
)
events.draft_order_added_products_event(
order=self.order, user=user, order_lines=[(line.quantity, line)]
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index 501d0b71f0..e78c32fe21 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -314,7 +314,7 @@ def orderline_cancel(request, order_pk, line_pk):
def add_variant_to_order(request, order_pk):
"""Add variant in given quantity to an order."""
order = get_object_or_404(Order.objects.drafts(), pk=order_pk)
- taxes = None
+ taxes = None # FIXME
form = AddVariantToOrderForm(
request.POST or None, order=order, discounts=request.discounts, taxes=taxes
)
@@ -432,7 +432,7 @@ def order_customer_remove(request, order_pk):
@permission_required("order.manage_orders")
def order_shipping_edit(request, order_pk):
order = get_object_or_404(Order.objects.drafts(), pk=order_pk)
- taxes = None
+ taxes = None # FIXME
form = OrderShippingForm(request.POST or None, instance=order, taxes=taxes)
status = 200
if form.is_valid():
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index 22689d1713..a2b1379cae 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -7,12 +7,10 @@ from django.forms.widgets import CheckboxSelectMultiple
from django.utils.encoding import smart_text
from django.utils.text import slugify
from django.utils.translation import pgettext_lazy
-from django_prices_vatlayer.utils import get_tax_rate_types
from mptt.forms import TreeNodeChoiceField
-from ...core import TaxRateType
from ...core.taxes import include_taxes_in_prices
-from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME # FIXME
+from ...core.taxes.interface import get_tax_rate_type_choices
from ...core.weight import WeightField
from ...product.models import (
Attribute,
@@ -68,17 +66,6 @@ class ProductTypeSelectorForm(forms.Form):
)
-def get_tax_rate_type_choices():
- rate_types = get_tax_rate_types() + [DEFAULT_TAX_RATE_NAME]
- translations = dict(TaxRateType.CHOICES)
- choices = [
- (rate_name, translations.get(rate_name, "---------"))
- for rate_name in rate_types
- ]
- # sort choices alphabetically by translations
- return sorted(choices, key=lambda x: x[1])
-
-
class ProductTypeForm(forms.ModelForm):
tax_rate = forms.ChoiceField(
required=False, label=pgettext_lazy("Product type tax rate type", "Tax rate")
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 8093c82186..7ced6de9a8 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -55,7 +55,7 @@ def product_details(request, pk):
variants = product.variants.all()
images = product.images.all()
availability = get_product_availability(
- product, discounts=request.discounts, taxes=request.taxes
+ product, discounts=request.discounts, country=request.country
)
sale_price = availability.price_range_undiscounted
discounted_price = availability.price_range
diff --git a/saleor/dashboard/taxes/views.py b/saleor/dashboard/taxes/views.py
index cf3f3519fd..c61d5637e7 100644
--- a/saleor/dashboard/taxes/views.py
+++ b/saleor/dashboard/taxes/views.py
@@ -5,6 +5,7 @@ from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
+from django.http import HttpResponseNotFound
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.translation import pgettext_lazy
@@ -21,24 +22,31 @@ from ...dashboard.views import staff_member_required
logger = logging.getLogger(__name__)
+# FIXME these views belong to vatlayer module.
+
@staff_member_required
def tax_list(request):
- taxes = VAT.objects.order_by("country_code")
- tax_filter = TaxFilter(request.GET, queryset=taxes)
- taxes = get_paginator_items(
- tax_filter.qs, settings.DASHBOARD_PAGINATE_BY, request.GET.get("page")
- )
- ctx = {
- "taxes": taxes,
- "filter_set": tax_filter,
- "is_empty": not tax_filter.queryset.exists(),
- }
+ if settings.VATLAYER_ACCESS_KEY:
+ taxes = VAT.objects.order_by("country_code")
+ tax_filter = TaxFilter(request.GET, queryset=taxes)
+ taxes = get_paginator_items(
+ tax_filter.qs, settings.DASHBOARD_PAGINATE_BY, request.GET.get("page")
+ )
+ ctx = {
+ "taxes": taxes,
+ "filter_set": tax_filter,
+ "is_empty": not tax_filter.queryset.exists(),
+ }
+ else:
+ ctx = {"taxes": [], "filter_set": None, "is_empty": True}
return TemplateResponse(request, "dashboard/taxes/list.html", ctx)
@staff_member_required
def tax_details(request, country_code):
+ if not settings.VATLAYER_ACCESS_KEY:
+ return HttpResponseNotFound()
tax = get_object_or_404(VAT, country_code=country_code)
tax_rates = get_taxes_for_country(Country(country_code))
translations = dict(TaxRateType.CHOICES)
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 96b2e64611..547f0c6b60 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -22,6 +22,7 @@ from ...checkout.utils import (
from ...core import analytics
from ...core.exceptions import InsufficientStock
from ...core.taxes.errors import TaxError
+from ...core.taxes.interface import get_subtotal_gross
from ...discount import models as voucher_model
from ...payment import PaymentError
from ...payment.utils import gateway_process_payment
@@ -36,9 +37,7 @@ from ..shipping.types import ShippingMethod
from .types import Checkout, CheckoutLine
-def clean_shipping_method(
- checkout, method, discounts, taxes, country_code=None, remove=True
-):
+def clean_shipping_method(checkout, method, discounts, country_code=None, remove=True):
# FIXME Add tests for this function
if not method:
return None
@@ -53,7 +52,7 @@ def clean_shipping_method(
)
valid_methods = ShippingMethodModel.objects.applicable_shipping_methods(
- price=checkout.get_subtotal(discounts, taxes).gross.amount,
+ price=get_subtotal_gross(checkout, discounts).gross.amount,
weight=checkout.get_total_weight(),
country_code=country_code or checkout.shipping_address.country.code,
)
@@ -239,7 +238,6 @@ class CheckoutLinesAdd(BaseMutation):
checkout=checkout,
method=checkout.shipping_method,
discounts=info.context.discounts,
- taxes=None,
)
if variants and quantities:
@@ -291,7 +289,6 @@ class CheckoutLineDelete(BaseMutation):
checkout=checkout,
method=checkout.shipping_method,
discounts=info.context.discounts,
- taxes=None,
)
recalculate_checkout_discount(
@@ -370,7 +367,6 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
checkout=checkout,
method=checkout.shipping_method,
discounts=info.context.discounts,
- taxes=None,
)
with transaction.atomic():
@@ -461,7 +457,6 @@ class CheckoutShippingMethodUpdate(BaseMutation):
checkout=checkout,
method=shipping_method,
discounts=info.context.discounts,
- taxes=info.context.taxes,
remove=False,
)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 60220e9331..87e8d7bbbd 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -3,6 +3,12 @@ import graphene_django_optimizer as gql_optimizer
from django.conf import settings
from ...checkout import models
+from ...core.taxes.interface import (
+ get_line_total_gross,
+ get_shipping_gross,
+ get_subtotal_gross,
+ get_total_gross,
+)
from ..core.connection import CountableDjangoObjectType
from ..core.types.money import TaxedMoney
from ..order.utils import applicable_shipping_methods
@@ -27,8 +33,9 @@ class CheckoutLine(CountableDjangoObjectType):
filter_fields = ["id"]
def resolve_total_price(self, info):
- taxes = None # FIXME
- return self.get_total(discounts=info.context.discounts, taxes=taxes)
+ return get_line_total_gross(
+ checkout_line=self, discounts=info.context.discounts
+ )
def resolve_requires_shipping(self, *_args):
return self.is_shipping_required()
@@ -98,16 +105,13 @@ class Checkout(CountableDjangoObjectType):
filter_fields = ["token"]
def resolve_total_price(self, info):
- taxes = None # FIXME
- return self.get_total(discounts=info.context.discounts, taxes=taxes)
+ return get_total_gross(checkout=self, discounts=info.context.discounts)
- def resolve_subtotal_price(self, *_args):
- taxes = None
- return self.get_subtotal(taxes=taxes)
+ def resolve_subtotal_price(self, info):
+ return get_subtotal_gross(checkout=self, discounts=info.context.discounts)
- def resolve_shipping_price(self, *_args):
- taxes = None
- return self.get_shipping_price(taxes=taxes)
+ def resolve_shipping_price(self, info):
+ return get_shipping_gross(checkout=self, discounts=info.context.discounts)
def resolve_lines(self, *_args):
return self.lines.prefetch_related("variant")
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index c2d74f8a5d..35546a418b 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -2,6 +2,7 @@ import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
+from ...core.taxes.interface import get_total_gross
from ...core.utils import get_client_ip
from ...payment import PaymentError, models
from ...payment.utils import (
@@ -77,10 +78,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
raise ValidationError(
{"billing_address": "No billing address associated with this checkout."}
)
-
- checkout_total = checkout.get_total(
- discounts=info.context.discounts, taxes=None
- )
+ checkout_total = get_total_gross(discounts=info.context.discounts)
amount = data.get("amount", checkout_total)
if amount < checkout_total.gross.amount:
raise ValidationError(
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 550881e6a8..b6c61d5836 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -442,7 +442,7 @@ class Product(CountableDjangoObjectType):
def resolve_pricing(self, info):
context = info.context
availability = get_product_availability(
- self, context.discounts, context.taxes, context.currency
+ self, context.discounts, context.country, context.currency
)
return ProductPricingInfo(**availability._asdict())
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index d890c86e39..877705ac8b 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -9,6 +9,7 @@ from prices import Money, TaxedMoney
from ..account.utils import store_user_address
from ..checkout import AddressType
from ..core.taxes import ZERO_MONEY
+from ..core.taxes.interface import get_order_line_total_gross
from ..core.weight import zero_weight
from ..dashboard.order.utils import get_voucher_discount_for_order
from ..discount.models import NotApplicable
@@ -153,11 +154,10 @@ def recalculate_order_weight(order):
def update_order_prices(order, discounts):
"""Update prices in order with given discounts and proper taxes."""
- taxes = None
-
for line in order:
if line.variant:
- line.unit_price = line.variant.get_price(discounts, taxes)
+ price = get_order_line_total_gross(line, discounts)
+ line.unit_price = price
line.tax_rate = 0
line.save()
@@ -267,6 +267,7 @@ def add_variant_to_order(
if not allow_overselling:
variant.check_quantity(quantity)
+ # FIXME maybe something more prettier ?
unit_price_net = variant.get_price(discounts).net
unit_price_gross = Money(
amount=unit_price_net.amount + unit_tax, currency=unit_price_net.currency
diff --git a/saleor/product/models.py b/saleor/product/models.py
index e6bd498f88..efa9c15757 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -15,7 +15,7 @@ from django_prices.templatetags import prices_i18n
from measurement.measures import Weight
from mptt.managers import TreeManager
from mptt.models import MPTTModel
-from prices import TaxedMoney, TaxedMoneyRange
+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
@@ -24,6 +24,7 @@ from saleor.core.utils import build_absolute_uri
from ..core import TaxRateType
from ..core.exceptions import InsufficientStock
from ..core.models import PublishableModel, SortableModel
+from ..core.taxes import interface as tax_interface
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
from ..discount.utils import calculate_discounted_price
@@ -178,18 +179,12 @@ class Product(SeoModel, PublishableModel):
images = list(self.images.all())
return images[0] if images else None
- def get_price_range(self, discounts=None, taxes=None):
+ def get_price_range(self, discounts=None, country=None):
if self.variants.all():
- prices = [
- variant.get_price(discounts=discounts, taxes=taxes) for variant in self
- ]
- return TaxedMoneyRange(min(prices), max(prices))
+ prices = [variant.get_price(discounts, country) for variant in self]
+ return MoneyRange(min(prices, max(prices)))
price = calculate_discounted_price(self, self.price, discounts)
- if not self.charge_taxes:
- taxes = None
- tax_rate = self.tax_rate or self.product_type.tax_rate
- price = TaxedMoney(net=price, gross=price)
- return TaxedMoneyRange(start=price, stop=price)
+ return MoneyRange(start=price, stop=price)
class ProductTranslation(SeoModelTranslation):
@@ -284,12 +279,8 @@ class ProductVariant(models.Model):
else self.product.price
)
- def get_price(self, discounts=None, taxes=None):
- price = calculate_discounted_price(self.product, self.base_price, discounts)
- if not self.product.charge_taxes:
- taxes = None
- tax_rate = self.product.tax_rate or self.product.product_type.tax_rate
- return TaxedMoney(net=price, gross=price)
+ def get_price(self, discounts=None):
+ return calculate_discounted_price(self.product, self.base_price, discounts)
def get_weight(self):
return self.weight or self.product.weight or self.product.product_type.weight
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index d6d414a90a..baac77000f 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -136,7 +136,7 @@ def get_product_list_context(request, filter_set):
)
products_and_availability = list(
products_with_availability(
- products_paginated, request.discounts, request.taxes, request.currency
+ products_paginated, request.discounts, request.country, request.currency
)
)
now_sorted_by = get_now_sorted_by(filter_set)
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index b2607e3784..eb55f7ac1a 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -7,6 +7,7 @@ from prices import TaxedMoneyRange
from saleor.graphql.core.types import MoneyRange
from saleor.product.models import Product, ProductVariant
+from ...core.taxes.interface import apply_taxes_to_product
from ...core.utils import to_local_currency
from .. import ProductAvailabilityStatus, VariantAvailabilityStatus
@@ -37,11 +38,11 @@ VariantAvailability = namedtuple(
)
-def products_with_availability(products, discounts, taxes, local_currency):
+def products_with_availability(products, discounts, country, local_currency):
for product in products:
yield (
product,
- get_product_availability(product, discounts, taxes, local_currency),
+ get_product_availability(product, discounts, country, local_currency),
)
@@ -107,11 +108,19 @@ def _get_product_price_range(
def get_product_availability(
- product: Product, discounts=None, taxes=None, local_currency=None
+ product: Product, discounts=None, country=None, local_currency=None
) -> ProductAvailability:
- discounted = product.get_price_range(discounts=discounts, taxes=taxes)
- undiscounted = product.get_price_range(taxes=taxes)
+ discounted_net_range = product.get_price_range(discounts=discounts)
+ undiscounted_net_range = product.get_price_range()
+ discounted = TaxedMoneyRange(
+ start=apply_taxes_to_product(product, discounted_net_range.start, country),
+ stop=apply_taxes_to_product(product, discounted_net_range.stop, country),
+ )
+ undiscounted = TaxedMoneyRange(
+ start=apply_taxes_to_product(product, undiscounted_net_range.start, country),
+ stop=apply_taxes_to_product(product, undiscounted_net_range.stop, country),
+ )
discount = _get_total_discount(undiscounted, discounted)
price_range_local, discount_local_currency = _get_product_price_range(
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index 256a52b8f7..2211c5e9a7 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -3,13 +3,14 @@ from collections import defaultdict
from django_prices.templatetags import prices_i18n
from ...core.taxes import display_gross_prices
+from ...core.taxes.interface import apply_taxes_to_variant
from ...core.utils import to_local_currency
from ...seo.schema.product import variant_json_ld
from .availability import get_product_availability
-def get_variant_picker_data(product, discounts=None, taxes=None, local_currency=None):
- availability = get_product_availability(product, discounts, taxes, local_currency)
+def get_variant_picker_data(product, discounts=None, country=None, local_currency=None):
+ availability = get_product_availability(product, discounts, country, local_currency)
variants = product.variants.all()
data = {"variantAttributes": [], "variants": []}
@@ -19,8 +20,10 @@ def get_variant_picker_data(product, discounts=None, taxes=None, local_currency=
filter_available_variants = defaultdict(list)
for variant in variants:
- price = variant.get_price(discounts, taxes)
- price_undiscounted = variant.get_price(taxes=taxes)
+ price = apply_taxes_to_variant(variant, variant.get_price(discounts), country)
+ price_undiscounted = apply_taxes_to_variant(
+ variant, variant.get_price(), country
+ )
if local_currency:
price_local_currency = to_local_currency(price, local_currency)
else:
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 922cc6d3d8..fb0ea42d1e 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -78,12 +78,12 @@ def product_details(request, slug, product_id, form=None):
availability = get_product_availability(
product,
discounts=request.discounts,
- taxes=request.taxes,
+ country=request.country,
local_currency=request.currency,
)
product_images = get_product_images(product)
variant_picker_data = get_variant_picker_data(
- product, request.discounts, request.taxes, request.currency
+ product, request.discounts, request.country, request.currency
)
product_attributes = get_product_attributes_data(product)
# show_variant_picker determines if variant picker is used or select input
diff --git a/saleor/search/views.py b/saleor/search/views.py
index 2050f85084..a9ceaade3d 100644
--- a/saleor/search/views.py
+++ b/saleor/search/views.py
@@ -23,7 +23,7 @@ def evaluate_search_query(form, request):
return products_with_availability(
results,
discounts=request.discounts,
- taxes=request.taxes,
+ country=request.country,
local_currency=request.currency,
)
diff --git a/saleor/settings.py b/saleor/settings.py
index e6ff4e3c04..38ed695c58 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -357,7 +357,7 @@ AVATAX_USERNAME_OR_ACCOUNT = os.environ.get("AVATAX_USERNAME_OR_ACCOUNT")
AVATAX_PASSWORD_OR_LICENSE = os.environ.get("AVATAX_PASSWORD_OR_LICENSE")
AVATAX_USE_SANDBOX = os.environ.get("AVATAX_USE_SANDBOX", True)
AVATAX_COMPANY_NAME = os.environ.get("AVATAX_COMPANY_NAME", "DEFAULT")
-AVATAX_CHECKOUT_CACHE_TIME = os.environ.get("AVATAX_CHECKOUT_CACHE_TIME", 60 * 60)
+AVATAX_CACHE_TIME = os.environ.get("AVATAX_CACHE_TIME", 60 * 60)
AVATAX_TAX_CODE_CACHE_TIME = os.environ.get("AVATAX_TAX_CODE_CACHE_TIME", 24 * 60 * 60)
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index a23b46c22f..0146ac90c5 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -159,7 +159,8 @@ class ShippingMethod(models.Model):
),
)
- def get_total(self, taxes=None):
+ def get_total(self, country=None):
+
return TaxedMoney(net=self.price, gross=self.price)
def get_ajax_label(self):