Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
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__.pyindex c9c67248d0..c1f9883809 100644--- a/saleor/core/taxes/avatax/__init__.py+++ b/saleor/core/taxes/avatax/__init__.py@@ -1,6 +1,6 @@import jsonfrom datetime import date-from typing import TYPE_CHECKING, Any, Dict, List, Optional+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Unionfrom urllib.parse import urljoinimport requests@@ -17,6 +17,8 @@ if TYPE_CHECKING:common_carrier_code = "FR020100" # FIXMEcache_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_codesdiff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.pyindex 4cbfc5b9f1..cdc69e9b63 100644--- a/saleor/core/taxes/avatax/interface.py+++ b/saleor/core/taxes/avatax/interface.py@@ -3,6 +3,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKINGfrom urllib.parse import urljoin+from django.utils.translation import pgettextfrom prices import Money, TaxedMoneyfrom ....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 Productfrom ....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_codediff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.pyindex 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.pyindex 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