Skip to content

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

Move avatax unconfigurable settings to avatax module. Clean up taxes modules. Revmoe ZERO_TAXED_MONEY adn ZERO_MONEY

Maciej Korycinskia90f64212977
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 34b9f6e397..3f4698ad49 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -11,7 +11,7 @@ from django.utils.encoding import smart_str
from django_prices.models import MoneyField
from ..account.models import Address
-from ..core.taxes import ZERO_MONEY, zero_money
+from ..core.taxes import zero_money
from ..core.weight import zero_weight
from ..giftcard.models import GiftCard
from ..shipping.models import ShippingMethod
@@ -104,7 +104,7 @@ class Checkout(models.Model):
def get_subtotal(self, discounts=None):
"""Return the total cost of the checkout prior to shipping."""
subtotals = (line.get_total(discounts) for line in self)
- return sum(subtotals, zero_money())
+ return sum(subtotals, zero_money(currency=settings.DEFAULT_CURRENCY))
def get_total(self, discounts=None):
"""Return the total cost of the checkout."""
@@ -113,14 +113,14 @@ class Checkout(models.Model):
+ self.get_shipping_price()
- self.discount_amount
)
- return max(total, ZERO_MONEY)
+ return max(total, zero_money(total.currency))
def get_total_gift_cards_balance(self):
"""Return the total balance of the gift cards assigned to the checkout."""
balance = self.gift_cards.aggregate(models.Sum("current_balance"))[
"current_balance__sum"
]
- return balance or ZERO_MONEY
+ return balance or zero_money(currency=settings.DEFAULT_CURRENCY)
def get_total_weight(self):
# Cannot use `sum` as it parses an empty Weight to an int
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index a69414fa91..7147b5f404 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -16,15 +16,15 @@ from ..account.forms import get_address_form
from ..account.models import Address, User
from ..account.utils import store_user_address
from ..core.exceptions import InsufficientStock
-from ..core.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
+from ..core.taxes import zero_money, zero_taxed_money
from ..core.taxes.interface import (
calculate_checkout_line_total,
calculate_checkout_shipping,
calculate_checkout_subtotal,
calculate_checkout_total,
- checkout_are_taxes_handled,
postprocess_order_creation,
preprocess_order_creation,
+ taxes_are_enabled,
)
from ..core.utils import to_local_currency
from ..core.utils.promo_code import (
@@ -665,7 +665,7 @@ def get_checkout_context(checkout, discounts, currency=None, shipping_range=None
calculate_checkout_total(checkout=checkout, discounts=discounts)
- checkout.get_total_gift_cards_balance()
)
- checkout_total = max(checkout_total, ZERO_TAXED_MONEY)
+ checkout_total = max(checkout_total, zero_taxed_money(checkout_total.currency))
checkout_subtotal = calculate_checkout_subtotal(checkout, discounts)
shipping_price = calculate_checkout_shipping(checkout, discounts)
@@ -678,7 +678,7 @@ def get_checkout_context(checkout, discounts, currency=None, shipping_range=None
context = {
"checkout": checkout,
- "checkout_are_taxes_handled": checkout_are_taxes_handled(),
+ "checkout_are_taxes_handled": taxes_are_enabled(),
"checkout_lines": [
(line, calculate_checkout_line_total(line, discounts)) for line in checkout
],
@@ -889,7 +889,7 @@ def remove_voucher_from_checkout(checkout: Checkout):
checkout.voucher_code = None
checkout.discount_name = None
checkout.translated_discount_name = None
- checkout.discount_amount = ZERO_MONEY
+ checkout.discount_amount = zero_money()
checkout.save(
update_fields=[
"voucher_code",
@@ -1044,7 +1044,7 @@ def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) ->
calculate_checkout_total(checkout=checkout, discounts=discounts)
- checkout.get_total_gift_cards_balance()
)
- total = max(total, ZERO_TAXED_MONEY)
+ total = max(total, zero_taxed_money(total.currency))
shipping_total = calculate_checkout_shipping(checkout, discounts)
order_data.update(_process_shipping_data_for_order(checkout, shipping_total))
@@ -1142,7 +1142,9 @@ def is_fully_paid(checkout: Checkout, discounts):
calculate_checkout_total(checkout=checkout, discounts=discounts)
- checkout.get_total_gift_cards_balance()
)
- checkout_total = max(checkout_total, ZERO_TAXED_MONEY).gross
+ checkout_total = max(
+ checkout_total, zero_taxed_money(checkout_total.currency)
+ ).gross
return total_paid >= checkout_total.amount
diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.py
index fdccd89a8e..cf07a7538c 100644
--- a/saleor/checkout/views/__init__.py
+++ b/saleor/checkout/views/__init__.py
@@ -5,9 +5,9 @@ from django.template.response import TemplateResponse
from ...account.forms import LoginForm
from ...core.taxes import (
- ZERO_TAXED_MONEY,
get_display_price,
interface as tax_interface,
+ zero_taxed_money,
)
from ...core.utils import format_money, get_user_shipping_country, to_local_currency
from ...shipping.utils import get_shipping_price_estimate
@@ -218,7 +218,8 @@ def update_checkout_line(request, checkout, variant_id):
checkout.refresh_from_db()
# Refresh obj from db and confirm that checkout still has this line
checkout_line = checkout.lines.filter(variant_id=variant_id).first()
- line_total = ZERO_TAXED_MONEY
+ currency = checkout.get_total().currency
+ line_total = zero_taxed_money(currency)
if checkout_line:
line_total = tax_interface.calculate_checkout_line_total(
checkout_line, discounts
diff --git a/saleor/core/taxes/__init__.py b/saleor/core/taxes/__init__.py
index 146700aedd..e1c0788f47 100644
--- a/saleor/core/taxes/__init__.py
+++ b/saleor/core/taxes/__init__.py
@@ -5,14 +5,15 @@ from django.conf import settings
from django.contrib.sites.models import Site
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-ZERO_MONEY = Money(0, settings.DEFAULT_CURRENCY)
-ZERO_TAXED_MONEY = TaxedMoney(net=ZERO_MONEY, gross=ZERO_MONEY)
+def zero_money(currency=settings.DEFAULT_CURRENCY):
+ """Function used as a model's default."""
+ return Money(0, currency)
-def zero_money():
- """Function used as a model's default."""
- return ZERO_MONEY
+def zero_taxed_money(currency=settings.DEFAULT_CURRENCY):
+ zero = zero_money(currency)
+ return TaxedMoney(net=zero, gross=zero)
def include_taxes_in_prices():
@@ -44,7 +45,7 @@ def get_display_price(
return base
-@dataclass
+@dataclass(frozen=True)
class TaxType:
"""Dataclass for unifying tax type object that comes from tax gateway"""
diff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/taxes/avatax/__init__.py
index 3a9bf84588..b41d5e9499 100644
--- a/saleor/core/taxes/avatax/__init__.py
+++ b/saleor/core/taxes/avatax/__init__.py
@@ -18,10 +18,16 @@ if TYPE_CHECKING:
from ....checkout.models import Checkout
from ....order.models import Order
-META_FIELD = "avatax"
-
logger = logging.getLogger(__name__)
+META_FIELD = "avatax"
+CACHE_TIME = 60 * 60
+TAX_CODES_CACHE_TIME = 60 * 60 * 24 * 7
+COMMON_CARRIER_CODE = "FR020100"
+CACHE_KEY = "avatax_request_id_"
+TAX_CODES_CACHE_KEY = "avatax_tax_codes_cache_key"
+TIMEOUT = 5
+
class TransactionType:
INVOICE = "SalesInvoice"
@@ -57,7 +63,7 @@ def api_post_request(
) -> Dict[str, Any]:
try:
auth = HTTPBasicAuth(username, password)
- response = requests.post(url, auth=auth, data=json.dumps(data), timeout=2)
+ response = requests.post(url, auth=auth, data=json.dumps(data), timeout=TIMEOUT)
logger.debug("Hit to Avatax to calculate taxes %s", url)
except requests.exceptions.RequestException:
logger.warning("Fetching taxes failed %s", url)
@@ -72,7 +78,7 @@ def api_get_request(
):
try:
auth = HTTPBasicAuth(username, password)
- response = requests.get(url, auth=auth, timeout=2)
+ response = requests.get(url, auth=auth, timeout=TIMEOUT)
logger.debug("[GET] Hit to %s", url)
except requests.exceptions.RequestException:
logger.warning("Failed to fetch data from %s", url)
@@ -80,7 +86,7 @@ def api_get_request(
return response.json()
-def validate_order(order: "Order") -> bool:
+def _validate_order(order: "Order") -> bool:
"""Validate if checkout object contains enough information to generate a request to
avatax"""
if not order.lines.count():
@@ -98,7 +104,7 @@ def validate_order(order: "Order") -> bool:
return True
-def validate_checkout(checkout: "Checkout") -> bool:
+def _validate_checkout(checkout: "Checkout") -> bool:
"""Validate if checkout object contains enough information to generate a request to
avatax"""
if not checkout.lines.count():
@@ -116,11 +122,17 @@ def validate_checkout(checkout: "Checkout") -> bool:
return True
+def _retrieve_from_cache(token):
+ taxes_cache_key = CACHE_KEY + token
+ cached_data = cache.get(taxes_cache_key)
+ return cached_data
+
+
def checkout_needs_new_fetch(data, checkout_token: str) -> bool:
"""We store the response from avatax for checkout object for given time. If object
doesn't exist in cache or something has changed, then we fetch data from avatax."""
- checkout_cache_key = settings.AVATAX_CACHE_KEY + checkout_token
- cached_checkout = cache.get(checkout_cache_key)
+
+ cached_checkout = _retrieve_from_cache(checkout_token)
if not cached_checkout:
return True
@@ -134,8 +146,7 @@ def checkout_needs_new_fetch(data, checkout_token: str) -> bool:
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 = settings.AVATAX_CACHE_KEY + taxes_token
- cached_data = cache.get(taxes_cache_key)
+ cached_data = _retrieve_from_cache(taxes_token)
if not cached_data:
return True
@@ -197,7 +208,7 @@ def get_checkout_lines_data(
data,
quantity=1,
amount=str(checkout.shipping_method.price.amount),
- tax_code=settings.AVATAX_COMMON_CARRIER_CODE,
+ tax_code=COMMON_CARRIER_CODE,
item_code="Shipping",
)
return data
@@ -230,7 +241,7 @@ def get_order_lines_data(order: "Order") -> List[Dict[str, str]]:
data,
quantity=1,
amount=order.shipping_method.price.amount,
- tax_code=settings.AVATAX_COMMON_CARRIER_CODE,
+ tax_code=COMMON_CARRIER_CODE,
item_code="Shipping",
)
return data
@@ -298,6 +309,9 @@ def generate_request_data_from_checkout(
address = checkout.shipping_address or checkout.billing_address
lines = get_checkout_lines_data(checkout, discounts)
+
+ # FIXME after we introduce multicurrency this should be taken from Checkout obj
+ currency = checkout.get_subtotal().currency
data = generate_request_data(
transaction_type=transaction_type,
lines=lines,
@@ -306,6 +320,7 @@ def generate_request_data_from_checkout(
customer_code=checkout.user.id if checkout.user else 0,
customer_email=checkout.email,
commit=commit,
+ currency=currency,
)
return data
@@ -313,12 +328,12 @@ def generate_request_data_from_checkout(
def get_cached_response_or_fetch(data, token_in_cache, force_refresh=False):
"""Try to find response in cache. Return cached response if requests data are
the same. Fetch new data in other cases"""
- data_cache_key = settings.AVATAX_CACHE_KEY + token_in_cache
+ data_cache_key = CACHE_KEY + token_in_cache
if taxes_need_new_fetch(data, token_in_cache) or force_refresh:
transaction_url = urljoin(get_api_url(), "transactions/createoradjust")
response = api_post_request(transaction_url, data)
if response and "error" not in response:
- cache.set(data_cache_key, (data, response), settings.AVATAX_CACHE_TIME)
+ cache.set(data_cache_key, (data, response), CACHE_TIME)
else:
# cache failed response to limit hits to avatax.
cache.set(data_cache_key, (data, response), 10)
@@ -349,6 +364,7 @@ def get_order_tax_data(
customer_code=order.user.id if order.user else None,
customer_email=order.user_email,
commit=commit,
+ currency=order.total.currency,
)
response = get_cached_response_or_fetch(
data, "order_%s" % order.token, force_refresh
@@ -366,18 +382,16 @@ def generate_tax_codes_dict(
return tax_codes
-def get_cached_tax_codes_or_fetch(
- cache_time: int = settings.AVATAX_TAX_CODES_CACHE_TIME
-):
+def get_cached_tax_codes_or_fetch(cache_time: int = TAX_CODES_CACHE_TIME):
"""Try to get cached tax codes. If cache is empty fetch the newest taxcodes from
avatax"""
- tax_codes = cache.get(settings.AVATAX_TAX_CODES_CACHE_KEY, {})
+ tax_codes = cache.get(TAX_CODES_CACHE_KEY, {})
if not tax_codes:
tax_codes_url = urljoin(get_api_url(), "definitions/taxcodes")
response = api_get_request(tax_codes_url)
if response and "error" not in response:
tax_codes = generate_tax_codes_dict(response)
- cache.set(settings.AVATAX_TAX_CODES_CACHE_KEY, tax_codes, cache_time)
+ cache.set(TAX_CODES_CACHE_KEY, tax_codes, cache_time)
return tax_codes
diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.py
index 9f669a3690..383688b71f 100644
--- a/saleor/core/taxes/avatax/interface.py
+++ b/saleor/core/taxes/avatax/interface.py
@@ -7,20 +7,20 @@ from django.conf import settings
from prices import Money, TaxedMoney
from ....checkout import models as checkout_models
-from .. import ZERO_TAXED_MONEY, TaxType
+from .. import TaxType, zero_taxed_money
from ..errors import TaxError
from . import (
META_FIELD,
CustomerErrors,
TransactionType,
+ _validate_checkout,
+ _validate_order,
api_post_request,
generate_request_data_from_checkout,
get_api_url,
get_cached_tax_codes_or_fetch,
get_checkout_tax_data,
get_order_tax_data,
- validate_checkout,
- validate_order,
)
if TYPE_CHECKING:
@@ -34,7 +34,7 @@ def calculate_checkout_total(
checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]
):
checkout_total = checkout.get_total(discounts=discounts)
- if not validate_checkout(checkout):
+ if not _validate_checkout(checkout):
return TaxedMoney(net=checkout_total, gross=checkout_total)
response = get_checkout_tax_data(checkout, discounts)
if not response or "error" in response:
@@ -49,14 +49,14 @@ def calculate_checkout_total(
voucher_amount = checkout.discount_amount
if voucher_amount:
total -= voucher_amount
- return max(total, ZERO_TAXED_MONEY)
+ return max(total, zero_taxed_money(total.currency))
def calculate_checkout_subtotal(
checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]
):
sub_total = checkout.get_subtotal(discounts)
- if not validate_checkout(checkout):
+ if not _validate_checkout(checkout):
return TaxedMoney(net=sub_total, gross=sub_total)
response = get_checkout_tax_data(checkout, discounts)
@@ -81,7 +81,7 @@ def calculate_checkout_shipping(
checkout: "checkout_models.Checkout", discounts: List["DiscountInfo"]
):
shipping_price = checkout.get_shipping_price()
- if not validate_checkout(checkout):
+ if not _validate_checkout(checkout):
return TaxedMoney(net=shipping_price, gross=shipping_price)
response = get_checkout_tax_data(checkout, discounts)
@@ -143,7 +143,7 @@ def calculate_checkout_line_total(
):
checkout = checkout_line.checkout
total = checkout_line.get_total(discounts)
- if not validate_checkout(checkout):
+ if not _validate_checkout(checkout):
return TaxedMoney(net=total, gross=total)
taxes_data = get_checkout_tax_data(checkout, discounts)
currency = taxes_data.get("currencyCode")
@@ -161,7 +161,7 @@ def calculate_checkout_line_total(
def calculate_order_line_unit(order_line: "OrderLine"):
order = order_line.order
- if validate_order(order):
+ if _validate_order(order):
taxes_data = get_order_tax_data(order)
currency = taxes_data.get("currencyCode")
for line in taxes_data.get("lines", []):
@@ -176,8 +176,8 @@ def calculate_order_line_unit(order_line: "OrderLine"):
def calculate_order_shipping(order: "Order"):
- if not validate_order(order):
- return ZERO_TAXED_MONEY
+ if not _validate_order(order):
+ return zero_taxed_money(order.total.currency)
taxes_data = get_order_tax_data(order, False)
currency = taxes_data.get("currencyCode")
for line in taxes_data.get("lines", []):
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
index 2a615e2924..dd3c36789c 100644
--- a/saleor/core/taxes/interface.py
+++ b/saleor/core/taxes/interface.py
@@ -4,7 +4,7 @@ from django.conf import settings
from django_countries.fields import Country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-from . import ZERO_TAXED_MONEY, TaxType
+from . import TaxType
from .avatax import interface as avatax_interface
from .vatlayer import interface as vatlayer_interface
@@ -47,14 +47,16 @@ def calculate_checkout_shipping(
checkout: "Checkout", discounts: List["DiscountInfo"]
) -> TaxedMoney:
"""Calculate shipping gross for checkout"""
+ total = checkout.get_shipping_price()
+ total = TaxedMoney(net=total, gross=total)
if not checkout.shipping_method:
- return ZERO_TAXED_MONEY
+ return total
if settings.VATLAYER_ACCESS_KEY:
return vatlayer_interface.calculate_checkout_shipping(checkout, discounts)
elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return avatax_interface.calculate_checkout_shipping(checkout, discounts)
- total = checkout.get_shipping_price()
- return TaxedMoney(net=total, gross=total)
+
+ return total
def calculate_order_shipping(order: "Order") -> TaxedMoney:
@@ -131,7 +133,7 @@ def show_taxes_on_storefront() -> bool:
return False
-def checkout_are_taxes_handled() -> bool:
+def taxes_are_enabled() -> bool:
if settings.VATLAYER_ACCESS_KEY:
return True
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
diff --git a/saleor/core/taxes/vatlayer/interface.py b/saleor/core/taxes/vatlayer/interface.py
index a1a18b5ae1..c1a1ee2c47 100644
--- a/saleor/core/taxes/vatlayer/interface.py
+++ b/saleor/core/taxes/vatlayer/interface.py
@@ -4,7 +4,7 @@ from django_countries.fields import Country
from django_prices_vatlayer.utils import get_tax_rate_types
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-from .. import ZERO_TAXED_MONEY, TaxType
+from .. import TaxType, zero_taxed_money
from . import (
DEFAULT_TAX_RATE_NAME,
TaxRateType,
@@ -41,7 +41,8 @@ def calculate_checkout_subtotal(
"""Calculate subtotal gross for checkout"""
address = checkout.shipping_address or checkout.billing_address
lines = checkout.lines.prefetch_related("variant__product__product_type")
- lines_total = ZERO_TAXED_MONEY
+ total = checkout.get_total()
+ lines_total = zero_taxed_money(currency=total.currency)
for line in lines:
price = line.variant.get_price(discounts)
lines_total += line.quantity * apply_taxes_to_product(
@@ -57,7 +58,8 @@ def calculate_checkout_shipping(
address = checkout.shipping_address or checkout.billing_address
taxes = get_taxes_for_address(address)
if not checkout.shipping_method:
- return ZERO_TAXED_MONEY
+ total = checkout.get_total()
+ return zero_taxed_money(total.currency)
return get_taxed_shipping_price(checkout.shipping_method.price, taxes)
@@ -65,7 +67,7 @@ def calculate_order_shipping(order: "Order") -> TaxedMoney:
address = order.shipping_address or order.billing_address
taxes = get_taxes_for_address(address)
if not order.shipping_method:
- return ZERO_TAXED_MONEY
+ return zero_taxed_money(order.total.currency)
return get_taxed_shipping_price(order.shipping_method.price, taxes)
diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.py
index bbea6218bc..6dfb8456ab 100644
--- a/saleor/dashboard/discount/forms.py
+++ b/saleor/dashboard/discount/forms.py
@@ -6,7 +6,7 @@ from django_countries import countries
from django_prices.forms import MoneyField
from mptt.forms import TreeNodeMultipleChoiceField
-from ...core.taxes import ZERO_MONEY
+from ...core.taxes import zero_money
from ...core.utils.promo_code import generate_promo_code
from ...discount import DiscountValueType
from ...discount.models import Sale, Voucher
@@ -14,7 +14,7 @@ from ...product.models import Category, Product
from ..forms import AjaxSelect2MultipleChoiceField
MinAmountSpent = MoneyField(
- min_value=ZERO_MONEY,
+ min_value=zero_money(),
required=False,
currency=settings.DEFAULT_CURRENCY,
label=pgettext_lazy(
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 31ffaf95b2..ecf9cf4701 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -11,7 +11,7 @@ from ...account.i18n import (
from ...account.models import User
from ...checkout.forms import QuantityField
from ...core.exceptions import InsufficientStock
-from ...core.taxes import ZERO_TAXED_MONEY, interface as tax_interface
+from ...core.taxes import interface as tax_interface, zero_taxed_money
from ...discount.models import Voucher
from ...discount.utils import decrease_voucher_usage, increase_voucher_usage
from ...order import OrderStatus, events
@@ -102,7 +102,7 @@ class CreateOrderFromDraftForm(forms.ModelForm):
remove_shipping_address = False
if not self.instance.is_shipping_required():
self.instance.shipping_method_name = None
- self.instance.shipping_price = ZERO_TAXED_MONEY
+ self.instance.shipping_price = zero_taxed_money()
if self.instance.shipping_address:
remove_shipping_address = True
super().save()
@@ -228,7 +228,7 @@ class OrderRemoveShippingForm(forms.ModelForm):
def save(self, commit=True):
self.instance.shipping_method = None
self.instance.shipping_method_name = None
- self.instance.shipping_price = ZERO_TAXED_MONEY
+ self.instance.shipping_price = zero_taxed_money()
recalculate_order(self.instance)
return super().save(commit)
diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.py
index 69ffbf4edf..4aa1dd92c1 100644
--- a/saleor/dashboard/order/utils.py
+++ b/saleor/dashboard/order/utils.py
@@ -5,7 +5,7 @@ from django.template.loader import get_template
from django.utils.translation import pgettext
from ...checkout import AddressType
-from ...core.taxes import ZERO_MONEY
+from ...core.taxes import zero_money
from ...discount import VoucherType
from ...discount.models import NotApplicable
from ...discount.utils import (
@@ -149,7 +149,7 @@ def get_voucher_discount_for_order(order):
Raise NotApplicable if voucher of given type cannot be applied.
"""
if not order.voucher:
- return ZERO_MONEY
+ return zero_money()
subtotal = order.get_subtotal()
if order.voucher.type == VoucherType.VALUE:
return get_value_voucher_discount(order.voucher, subtotal.gross)
diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.py
index 01b007fd06..2da5e92287 100644
--- a/saleor/data_feeds/google_merchant.py
+++ b/saleor/data_feeds/google_merchant.py
@@ -9,7 +9,7 @@ from django.core.files.storage import default_storage
from django.utils import timezone
from django.utils.encoding import smart_text
-from ..core.taxes import ZERO_MONEY
+from ..core.taxes import zero_money
from ..discount import DiscountInfo
from ..discount.utils import fetch_discounts
from ..product.models import Attribute, AttributeValue, Category, ProductVariant
@@ -128,7 +128,7 @@ def item_tax(item: ProductVariant, discounts: Iterable[DiscountInfo]):
https://support.google.com/merchants/answer/6324454
"""
# FIXME https://github.com/mirumee/saleor/issues/4311
- return "US::%s:y" % ZERO_MONEY
+ return "US::%s:y" % zero_money()
def item_group_id(item: ProductVariant):
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index d797884f2a..800c9caab3 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -5,7 +5,7 @@ from typing import Iterable
from django.db.models import F
from django.utils.translation import pgettext
-from ..core.taxes import ZERO_MONEY
+from ..core.taxes import zero_money
from . import DiscountInfo
from .models import NotApplicable, Sale
@@ -78,7 +78,7 @@ def get_products_voucher_discount(voucher, prices):
if voucher.apply_once_per_order:
return voucher.get_discount_amount_for(min(prices))
discounts = (voucher.get_discount_amount_for(price) for price in prices)
- total_amount = sum(discounts, ZERO_MONEY)
+ total_amount = sum(discounts, zero_money())
return total_amount
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index fbb1572ecc..f85d9d0e4b 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -3,7 +3,7 @@ import graphene_django_optimizer as gql_optimizer
from django.conf import settings
from ...checkout import models
-from ...core.taxes import ZERO_TAXED_MONEY
+from ...core.taxes import zero_taxed_money
from ...core.taxes.interface import (
calculate_checkout_line_total,
calculate_checkout_shipping,
@@ -121,7 +121,7 @@ class Checkout(CountableDjangoObjectType):
calculate_checkout_total(checkout=root, discounts=info.context.discounts)
- root.get_total_gift_cards_balance()
)
- return max(taxed_total, ZERO_TAXED_MONEY)
+ return max(taxed_total, zero_taxed_money())
@staticmethod
def resolve_subtotal_price(root: models.Checkout, info):
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 49967485a2..08e5008b1a 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -4,7 +4,7 @@ from graphene.types import InputObjectType
from ....account.models import User
from ....core.exceptions import InsufficientStock
-from ....core.taxes import ZERO_TAXED_MONEY
+from ....core.taxes import zero_taxed_money
from ....order import OrderStatus, events, models
from ....order.utils import (
add_variant_to_order,
@@ -239,7 +239,7 @@ class DraftOrderComplete(BaseMutation):
if not order.is_shipping_required():
order.shipping_method_name = None
- order.shipping_price = ZERO_TAXED_MONEY
+ order.shipping_price = zero_taxed_money()
if order.shipping_address:
order.shipping_address.delete()
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 4674251bdc..122b6c8cb8 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -2,7 +2,7 @@ import graphene
from django.core.exceptions import ValidationError
from ....account.models import User
-from ....core.taxes import ZERO_TAXED_MONEY, interface as tax_interface
+from ....core.taxes import interface as tax_interface, zero_taxed_money
from ....order import events, models
from ....order.utils import cancel_order, recalculate_order
from ....payment import CustomPaymentChoices, PaymentError
@@ -150,7 +150,7 @@ class OrderUpdateShipping(BaseMutation):
)
order.shipping_method = None
- order.shipping_price = ZERO_TAXED_MONEY
+ order.shipping_price = zero_taxed_money()
order.shipping_method_name = None
order.save(
update_fields=[
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 8f01d9902a..82f7615a06 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -2,7 +2,7 @@ import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
-from ...core.taxes import ZERO_TAXED_MONEY
+from ...core.taxes import zero_taxed_money
from ...core.taxes.interface import calculate_checkout_total
from ...core.utils import get_client_ip
from ...payment import PaymentError, models
@@ -83,7 +83,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
calculate_checkout_total(checkout, discounts=info.context.discounts)
- checkout.get_total_gift_cards_balance()
)
- checkout_total = max(checkout_total, ZERO_TAXED_MONEY)
+ checkout_total = max(checkout_total, zero_taxed_money(checkout_total.currency))
amount = data.get("amount", checkout_total.gross.amount)
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 de0064e4cb..13aead3dbc 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -381,8 +381,7 @@ class Product(CountableDjangoObjectType):
tax_rate = TaxRateType(
description="A type of tax rate.",
deprecation_reason=(
- "taxRate is deprecated. Use tax_type to obtain tax_code for given tax "
- "gateway"
+ "taxRate is deprecated. Use taxType to obtain taxCode for given tax gateway"
),
)
diff --git a/saleor/order/models.py b/saleor/order/models.py
index caf5e4487e..6c6df861b9 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -16,7 +16,7 @@ from measurement.measures import Weight
from prices import Money
from ..account.models import Address
-from ..core.taxes import ZERO_TAXED_MONEY, zero_money
+from ..core.taxes import zero_money, zero_taxed_money
from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.weight import WeightUnits, zero_weight
from ..discount.models import Voucher
@@ -179,7 +179,7 @@ class Order(models.Model):
]
)
total_captured = [payment.get_captured_amount() for payment in payments]
- total_paid = sum(total_captured, ZERO_TAXED_MONEY)
+ total_paid = sum(total_captured, zero_taxed_money())
return total_paid
def _index_billing_phone(self):
@@ -233,7 +233,7 @@ class Order(models.Model):
def get_subtotal(self):
subtotal_iterator = (line.get_total() for line in self)
- return sum(subtotal_iterator, ZERO_TAXED_MONEY)
+ return sum(subtotal_iterator, zero_taxed_money())
def get_total_quantity(self):
return sum([line.quantity for line in self])
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index e2553d870f..5058c23259 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -8,7 +8,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 import zero_money
from ..core.taxes.interface import calculate_order_line_unit, calculate_order_shipping
from ..core.weight import zero_weight
from ..dashboard.order.utils import get_voucher_discount_for_order
@@ -112,7 +112,7 @@ def update_voucher_discount(func):
try:
discount_amount = get_voucher_discount_for_order(order)
except NotApplicable:
- discount_amount = ZERO_MONEY
+ discount_amount = zero_money()
order.discount_amount = discount_amount
return func(*args, **kwargs)
@@ -309,11 +309,11 @@ def add_gift_card_to_order(order, gift_card, total_price_left):
Return a total price left after applying the gift cards.
"""
- if total_price_left > ZERO_MONEY:
+ if total_price_left > zero_money(total_price_left.currency):
order.gift_cards.add(gift_card)
if total_price_left < gift_card.current_balance:
gift_card.current_balance = gift_card.current_balance - total_price_left
- total_price_left = ZERO_MONEY
+ total_price_left = zero_money(total_price_left.currency)
else:
total_price_left = total_price_left - gift_card.current_balance
gift_card.current_balance = 0
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 7ce4e36228..44e302ad72 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -7,7 +7,7 @@ from ...checkout.utils import (
get_checkout_from_request,
get_or_create_checkout_from_request,
)
-from ...core.taxes import ZERO_TAXED_MONEY, TaxedMoney
+from ...core.taxes import TaxedMoney, zero_taxed_money
from ...core.utils import get_paginator_items
from ...core.utils.filters import get_now_sorted_by
from ..forms import ProductForm
@@ -168,7 +168,7 @@ def collections_visible_to_user(user):
def calculate_revenue_for_variant(variant, start_date):
"""Calculate total revenue generated by a product variant."""
- revenue = ZERO_TAXED_MONEY
+ revenue = zero_taxed_money()
for order_line in variant.order_lines.all():
if order_line.order.created >= start_date:
net = order_line.unit_price_net * order_line.quantity
diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.py
index fe4de3daa8..c25b6b88d7 100644
--- a/saleor/product/utils/costs.py
+++ b/saleor/product/utils/costs.py
@@ -1,10 +1,11 @@
from prices import MoneyRange
-from ...core.taxes import ZERO_MONEY
+from ...core.taxes import zero_money
def get_product_costs_data(product):
- purchase_costs_range = MoneyRange(start=ZERO_MONEY, stop=ZERO_MONEY)
+
+ purchase_costs_range = MoneyRange(start=zero_money(), stop=zero_money())
margin = (0, 0)
if not product.variants.exists():
@@ -49,7 +50,7 @@ def get_variant_costs_data(variant):
def get_cost_price(variant):
if not variant.cost_price:
- return ZERO_MONEY
+ return zero_money()
return variant.cost_price
diff --git a/saleor/settings.py b/saleor/settings.py
index 3477c654af..e5a6640cbd 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -347,15 +347,8 @@ VATLAYER_USE_HTTPS = get_bool_from_env("VATLAYER_USE_HTTPS", False)
# Avatax supports two ways of log in - username:password or account:license
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_USE_SANDBOX = os.environ.get("AVATAX_USE_SANDBOX", DEBUG)
AVATAX_COMPANY_NAME = os.environ.get("AVATAX_COMPANY_NAME", "DEFAULT")
-AVATAX_CACHE_TIME = os.environ.get("AVATAX_CACHE_TIME", 60 * 60)
-AVATAX_TAX_CODES_CACHE_TIME = os.environ.get("AVATAX_TAX_CODES_CACHE", 60 * 60 * 24 * 7)
-AVATAX_COMMON_CARRIER_CODE = os.environ.get("AVATAX_COMMON_CARRIER_CODE", "FR020100")
-AVATAX_CACHE_KEY = os.environ.get("AVATAX_CACHE_KEY", "avatax_request_id_")
-AVATAX_TAX_CODES_CACHE_KEY = os.environ.get(
- "AVATAX_TAX_CODES_CACHE_KEY", "avatax_tax_codes_cache_key"
-)
AVATAX_AUTOCOMMIT = os.environ.get("AVATAX_AUTOCOMMIT", False)
ACCOUNT_ACTIVATION_DAYS = 3
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index e11097a6e8..914117db22 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -8,7 +8,7 @@ from prices import TaxedMoney
from saleor.checkout.models import Checkout
from saleor.checkout.utils import clean_checkout, is_fully_paid
-from saleor.core.taxes import ZERO_MONEY
+from saleor.core.taxes import zero_money
from saleor.graphql.core.utils import str_to_enum
from saleor.order.models import Order
from saleor.payment import PaymentError
@@ -932,7 +932,7 @@ def test_checkout_complete(
assert payment.transactions.count() == 1
gift_card.refresh_from_db()
- assert gift_card.current_balance == ZERO_MONEY
+ assert gift_card.current_balance == zero_money()
assert gift_card.last_used_on
assert not Checkout.objects.filter(
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index ca3418c85d..68ce55796a 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -9,7 +9,7 @@ from freezegun import freeze_time
from prices import Money, TaxedMoney
from saleor.account.models import CustomerEvent
-from saleor.core.taxes import ZERO_TAXED_MONEY
+from saleor.core.taxes import zero_taxed_money
from saleor.graphql.core.enums import ReportingPeriod
from saleor.graphql.order.mutations.orders import (
clean_order_cancel,
@@ -1712,7 +1712,7 @@ def test_order_update_shipping_clear_shipping_method(
order.refresh_from_db()
assert order.shipping_method is None
- assert order.shipping_price == ZERO_TAXED_MONEY
+ assert order.shipping_price == zero_taxed_money()
assert order.shipping_method_name is None
@@ -1801,7 +1801,7 @@ def test_draft_order_clear_shipping_method(
assert data["order"]["id"] == order_id
draft_order.refresh_from_db()
assert draft_order.shipping_method is None
- assert draft_order.shipping_price == ZERO_TAXED_MONEY
+ assert draft_order.shipping_price == zero_taxed_money()
assert draft_order.shipping_method_name is None
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index 91adc5473e..466d5b2e96 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -8,7 +8,7 @@ from phonenumber_field.phonenumber import PhoneNumber
from prices import Money, TaxedMoney
from saleor.checkout import AddressType
-from saleor.core.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
+from saleor.core.taxes import zero_money, zero_taxed_money
from saleor.dashboard.order.forms import ChangeQuantityForm
from saleor.dashboard.order.utils import (
remove_customer_from_order,
@@ -858,7 +858,7 @@ def test_view_order_shipping_remove(admin_client, draft_order):
draft_order.refresh_from_db()
assert not draft_order.shipping_method
assert not draft_order.shipping_method_name
- assert draft_order.shipping_price == ZERO_TAXED_MONEY
+ assert draft_order.shipping_price == zero_taxed_money()
def test_view_remove_draft_order(admin_client, draft_order):
@@ -1019,7 +1019,7 @@ def test_view_order_voucher_remove(admin_client, draft_order, settings, voucher)
assert get_redirect_location(response) == redirect_url
draft_order.refresh_from_db()
- assert draft_order.discount_amount == ZERO_MONEY
+ assert draft_order.discount_amount == zero_money()
assert draft_order.total == total_before + discount_amount
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 611415ca78..e92e31d67f 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -30,8 +30,8 @@ from saleor.checkout.utils import (
remove_voucher_from_checkout,
)
from saleor.core.exceptions import InsufficientStock
-from saleor.core.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
-from saleor.core.taxes.interface import checkout_are_taxes_handled
+from saleor.core.taxes import zero_money, zero_taxed_money
+from saleor.core.taxes.interface import taxes_are_enabled
from saleor.discount import DiscountValueType, VoucherType
from saleor.discount.models import NotApplicable, Voucher
from saleor.order import OrderEvents, OrderEventsEmails
@@ -758,7 +758,7 @@ def test_create_order_with_gift_card_partial_use(
gift_card_used.refresh_from_db()
assert order.gift_cards.count() > 0
- assert order.total == ZERO_TAXED_MONEY
+ assert order.total == zero_taxed_money()
assert (
gift_card_balance_before_order
== (price_without_gift_card + gift_card_used.current_balance).gross.amount
@@ -799,9 +799,10 @@ def test_create_order_with_many_gift_cards(
gift_card_created_by_staff.refresh_from_db()
gift_card.refresh_from_db()
+ zero_price = zero_money()
assert order.gift_cards.count() > 0
- assert gift_card_created_by_staff.current_balance == ZERO_MONEY
- assert gift_card.current_balance == ZERO_MONEY
+ assert gift_card_created_by_staff.current_balance == zero_price
+ assert gift_card.current_balance == zero_price
assert price_without_gift_card.gross.amount == (
gift_cards_balance_befor_order + order.total.gross.amount
)
@@ -1189,7 +1190,7 @@ def test_remove_voucher_from_checkout(checkout_with_voucher, voucher_translation
assert not checkout.voucher_code
assert not checkout.discount_name
assert not checkout.translated_discount_name
- assert checkout.discount_amount == ZERO_MONEY
+ assert checkout.discount_amount == zero_money()
def test_recalculate_checkout_discount(
@@ -1226,7 +1227,7 @@ def test_recalculate_checkout_discount_voucher_not_applicable(
assert not checkout.voucher_code
assert not checkout.discount_name
- assert checkout.discount_amount == ZERO_MONEY
+ assert checkout.discount_amount == zero_money()
def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, voucher):
@@ -1239,16 +1240,16 @@ def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, vo
assert not checkout.voucher_code
assert not checkout.discount_name
- assert checkout.discount_amount == ZERO_MONEY
+ assert checkout.discount_amount == zero_money()
def test_get_checkout_context(checkout_with_voucher):
line_price = TaxedMoney(net=Money("30.00", "USD"), gross=Money("30.00", "USD"))
expected_data = {
"checkout": checkout_with_voucher,
- "checkout_are_taxes_handled": checkout_are_taxes_handled(),
+ "checkout_are_taxes_handled": taxes_are_enabled(),
"checkout_lines": [(checkout_with_voucher.lines.first(), line_price)],
- "checkout_shipping_price": ZERO_TAXED_MONEY,
+ "checkout_shipping_price": zero_taxed_money(),
"checkout_subtotal": line_price,
"checkout_total": line_price - checkout_with_voucher.discount_amount,
"shipping_required": checkout_with_voucher.is_shipping_required(),