Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix mypy errors for discount and releated files
IKarbowiakbcccc163997f
diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 3c550ae63a..daa8da7bc7 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -181,7 +181,7 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):def get_short_name(self):return self.email- def has_perm(self, perm: BasePermissionEnum, obj=None):+ def has_perm(self, perm: BasePermissionEnum, obj=None): # type: ignore# This method is overridden to accept perm as BasePermissionEnumreturn super().has_perm(perm.value, obj)diff --git a/saleor/core/payments.py b/saleor/core/payments.pyindex 999aef1156..55e563a69a 100644--- a/saleor/core/payments.py+++ b/saleor/core/payments.py@@ -2,7 +2,13 @@ from abc import ABC, abstractmethodfrom typing import TYPE_CHECKING, Listif TYPE_CHECKING:- from saleor.payment.interface import PaymentData, GatewayResponse, TokenConfig+ # flake8: noqa+ from saleor.payment.interface import (+ PaymentData,+ GatewayResponse,+ TokenConfig,+ CustomerSource,+ )class PaymentInterface(ABC):diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex a4c5b760fd..a9f72e788b 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -1,5 +1,6 @@import loggingimport socket+from typing import Optionalfrom urllib.parse import urljoinfrom babel.numbers import get_territory_currencies@@ -17,8 +18,7 @@ georeader = geolite2.reader()logger = logging.getLogger(__name__)-def build_absolute_uri(location):- # type: (str) -> str+def build_absolute_uri(location: str) -> Optional[str]:host = Site.objects.get_current().domainprotocol = "https" if settings.ENABLE_SSL else "http"current_uri = "%s://%s" % (protocol, host)diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.pyindex 39fe0e880d..f88fc9e776 100644--- a/saleor/discount/__init__.py+++ b/saleor/discount/__init__.py@@ -1,9 +1,13 @@from dataclasses import dataclass-from typing import Any, List+from typing import TYPE_CHECKING, List, Set, Unionfrom django.conf import settingsfrom django.utils.translation import pgettext_lazy+if TYPE_CHECKING:+ # flake8: noqa+ from .models import Sale, Voucher+class DiscountValueType:FIXED = "fixed"@@ -34,7 +38,7 @@ class VoucherType:@dataclassclass DiscountInfo:- sale: Any- product_ids: List[int]- category_ids: List[int]- collection_ids: List[int]+ sale: Union["Sale", "Voucher"]+ product_ids: Union[List[int], Set[int]]+ category_ids: Union[List[int], Set[int]]+ collection_ids: Union[List[int], Set[int]]diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 7d5bca5fd7..389275a031 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -15,6 +15,7 @@ from .models import NotApplicable, Sale, VoucherCustomerif TYPE_CHECKING:# flake8: noqafrom .models import Voucher+ from .types import DiscountsListTypefrom ..product.models import Productfrom ..checkout.models import Checkoutfrom ..order.models import Order@@ -55,7 +56,7 @@ def remove_voucher_usage_by_customer(voucher: "Voucher", customer_email: str) ->def get_product_discount_on_sale(- product: "Product", product_collections: Set[str], discount: DiscountInfo+ product: "Product", product_collections: Set[int], discount: DiscountInfo):"""Return discount value if product is on sale or raise NotApplicable."""is_product_on_sale = (@@ -73,7 +74,7 @@ def get_product_discount_on_sale(def get_product_discounts(product: "Product", discounts: "DiscountsListType") -> Money:"""Return discount values for all discounts applicable to a product."""product_collections = set(product.collections.all().values_list("pk", flat=True))- for discount in discounts:+ for discount in discounts: # type: ignoretry:yield get_product_discount_on_sale(product, product_collections, discount)except NotApplicable:@@ -85,9 +86,9 @@ def calculate_discounted_price() -> Money:"""Return minimum product's price of all prices with discounts applied."""if discounts:- discounts = list(get_product_discounts(product, discounts))+ discount_prices = list(get_product_discounts(product, discounts))if discounts:- price = min(discount(price) for discount in discounts)+ price = min(discount(price) for discount in discount_prices)return price@@ -104,6 +105,8 @@ def validate_voucher_in_order(order: "Order"):subtotal = order.get_subtotal()quantity = order.get_total_quantity()customer_email = order.get_customer_email()+ if not order.voucher:+ returnvalidate_voucher(order.voucher, subtotal.gross, quantity, customer_email)@@ -125,16 +128,16 @@ def get_products_voucher_discount(voucher: "Voucher", prices: Iterable[Money]) -return total_amount-def _fetch_categories(sale_pks: Iterable[str]) -> Dict[str, Set[str]]:+def _fetch_categories(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:from ..product.models import Categorycategories = Sale.categories.through.objects.filter(sale_id__in=sale_pks).values_list("sale_id", "category_id")- category_map = defaultdict(set)+ category_map: Dict[int, Set[int]] = defaultdict(set)for sale_pk, category_pk in categories:category_map[sale_pk].add(category_pk)- subcategory_map = defaultdict(set)+ subcategory_map: Dict[int, Set[int]] = defaultdict(set)for sale_pk, category_pks in category_map.items():subcategory_map[sale_pk] = set(Category.tree.filter(pk__in=category_pks)@@ -144,21 +147,21 @@ def _fetch_categories(sale_pks: Iterable[str]) -> Dict[str, Set[str]]:return subcategory_map-def _fetch_collections(sale_pks: Iterable[str]) -> Dict[str, set]:+def _fetch_collections(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:collections = Sale.collections.through.objects.filter(sale_id__in=sale_pks).values_list("sale_id", "collection_id")- collection_map = defaultdict(set)+ collection_map: Dict[int, Set[int]] = defaultdict(set)for sale_pk, collection_pk in collections:collection_map[sale_pk].add(collection_pk)return collection_map-def _fetch_products(sale_pks: Iterable[str]) -> Dict[str, set]:+def _fetch_products(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:products = Sale.products.through.objects.filter(sale_id__in=sale_pks).values_list("sale_id", "product_id")- product_map = defaultdict(set)+ product_map: Dict[int, Set[int]] = defaultdict(set)for sale_pk, product_pk in products:product_map[sale_pk].add(product_pk)return product_mapdiff --git a/saleor/extensions/base_plugin.py b/saleor/extensions/base_plugin.pyindex 747815a4f8..79e0e5a078 100644--- a/saleor/extensions/base_plugin.py+++ b/saleor/extensions/base_plugin.py@@ -309,7 +309,7 @@ class BasePlugin:def _update_config_items(cls, configuration_to_update: List[dict], current_config: List[dict]):- config_structure = (+ config_structure: dict = (cls.CONFIG_STRUCTURE if cls.CONFIG_STRUCTURE is not None else {})for config_item in current_config:@@ -318,8 +318,10 @@ class BasePlugin:if config_item["name"] == config_item_name:new_value = config_item_to_update.get("value")item_type = config_structure.get(config_item_name, {}).get("type")- if item_type == ConfigurationTypeField.BOOLEAN and not isinstance(- new_value, bool+ if (+ item_type == ConfigurationTypeField.BOOLEAN+ and new_value+ and not isinstance(new_value, bool)):new_value = new_value.lower() == "true"config_item.update([("value", new_value)])diff --git a/saleor/extensions/checks.py b/saleor/extensions/checks.pyindex 0aee8079a3..7df83f8023 100644--- a/saleor/extensions/checks.py+++ b/saleor/extensions/checks.py@@ -53,5 +53,8 @@ def check_single_plugin(plugin_path: str, errors: List[Error]):def check_plugin_name(plugin_class: "BasePlugin", errors: List[Error]):if not getattr(plugin_class, "PLUGIN_NAME", None):errors.append(- Error("Missing field PLUGIN_NAME for plugin - %s" % plugin_class.__name__)+ Error(+ "Missing field PLUGIN_NAME for plugin - %s"+ % plugin_class.__name__ # type: ignore+ ))diff --git a/saleor/extensions/manager.py b/saleor/extensions/manager.pyindex f077249539..cbf75c38ab 100644--- a/saleor/extensions/manager.py+++ b/saleor/extensions/manager.py@@ -8,11 +8,12 @@ from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRangefrom ..checkout import base_calculationsfrom ..core.payments import PaymentInterface-from ..core.taxes import TaxType, quantize_price+from ..core.taxes import TaxType, quantize_price, zero_taxed_moneyfrom .models import PluginConfigurationif TYPE_CHECKING:# flake8: noqa+ from django.db.models.query import QuerySetfrom .base_plugin import BasePluginfrom ..checkout.models import Checkout, CheckoutLinefrom ..discount.types import DiscountsListType@@ -30,7 +31,7 @@ if TYPE_CHECKING:class ExtensionsManager(PaymentInterface):"""Base manager for handling plugins logic."""- plugins = None+ plugins: list = []def __init__(self, plugins: List[str]):self.plugins = []@@ -51,7 +52,7 @@ class ExtensionsManager(PaymentInterface):def __run_method_on_single_plugin(self,- plugin: "BasePlugin",+ plugin: Optional["BasePlugin"],method_name: str,previous_value: Any,*args,@@ -116,6 +117,8 @@ class ExtensionsManager(PaymentInterface):)def calculate_order_shipping(self, order: "Order") -> TaxedMoney:+ if not order.shipping_method:+ return zero_taxed_money(order.currency)shipping_price = order.shipping_method.pricedefault_value = quantize_price(TaxedMoney(net=shipping_price, gross=shipping_price),@@ -143,7 +146,7 @@ class ExtensionsManager(PaymentInterface):)def get_tax_rate_type_choices(self) -> List[TaxType]:- default_value = []+ default_value: list = []return self.__run_method_on_plugins("get_tax_rate_type_choices", default_value)def show_taxes_on_storefront(self) -> bool:@@ -218,37 +221,37 @@ class ExtensionsManager(PaymentInterface):def authorize_payment(self, gateway: str, payment_information: "PaymentData"- ) -> Optional["GatewayResponse"]:+ ) -> "GatewayResponse":method_name = "authorize_payment"return self.__run_payment_method(gateway, method_name, payment_information)def capture_payment(self, gateway: str, payment_information: "PaymentData"- ) -> Optional["GatewayResponse"]:+ ) -> "GatewayResponse":method_name = "capture_payment"return self.__run_payment_method(gateway, method_name, payment_information)def refund_payment(self, gateway: str, payment_information: "PaymentData"- ) -> Optional["GatewayResponse"]:+ ) -> "GatewayResponse":method_name = "refund_payment"return self.__run_payment_method(gateway, method_name, payment_information)def void_payment(self, gateway: str, payment_information: "PaymentData"- ) -> Optional["GatewayResponse"]:+ ) -> "GatewayResponse":method_name = "void_payment"return self.__run_payment_method(gateway, method_name, payment_information)def confirm_payment(self, gateway: str, payment_information: "PaymentData"- ) -> Optional["GatewayResponse"]:+ ) -> "GatewayResponse":method_name = "confirm_payment"return self.__run_payment_method(gateway, method_name, payment_information)def process_payment(self, gateway: str, payment_information: "PaymentData"- ) -> Optional["GatewayResponse"]:+ ) -> "GatewayResponse":method_name = "process_payment"return self.__run_payment_method(gateway, method_name, payment_information)@@ -263,7 +266,7 @@ class ExtensionsManager(PaymentInterface):def list_payment_sources(self, gateway: str, customer_id: str) -> List["CustomerSource"]:- default_value = []+ default_value: list = []gtw = self.get_plugin(gateway)if gtw is not None:return self.__run_method_on_single_plugin(@@ -277,7 +280,7 @@ class ExtensionsManager(PaymentInterface):return [pluginfor plugin in plugins- if self.get_plugin_configuration(plugin.PLUGIN_NAME).active+ if getattr(self.get_plugin_configuration(plugin.PLUGIN_NAME), "active")]def list_payment_plugin_names(self, active_only: bool = False) -> List[str]:@@ -291,7 +294,7 @@ class ExtensionsManager(PaymentInterface):if payment_method in type(plugin).__dict__]- def list_payment_gateways(self, active_only: bool = True) -> List[dict]:+ def list_payment_gateways(self, active_only: bool = True) -> List[dict]: # type: ignorepayment_plugins = self.list_payment_plugin_names(active_only=active_only)return [{"name": plugin_name, "config": self.__get_payment_config(plugin_name)}@@ -300,7 +303,7 @@ class ExtensionsManager(PaymentInterface):def __get_payment_config(self, gateway: str) -> List[dict]:method_name = "get_payment_config"- default_value = []+ default_value: list = []gtw = self.get_plugin(gateway)return self.__run_method_on_single_plugin(gtw, method_name, default_value)@@ -310,7 +313,7 @@ class ExtensionsManager(PaymentInterface):method_name: str,payment_information: "PaymentData",**kwargs,- ) -> Optional["GatewayResponse"]:+ ) -> "GatewayResponse":default_value = Nonegtw = self.get_plugin(gateway)if gtw is not None:@@ -367,14 +370,16 @@ class ExtensionsManager(PaymentInterface):for plugin in self.plugins:if plugin.PLUGIN_NAME == plugin_name:return plugin+ return Nonedef get_plugin_configuration(self, plugin_name) -> Optional["PluginConfiguration"]:plugin = self.get_plugin(plugin_name)if plugin is not None:plugin_configurations_qs = PluginConfiguration.objects.all()return plugin.get_plugin_configuration(plugin_configurations_qs)+ return None- def get_plugin_configurations(self) -> List["PluginConfiguration"]:+ def get_plugin_configurations(self) -> "QuerySet[PluginConfiguration]":plugin_configuration_ids = []plugin_configurations_qs = PluginConfiguration.objects.all()for plugin in self.plugins:diff --git a/saleor/order/models.py b/saleor/order/models.pyindex ca239dbf77..62f7e6bb1e 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -1,5 +1,6 @@from decimal import Decimalfrom operator import attrgetter+from typing import Optionalfrom uuid import uuid4from django.conf import settings@@ -416,8 +417,10 @@ class OrderLine(models.Model):return self.quantity - self.quantity_fulfilled@property- def is_digital(self) -> bool:+ def is_digital(self) -> Optional[bool]:"""Check if a variant is digital and contains digital content."""+ if not self.variant:+ return Noneis_digital = self.variant.is_digital()has_digital = hasattr(self.variant, "digital_content")return is_digital and has_digitaldiff --git a/saleor/product/models.py b/saleor/product/models.pyindex 687c1a648e..cd2c18a759 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -1,5 +1,5 @@from decimal import Decimal-from typing import TYPE_CHECKING, Iterable, Union+from typing import TYPE_CHECKING, Iterable, Optional, Unionfrom uuid import uuid4from django.conf import settings@@ -214,7 +214,7 @@ class ProductsQueryset(PublishedQuerySet):ordering=([f"filtered_attribute__values__{field_name}"- for field_name in AttributeValue._meta.ordering+ for field_name in AttributeValue._meta.ordering or []]),),@@ -224,7 +224,7 @@ class ProductsQueryset(PublishedQuerySet):qs = qs.extra(order_by=[- Case(+ Case( # type: ignore# Make the products having no such attribute be last in the sortingWhen(concatenated_values=None, then=2),# Put the products having an empty attribute value at the bottom of@@ -602,7 +602,7 @@ class DigitalContentUrl(models.Model):self.token = str(uuid4()).replace("-", "")super().save(force_insert, force_update, using, update_fields)- def get_absolute_url(self) -> str:+ def get_absolute_url(self) -> Optional[str]:url = reverse("digital-product", kwargs={"token": str(self.token)})return build_absolute_uri(url)@@ -681,7 +681,7 @@ class AttributeProduct(SortableModel):Product,blank=True,through=AssignedProductAttribute,- through_fields=["assignment", "product"],+ through_fields=("assignment", "product"),related_name="attributesrelated",)@@ -706,7 +706,7 @@ class AttributeVariant(SortableModel):ProductVariant,blank=True,through=AssignedVariantAttribute,- through_fields=["assignment", "variant"],+ through_fields=("assignment", "variant"),related_name="attributesrelated",)@@ -744,7 +744,7 @@ class AttributeQuerySet(BaseAttributeQuerySet):id_sort = id_fieldelse:sort_method = sort_order_field.desc(nulls_first=True)- id_sort = id_field.desc()+ id_sort = id_field.desc() # type: ignorereturn self.order_by(sort_method, id_sort)@@ -770,14 +770,14 @@ class Attribute(ModelWithMetadata):blank=True,related_name="product_attributes",through=AttributeProduct,- through_fields=["attribute", "product_type"],+ through_fields=("attribute", "product_type"),)product_variant_types = models.ManyToManyField(ProductType,blank=True,related_name="variant_attributes",through=AttributeVariant,- through_fields=["attribute", "product_type"],+ through_fields=("attribute", "product_type"),)value_required = models.BooleanField(default=False, blank=True)@@ -930,7 +930,7 @@ class Collection(SeoModel, ModelWithMetadata, PublishableModel):blank=True,related_name="collections",through=CollectionProduct,- through_fields=["collection", "product"],+ through_fields=("collection", "product"),)background_image = VersatileImageField(upload_to="collection-backgrounds", blank=True, null=Truediff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 29bdd62026..ac9ec7e925 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -12,7 +12,7 @@ from .utils.variant_prices import ()-def _update_variants_names(instance: ProductVariant, saved_attributes: Iterable):+def _update_variants_names(instance: ProductType, saved_attributes: Iterable):"""Product variant names are created from names of assigned attributes.After change in attribute value name, for all product variants using this@@ -35,7 +35,7 @@ def _update_variants_names(instance: ProductVariant, saved_attributes: Iterable)@app.task-def update_variants_names(product_type_pk: List[int], saved_attributes_ids: List[int]):+def update_variants_names(product_type_pk: int, saved_attributes_ids: List[int]):instance = ProductType.objects.get(pk=product_type_pk)saved_attributes = Attribute.objects.filter(pk__in=saved_attributes_ids)_update_variants_names(instance, saved_attributes)diff --git a/saleor/product/utils/attributes.py b/saleor/product/utils/attributes.pyindex 9a88153070..3b2d9f9bcb 100644--- a/saleor/product/utils/attributes.py+++ b/saleor/product/utils/attributes.py@@ -1,4 +1,4 @@-from typing import Set, Union+from typing import TYPE_CHECKING, Optional, Set, Unionfrom ..models import (AssignedProductAttribute,@@ -12,6 +12,11 @@ from ..models import (AttributeAssignmentType = Union[AssignedProductAttribute, AssignedVariantAttribute]+if TYPE_CHECKING:+ # flake8: noqa+ from ..models import AttributeProduct, AttributeVariant++def generate_name_for_variant(variant: ProductVariant) -> str:"""Generate ProductVariant's name based on its attributes."""attributes_display = []@@ -25,13 +30,14 @@ def generate_name_for_variant(variant: ProductVariant) -> str:def _associate_attribute_to_instance(- instance: Union[Product, ProductVariant], attribute_pk: Attribute+ instance: Union[Product, ProductVariant], attribute_pk: int) -> AttributeAssignmentType:"""Associate a given attribute to an instance."""+ assignment: Union["AssignedProductAttribute", "AssignedVariantAttribute"]if isinstance(instance, Product):- attribute_rel = instance.product_type.attributeproduct.get(- attribute_id=attribute_pk- )+ attribute_rel: Union[+ "AttributeProduct", "AttributeVariant"+ ] = instance.product_type.attributeproduct.get(attribute_id=attribute_pk)assignment, _ = AssignedProductAttribute.objects.get_or_create(product=instance, assignment=attribute_reldiff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex de709ad209..b5d4774ce0 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -1,4 +1,4 @@-from typing import Union+from typing import TYPE_CHECKING, Unionfrom django.conf import settingsfrom django.contrib.postgres.fields import JSONField@@ -22,6 +22,11 @@ from ..core.weight import ()from . import ShippingMethodType+if TYPE_CHECKING:+ # flake8: noqa+ from ..checkout.models import Checkout+ from ..order.models import Order+def _applicable_weight_based_methods(weight, qs):"""Return weight based shipping methods that are applicable for the total weight."""diff --git a/saleor/site/models.py b/saleor/site/models.pyindex b477b90217..aaa4071478 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -66,7 +66,7 @@ class SiteSettings(models.Model):max_length=settings.DEFAULT_MAX_EMAIL_DISPLAY_NAME_LENGTH,blank=True,default="",- validators=EMAIL_SENDER_NAME_VALIDATORS,+ validators=EMAIL_SENDER_NAME_VALIDATORS, # type: ignore)default_mail_sender_address = models.EmailField(blank=True, null=True)customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)diff --git a/saleor/wishlist/models.py b/saleor/wishlist/models.pyindex c076986403..b36f73c041 100644--- a/saleor/wishlist/models.py+++ b/saleor/wishlist/models.py@@ -7,7 +7,8 @@ from ..product.models import Product, ProductVariantclass WishlistQuerySet(models.QuerySet):- def get_or_create(self, user: "User"): # pylint: disable=W0221+ def get_or_create(self, user: "User"): # type: ignore+ # pylint: disable=W0221try:return user.wishlistexcept self.model.DoesNotExist: