Skip to content

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

Add fetching tax_codes from avatax. Add logic to assign tax_code to product.meta

Maciej Korycinski4ff7c548df3c
diff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/taxes/avatax/__init__.py
index c9c67248d0..c1f9883809 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 TYPE_CHECKING, Any, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from urllib.parse import urljoin
import requests
@@ -17,6 +17,8 @@ if TYPE_CHECKING:
common_carrier_code = "FR020100" # FIXME
cache_key = "avatax_request_id_" # FIXME
+TAX_CODES_CACHE_KEY = "tax_codes_cache_key"
+COMMON_CARRIER_CODE = "FR000000"
class TransactionType:
@@ -46,11 +48,16 @@ def api_post_request(
def api_get_request(
- url,
- username=settings.AVATAX_USERNAME_OR_ACCOUNT,
- password=settings.AVATAX_PASSWORD_OR_LICENSE,
+ url: str,
+ username: str = settings.AVATAX_USERNAME_OR_ACCOUNT,
+ password: str = settings.AVATAX_PASSWORD_OR_LICENSE,
):
- return requests.get(url, auth=HTTPBasicAuth(username, password))
+ try:
+ auth = HTTPBasicAuth(username, password)
+ response = requests.get(url, auth=auth)
+ except requests.exceptions.RequestException:
+ return {}
+ return response.json()
def validate_order(order: "Order") -> bool:
@@ -184,11 +191,12 @@ def get_order_lines_data(order: "Order") -> List[Dict[str, str]]:
for line in lines:
if not line.variant.product.charge_taxes:
continue
+ tax_code = line.variant.product.meta.get("taxes", {}).get("avatax", "")
append_line_to_data(
data=data,
quantity=line.quantity,
amount=line.unit_price_net.amount * line.quantity,
- tax_code="PC040156",
+ tax_code=tax_code,
item_code=line.variant.sku,
description=line.variant.product.description,
)
@@ -316,3 +324,28 @@ def get_order_tax_data(order: "Order", commit=False) -> Dict[str, Any]:
)
response = get_cached_response_or_fetch(data, "order_%s" % order.token)
return response
+
+
+def generate_tax_codes_dict(
+ response: Dict[str, Union[str, int, bool]]
+) -> Dict[str, str]:
+ tax_codes = {}
+ for line in response.get("value", []):
+ if line.get("isActive"):
+ tax_codes[line.get("description")] = line.get("taxCode")
+ return tax_codes
+
+
+def get_cached_tax_codes_or_fetch(
+ cache_time: int = settings.AVATAX_TAX_CODES_CACHE_TIME
+):
+ """Try to get cached tax codes. If cache is empty fetch the newest taxcodes from
+ avatax"""
+ 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(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 4cbfc5b9f1..cdc69e9b63 100644
--- a/saleor/core/taxes/avatax/interface.py
+++ b/saleor/core/taxes/avatax/interface.py
@@ -3,6 +3,7 @@ from decimal import Decimal
from typing import TYPE_CHECKING
from urllib.parse import urljoin
+from django.utils.translation import pgettext
from prices import Money, TaxedMoney
from ....checkout import models as checkout_models
@@ -14,6 +15,7 @@ from . import (
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,
@@ -21,6 +23,7 @@ from . import (
)
if TYPE_CHECKING:
+ from ....product.models import Product
from ....order.models import Order, OrderLine
@@ -155,3 +158,20 @@ def calculate_order_shipping(order: "Order"):
return TaxedMoney(
net=order.shipping_method.price, gross=order.shipping_method.price
)
+
+
+def get_tax_rate_type_choices():
+ return [
+ (desc, pgettext("Avatax tax code", desc))
+ for desc, tax_code in get_cached_tax_codes_or_fetch().items()
+ ]
+
+
+def assign_tax_code_to_product(product: "Product", tax_code: str) -> None:
+ # FIXME confirm that tax_code exists in avatax
+ # if tax_code not in dict(TaxRateType.CHOICES):
+ # return
+
+ if "taxes" in product.meta:
+ product.meta["taxes"] = {}
+ product.meta["taxes"]["avatax"] = tax_code
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
index 88343f3364..fa480cc22b 100644
--- a/saleor/core/taxes/interface.py
+++ b/saleor/core/taxes/interface.py
@@ -79,7 +79,8 @@ 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 []
+ # FIXME shouldn't use description as a id for tax rates.
+ return avatax_interface.get_tax_rate_type_choices()
return []
@@ -159,3 +160,10 @@ def apply_taxes_to_shipping_price_range(prices: MoneyRange, country: Country):
def postprocess_order_creation(order: "Order"):
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return avatax_interface.postprocess_order_creation(order)
+
+
+def assign_tax_code_to_product(product: "Product", tax_code: str):
+ if settings.VATLAYER_ACCESS_KEY:
+ vatlayer_interface.assign_tax_code_to_product(product, tax_code)
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ avatax_interface.assign_tax_code_to_product(product, tax_code)
diff --git a/saleor/core/taxes/vatlayer/interface.py b/saleor/core/taxes/vatlayer/interface.py
index fede8a45a6..c2dad90c0b 100644
--- a/saleor/core/taxes/vatlayer/interface.py
+++ b/saleor/core/taxes/vatlayer/interface.py
@@ -104,3 +104,12 @@ def apply_taxes_to_shipping_price_range(
if country:
taxes = get_taxes_for_country(country)
return get_taxed_shipping_price(prices, taxes)
+
+
+def assign_tax_code_to_product(product: "Product", tax_code: str) -> None:
+ if tax_code not in dict(TaxRateType.CHOICES):
+ return
+
+ if "taxes" in product.meta:
+ product.meta["taxes"] = {}
+ product.meta["taxes"]["vatlayer"] = tax_code