Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add taxes support to api
Maciej Korycinski5f35350af583
diff --git a/saleor/core/taxes/__init__.py b/saleor/core/taxes/__init__.pyindex 1f27598c2d..0804b012b8 100644--- a/saleor/core/taxes/__init__.py+++ b/saleor/core/taxes/__init__.py@@ -1,3 +1,5 @@+from dataclasses import dataclass+from django.conf import settingsfrom django.contrib.sites.models import Sitefrom prices import Money, TaxedMoney@@ -22,3 +24,11 @@ def display_gross_prices():def charge_taxes_on_shipping():return Site.objects.get_current().settings.charge_taxes_on_shipping+++@dataclass+class TaxType:+ """Dataclass for unifying tax type object that comes from tax gateway"""++ code: str+ description: strdiff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/taxes/avatax/__init__.pyindex c1f9883809..e5a06264e4 100644--- a/saleor/core/taxes/avatax/__init__.py+++ b/saleor/core/taxes/avatax/__init__.py@@ -17,7 +17,7 @@ if TYPE_CHECKING:common_carrier_code = "FR020100" # FIXMEcache_key = "avatax_request_id_" # FIXME-TAX_CODES_CACHE_KEY = "tax_codes_cache_key"+TAX_CODES_CACHE_KEY = "avatax_tax_codes_cache_key"COMMON_CARRIER_CODE = "FR000000"@@ -332,7 +332,7 @@ def generate_tax_codes_dict(tax_codes = {}for line in response.get("value", []):if line.get("isActive"):- tax_codes[line.get("description")] = line.get("taxCode")+ tax_codes[line.get("taxCode")] = line.get("description")return tax_codesdiff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.pyindex cdc69e9b63..f5e9850c98 100644--- a/saleor/core/taxes/avatax/interface.py+++ b/saleor/core/taxes/avatax/interface.py@@ -1,14 +1,13 @@from datetime import datefrom decimal import Decimal-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, List, Unionfrom urllib.parse import urljoin-from django.utils.translation import pgettextfrom prices import Money, TaxedMoneyfrom ....checkout import models as checkout_modelsfrom ....discount.models import Sale-from .. import ZERO_TAXED_MONEY+from .. import ZERO_TAXED_MONEY, TaxTypefrom ..errors import TaxErrorfrom . import (TransactionType,@@ -23,9 +22,10 @@ from . import ()if TYPE_CHECKING:- from ....product.models import Productfrom ....order.models import Order, OrderLine+META_FIELD = "avatax"+def get_total_gross(checkout: "checkout_models.Checkout", discounts):checkout_total = checkout.get_total(discounts=discounts)@@ -160,18 +160,29 @@ def calculate_order_shipping(order: "Order"):)-def get_tax_rate_type_choices():+def get_tax_rate_type_choices() -> List[TaxType]:return [- (desc, pgettext("Avatax tax code", desc))- for desc, tax_code in get_cached_tax_codes_or_fetch().items()+ TaxType(code=tax_code, description=desc)+ for tax_code, desc 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+def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):+ codes = get_cached_tax_codes_or_fetch()+ if tax_code not in codes:+ return++ tax_description = codes[tax_code]+ if not hasattr(obj, "meta"):+ return+ if "taxes" not in obj.meta:+ obj.meta["taxes"] = {}+ obj.meta["taxes"]["avatax"] = {"code": tax_code, "description": tax_description}+++def get_tax_from_object_meta(obj: Union["Product", "ProductType"]) -> TaxType:+ if not hasattr(obj, "meta"):+ return TaxType(code="", description="")- if "taxes" in product.meta:- product.meta["taxes"] = {}- product.meta["taxes"]["avatax"] = tax_code+ tax = obj.meta.get("taxes", {}).get(META_FIELD, {})+ return TaxType(code=tax.get("code", ""), description=tax.get("description"))diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.pyindex fa480cc22b..8dddaa3e1c 100644--- a/saleor/core/taxes/interface.py+++ b/saleor/core/taxes/interface.py@@ -1,10 +1,10 @@-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, List, Unionfrom django.conf import settingsfrom django_countries.fields import Countryfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange-from . import ZERO_TAXED_MONEY+from . import ZERO_TAXED_MONEY, TaxTypefrom .avatax import interface as avatax_interfacefrom .vatlayer import interface as vatlayer_interface@@ -75,7 +75,7 @@ def apply_taxes_to_shipping(price: Money, shipping_address: "Address") -> TaxedMreturn TaxedMoney(net=price, gross=price)-def get_tax_rate_type_choices():+def get_tax_rate_type_choices() -> List[TaxType]: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:@@ -162,8 +162,16 @@ def postprocess_order_creation(order: "Order"):return avatax_interface.postprocess_order_creation(order)-def assign_tax_code_to_product(product: "Product", tax_code: str):+def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):if settings.VATLAYER_ACCESS_KEY:- vatlayer_interface.assign_tax_code_to_product(product, tax_code)+ vatlayer_interface.assign_tax_to_object_meta(obj, tax_code)if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:- avatax_interface.assign_tax_code_to_product(product, tax_code)+ avatax_interface.assign_tax_to_object_meta(obj, tax_code)+++def get_tax_from_object_meta(obj: Union["Product", "ProductType"],) -> TaxType:+ if settings.VATLAYER_ACCESS_KEY:+ return vatlayer_interface.get_tax_from_object_meta(obj)+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:+ return avatax_interface.get_tax_from_object_meta(obj)+ return TaxType(code="", description="")diff --git a/saleor/core/taxes/vatlayer/interface.py b/saleor/core/taxes/vatlayer/interface.pyindex c2dad90c0b..e54ac3331a 100644--- a/saleor/core/taxes/vatlayer/interface.py+++ b/saleor/core/taxes/vatlayer/interface.py@@ -1,11 +1,11 @@-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, List, Unionfrom django_countries.fields import Countryfrom django_prices_vatlayer.utils import get_tax_rate_typesfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRangefrom ....core import TaxRateType # FIXME this should be placed in VatLayer module-from .. import ZERO_TAXED_MONEY+from .. import ZERO_TAXED_MONEY, TaxTypefrom . import (DEFAULT_TAX_RATE_NAME,apply_tax_to_price,@@ -21,6 +21,9 @@ if TYPE_CHECKING:from ....account.models import Address+META_FIELD = "vatlayer"++def get_total_gross(checkout: "Checkout", discounts: "SaleQueryset") -> TaxedMoney:"""Calculate total gross for checkout by using vatlayer"""return (@@ -66,15 +69,13 @@ def apply_taxes_to_shipping(price: Money, shipping_address: "Address"):return get_taxed_shipping_price(price, taxes)-def get_tax_rate_type_choices():+def get_tax_rate_type_choices() -> List[TaxType]: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+ TaxType(code=rate_name, description=rate_name) for rate_name in rate_types]# sort choices alphabetically by translations- return sorted(choices, key=lambda x: x[1])+ return sorted(choices, key=lambda x: x.code)def apply_taxes_to_variant(@@ -106,10 +107,19 @@ def apply_taxes_to_shipping_price_range(return get_taxed_shipping_price(prices, taxes)-def assign_tax_code_to_product(product: "Product", tax_code: str) -> None:+def assign_tax_to_object_meta(obj: Union["Product", "ProductType"], tax_code: str):if tax_code not in dict(TaxRateType.CHOICES):return+ if not hasattr(obj, "meta"):+ return+ if "taxes" not in obj.meta:+ obj.meta["taxes"] = {}+ obj.meta["taxes"][META_FIELD] = {"code": tax_code, "description": tax_code}+++def get_tax_from_object_meta(obj: Union["Product", "ProductType"]) -> TaxType:+ if not hasattr(obj, "meta"):+ return TaxType(code="", description="")+ tax = obj.meta.get("taxes", {}).get(META_FIELD)- if "taxes" in product.meta:- product.meta["taxes"] = {}- product.meta["taxes"]["vatlayer"] = tax_code+ return TaxType(code=tax.get("code", ""), description=tax.get("description"))diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex a2b1379cae..100a0f0d70 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -106,7 +106,9 @@ class ProductTypeForm(forms.ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- self.fields["tax_rate"].choices = get_tax_rate_type_choices()+ self.fields["tax_rate"].choices = [+ (tax.code, tax.description) for tax in get_tax_rate_type_choices()+ ]unassigned_attrs_q = Q(product_type__isnull=True, product_variant_type__isnull=True)@@ -293,7 +295,9 @@ class ProductForm(forms.ModelForm, AttributesMixin):self.fields["seo_title"] = SeoTitleField(extra_attrs={"data-bind": self["name"].auto_id})- self.fields["tax_rate"].choices = get_tax_rate_type_choices()+ self.fields["tax_rate"].choices = [+ (tax.code, tax.description) for tax in get_tax_rate_type_choices()+ ]if include_taxes_in_prices():self.fields["price"].label = pgettext_lazy("Currency gross amount", "Gross price"diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex ddad34e404..8706f0e254 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -2,7 +2,7 @@ import graphenefrom .account.schema import AccountMutations, AccountQueriesfrom .checkout.schema import CheckoutMutations, CheckoutQueries-from .core.schema import CoreMutations+from .core.schema import CoreMutations, CoreQueriesfrom .discount.schema import DiscountMutations, DiscountQueriesfrom .menu.schema import MenuMutations, MenuQueriesfrom .order.schema import OrderMutations, OrderQueries@@ -17,6 +17,7 @@ from .translations.schema import TranslationQueriesclass Query(AccountQueries,CheckoutQueries,+ CoreQueries,DiscountQueries,MenuQueries,OrderQueries,diff --git a/saleor/graphql/core/schema.py b/saleor/graphql/core/schema.pyindex 307c40efef..ec29797bce 100644--- a/saleor/graphql/core/schema.py+++ b/saleor/graphql/core/schema.py@@ -1,10 +1,24 @@import grapheneimport graphql_jwt+from ...core.taxes import interface as tax_interfacefrom .mutations import CreateToken, VerifyToken+from .types.common import TaxTypeclass CoreMutations(graphene.ObjectType):token_create = CreateToken.Field()token_refresh = graphql_jwt.Refresh.Field()token_verify = VerifyToken.Field()+++class CoreQueries(graphene.ObjectType):+ tax_types = graphene.List(+ TaxType, description="List of all tax rates available from tax gateway"+ )++ def resolve_tax_types(self, _info):+ return [+ TaxType(description=tax.description, tax_code=tax.code)+ for tax in tax_interface.get_tax_rate_type_choices()+ ]diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.pyindex 3ea384e89d..92efe4e307 100644--- a/saleor/graphql/core/types/__init__.py+++ b/saleor/graphql/core/types/__init__.py@@ -6,6 +6,7 @@ from .common import (LanguageDisplay,PermissionDisplay,SeoInput,+ TaxType,Weight,)from .filter_input import FilterInputObjectTypediff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex 9ec2cb04e5..3bba856d6f 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -89,3 +89,12 @@ class DateRangeInput(graphene.InputObjectType):class IntRangeInput(graphene.InputObjectType):gte = graphene.Int(description="Value greater than or equal", required=False)lte = graphene.Int(description="Value less than or equal", required=False)+++class TaxType(graphene.ObjectType):+ """Representation of tax types fetched from tax gateway"""++ description = graphene.String(description="Description of the tax type")+ tax_code = graphene.String(+ description="External tax code used to identify given tax group"+ )diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 2d2f1b3606..a7d6ae1889 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -4,6 +4,7 @@ from django.db import transactionfrom django.template.defaultfilters import slugifyfrom graphene.types import InputObjectType+from ....core.taxes import interface as tax_interfacefrom ....product import modelsfrom ....product.tasks import update_variants_namesfrom ....product.thumbnails import (@@ -275,7 +276,7 @@ class ProductInput(graphene.InputObjectType):Product price. Note: this field is deprecated, use basePrice instead.""")base_price = Decimal(description="Product price.")- tax_rate = TaxRateType(description="Tax rate.")+ tax_rate = graphene.String(description="Tax rate for enabled tax gateway")seo = SeoInput(description="Search engine optimization fields.")weight = WeightScalar(description="Weight of the Product.", required=False)sku = graphene.String(@@ -333,6 +334,10 @@ class ProductCreate(ModelMutation):if price is not None:cleaned_input["price"] = price+ tax_rate = cleaned_input.pop("tax_rate", "")+ if tax_rate:+ tax_interface.assign_tax_to_object_meta(instance, tax_rate)+if attributes and product_type:qs = product_type.product_attributes.prefetch_related("values")try:diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex dedebb831d..0b9d5205ae 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -5,6 +5,7 @@ from graphene import relayfrom graphql.error import GraphQLErrorfrom graphql_jwt.decorators import permission_required+from ....core.taxes import interface as tax_interfacefrom ....product import modelsfrom ....product.templatetags.product_images import (get_product_image_thumbnail,@@ -19,7 +20,7 @@ from ....product.utils.costs import get_margin_for_variant, get_product_costs_dafrom ...core.connection import CountableDjangoObjectTypefrom ...core.enums import ReportingPeriod, TaxRateTypefrom ...core.fields import PrefetchingConnectionField-from ...core.types import Image, Money, MoneyRange, TaxedMoney, TaxedMoneyRange+from ...core.types import Image, Money, MoneyRange, TaxedMoney, TaxedMoneyRange, TaxTypefrom ...translations.enums import LanguageCodeEnumfrom ...translations.resolvers import resolve_translationfrom ...translations.types import (@@ -349,7 +350,9 @@ class Product(CountableDjangoObjectType):description="The product's default base price.",deprecation_reason=("Has been replaced by 'basePrice'"),)- tax_rate = TaxRateType(description="A type of tax rate.")+ tax_type = graphene.Field(+ TaxType, description="A type of tax. Assigned by enabled tax gateway"+ )attributes = graphene.List(graphene.NonNull(SelectedAttribute),required=True,@@ -413,6 +416,10 @@ class Product(CountableDjangoObjectType):"weight",]+ def resolve_tax_type(self, _info):+ tax_data = tax_interface.get_tax_from_object_meta(self)+ return TaxType(tax_code=tax_data.code, description=tax_data.description)+@gql_optimizer.resolver_hints(prefetch_related="images")def resolve_thumbnail_url(self, info, *, size=None):if not size:diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 8a80e652ae..ca1ea3c6d4 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2043,7 +2043,7 @@ type Product implements Node {isAvailable: BooleanbasePrice: Moneyprice: Money @deprecated(reason: "Has been replaced by 'basePrice'")- taxRate: TaxRateType+ taxType: TaxTypeattributes: [SelectedAttribute!]!purchaseCost: MoneyRangemargin: Margin@@ -2093,7 +2093,7 @@ input ProductCreateInput {name: Stringprice: DecimalbasePrice: Decimal- taxRate: TaxRateType+ taxRate: Stringseo: SeoInputweight: WeightScalarsku: String@@ -2176,7 +2176,7 @@ input ProductInput {name: Stringprice: DecimalbasePrice: Decimal- taxRate: TaxRateType+ taxRate: Stringseo: SeoInputweight: WeightScalarsku: String@@ -2421,6 +2421,7 @@ type Query {sales(filter: SaleFilterInput, query: String, before: String, after: String, first: Int, last: Int): SaleCountableConnectionvoucher(id: ID!): Vouchervouchers(filter: VoucherFilterInput, query: String, before: String, after: String, first: Int, last: Int): VoucherCountableConnection+ taxTypes: [TaxType]checkout(token: UUID): Checkoutcheckouts(before: String, after: String, first: Int, last: Int): CheckoutCountableConnectioncheckoutLine(id: ID): CheckoutLine@@ -2823,6 +2824,11 @@ enum TaxRateType {WINE}+type TaxType {+ description: String+ taxCode: String+}+type TaxedMoney {currency: String!gross: Money!