Skip to content

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

Enable return lint rules in Ruff

Patryk Zawadzkia3a599be6c43
diff --git a/pyproject.toml b/pyproject.toml
index 7121150b61..502a60bc7d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -200,6 +200,7 @@ target-version = "py39"
"PIE",
"PT",
"PYI",
+ "RET",
"T20",
"UP",
"W"
@@ -223,7 +224,8 @@ target-version = "py39"
"D407", # Missing dashed underline after section
"E501", # Line too long
"PT019", # Fixture without value is injected as parameter, use @pytest.mark.usefixtures instead
- "PYI041" # Use `float` instead of `int | float`
+ "PYI041", # Use `float` instead of `int | float`
+ "RET504" # Unnecessary assignment before return statement
]
[tool.ruff.lint.flake8-pytest-style]
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index b1f9c14d85..3c3091c828 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -131,7 +131,7 @@ class AddressForm(forms.ModelForm):
def clean(self):
data = super().clean()
if not data:
- return
+ return None
phone = data.get("phone")
country = data.get("country")
if phone:
@@ -228,7 +228,7 @@ def get_address_form_class(country_code):
return COUNTRY_FORMS.get(country_code, AddressForm)
-def get_form_i18n_lines(form_instance):
+def get_form_i18n_lines(form_instance) -> list[list[BoundField]]:
country_code = form_instance.i18n_country_code
try:
fields_order = i18naddress.get_field_order({"country_code": country_code})
@@ -248,6 +248,7 @@ def get_form_i18n_lines(form_instance):
if fields_order:
return [_convert_to_bound_fields(form_instance, line) for line in fields_order]
+ return []
def update_base_fields(form_class, i18n_rules):
diff --git a/saleor/account/management/commands/createsuperuser.py b/saleor/account/management/commands/createsuperuser.py
index 19794be69f..9531fc4c97 100644
--- a/saleor/account/management/commands/createsuperuser.py
+++ b/saleor/account/management/commands/createsuperuser.py
@@ -69,15 +69,14 @@ class Command(BaseCommand):
f"Required field '{field_name}' specifies a many-to-many "
"relation through model, which is not supported."
)
- else:
- parser.add_argument(
- f"--{field_name}",
- action="append",
- help=(
- f"Specifies the {field_name} for the superuser. Can be "
- "used multiple times."
- ),
- )
+ parser.add_argument(
+ f"--{field_name}",
+ action="append",
+ help=(
+ f"Specifies the {field_name} for the superuser. Can be "
+ "used multiple times."
+ ),
+ )
else:
parser.add_argument(
f"--{field_name}",
@@ -206,12 +205,11 @@ class Command(BaseCommand):
raise CommandError(
f"You must use --{self.UserModel.USERNAME_FIELD} with --noinput."
)
- else:
- error_msg = self._validate_username(
- username, verbose_field_name, database
- )
- if error_msg:
- raise CommandError(error_msg)
+ error_msg = self._validate_username(
+ username, verbose_field_name, database
+ )
+ if error_msg:
+ raise CommandError(error_msg)
user_data[self.UserModel.USERNAME_FIELD] = username
for field_name in self.UserModel.REQUIRED_FIELDS:
diff --git a/saleor/account/migrations/0041_permissions_to_groups.py b/saleor/account/migrations/0041_permissions_to_groups.py
index bf190b0084..bfbb15eb5c 100644
--- a/saleor/account/migrations/0041_permissions_to_groups.py
+++ b/saleor/account/migrations/0041_permissions_to_groups.py
@@ -55,6 +55,7 @@ def get_group_with_given_permissions(permissions, groups):
group_perm_pks = {perm.pk for perm in group.permissions.all()}
if group_perm_pks == set(permissions):
return group
+ return None
def create_group_with_given_permissions(perm_pks, counter, Group):
diff --git a/saleor/account/throttling.py b/saleor/account/throttling.py
index 65103883e2..9a39290139 100644
--- a/saleor/account/throttling.py
+++ b/saleor/account/throttling.py
@@ -51,9 +51,8 @@ def authenticate_with_throttling(request, email, password) -> Optional[models.Us
clear_cache([ip_key, ip_user_key, block_key])
return user
- else:
- # increment failed attempt for known user
- ip_user_attempts_count = increment_attempt(ip_user_key)
+ # increment failed attempt for known user
+ ip_user_attempts_count = increment_attempt(ip_user_key)
# increment failed attempt for whatever user
ip_attempts_count = increment_attempt(ip_key)
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index be0ea7c5ae..e269895bd0 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -48,7 +48,7 @@ def _clean_extension_url_with_only_path(
):
if target == AppExtensionTarget.APP_PAGE:
return
- elif manifest_data["appUrl"]:
+ if manifest_data["appUrl"]:
_clean_app_url(manifest_data["appUrl"])
else:
msg = (
diff --git a/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
index 0dc441666b..476451494f 100644
--- a/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
+++ b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
@@ -60,14 +60,14 @@ def clean_editor_js(definitions: Optional[dict], *, to_string: bool = False):
return " ".join(plain_text_list) if to_string else definitions
-def clean_text_data(text: str):
+def clean_text_data(text: str) -> str:
"""Look for url in text, check if URL is allowed and return the cleaned URL.
By default, only the protocol ``javascript`` is denied.
"""
if not text:
- return
+ return text
end_of_match = 0
new_text = ""
diff --git a/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
index 34ef498903..11327ee726 100644
--- a/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
+++ b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
@@ -67,7 +67,7 @@ def clean_text_data(text: str):
"""
if not text:
- return
+ return text
end_of_match = 0
new_text = ""
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 8bc4193553..c0a89a7227 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -154,7 +154,7 @@ def call_checkout_info_event(
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"] = None,
webhook_event_map: Optional[dict[str, set["Webhook"]]] = None,
-):
+) -> None:
checkout = checkout_info.checkout
if webhook_event_map is None:
webhook_event_map = get_webhooks_for_multiple_events(
@@ -176,7 +176,7 @@ def call_checkout_info_event(
possible_sync_events=WebhookEventSyncType.CHECKOUT_EVENTS,
):
call_event_including_protected_events(event_func, checkout, webhooks=webhooks)
- return None
+ return
_trigger_checkout_sync_webhooks(
manager,
@@ -187,7 +187,7 @@ def call_checkout_info_event(
)
call_event_including_protected_events(event_func, checkout, webhooks=webhooks)
- return None
+ return
def update_last_transaction_modified_at_for_checkout(
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index d932b425eb..9d61cad7b5 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -424,6 +424,7 @@ def _get_sale_id(line_discounts: list[OrderLineDiscount]):
if discount.type == DiscountType.PROMOTION:
if rule := discount.promotion_rule:
return get_sale_id(rule.promotion)
+ return None
def _create_lines_for_order(
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index de7bbc1329..f9e6a4ef0f 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -134,6 +134,8 @@ class CheckoutInfo:
new_shipping_method_id = convert_to_app_id_with_identifier(
external_shipping_method_id
)
+ if new_shipping_method_id is None:
+ return None
return methods.get(new_shipping_method_id)
delivery_method = _resolve_external_method
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index b7af3dac5e..40e9d1576e 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -306,6 +306,7 @@ def add_variants_to_checkout(
def _get_line_if_exist(line_data, lines_by_ids):
if line_data.line_id and line_data.line_id in lines_by_ids:
return lines_by_ids[line_data.line_id]
+ return None
def _append_line_to_update(to_update, to_delete, line_data, replace, line):
@@ -1032,8 +1033,7 @@ def get_checkout_metadata(checkout: "Checkout"):
if hasattr(checkout, "metadata_storage"):
# TODO: load metadata_storage with dataloader and pass as an argument
return checkout.metadata_storage
- else:
- return CheckoutMetadata(checkout=checkout)
+ return CheckoutMetadata(checkout=checkout)
def calculate_checkout_weight(lines: Iterable["CheckoutLineInfo"]) -> "Weight":
diff --git a/saleor/core/auth_backend.py b/saleor/core/auth_backend.py
index 84fd536fdc..497eef7274 100644
--- a/saleor/core/auth_backend.py
+++ b/saleor/core/auth_backend.py
@@ -140,7 +140,7 @@ def load_user_from_request(request):
raise jwt.InvalidTokenError(
"Invalid token. Create new one by using tokenCreate mutation."
)
- elif not user:
+ if not user:
raise jwt.InvalidTokenError(
"Invalid token. User does not exist or is inactive."
)
diff --git a/saleor/core/jwt_manager.py b/saleor/core/jwt_manager.py
index 3b3638b657..580c6083b7 100644
--- a/saleor/core/jwt_manager.py
+++ b/saleor/core/jwt_manager.py
@@ -207,12 +207,11 @@ class JWTManager(JWTManagerBase):
"Variable RSA_PRIVATE_KEY is not provided. "
"It is required for running in not DEBUG mode."
)
- else:
- msg = (
- "RSA_PRIVATE_KEY is missing. Using temporary key for local "
- "development with DEBUG mode."
- )
- logger.warning(color_style().WARNING(msg))
+ msg = (
+ "RSA_PRIVATE_KEY is missing. Using temporary key for local "
+ "development with DEBUG mode."
+ )
+ logger.warning(color_style().WARNING(msg))
cls.get_private_key.cache_clear()
cls.get_public_key.cache_clear()
diff --git a/saleor/core/tasks.py b/saleor/core/tasks.py
index f4a44f0834..977741023e 100644
--- a/saleor/core/tasks.py
+++ b/saleor/core/tasks.py
@@ -34,7 +34,7 @@ class RestrictWriterDBTask(Task):
func_path = settings.CELERY_RESTRICT_WRITER_METHOD
if not func_path:
- return
+ return None
try:
wrapper_fun = import_string(func_path)
diff --git a/saleor/core/utils/date_time.py b/saleor/core/utils/date_time.py
index df1e983632..feea6555ea 100644
--- a/saleor/core/utils/date_time.py
+++ b/saleor/core/utils/date_time.py
@@ -1,10 +1,10 @@
import datetime
-def convert_to_utc_date_time(date):
+def convert_to_utc_date_time(date) -> None | datetime.datetime:
"""Convert date into utc date time."""
if date is None:
- return
+ return None
return datetime.datetime.combine(
date, datetime.datetime.min.time(), tzinfo=datetime.UTC
)
diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.py
index e045025fb9..9702fb51cc 100644
--- a/saleor/discount/utils/order.py
+++ b/saleor/discount/utils/order.py
@@ -68,13 +68,13 @@ def create_order_line_discount_objects(
lines_info: Iterable["EditableOrderLineInfo"],
discount_data: tuple[
list[dict],
- list["OrderLineDiscount"],
- list["OrderLineDiscount"],
+ list[OrderLineDiscount],
+ list[OrderLineDiscount],
list[str],
],
-):
+) -> None | list["EditableOrderLineInfo"]:
if not discount_data or not lines_info:
- return
+ return None
(
discounts_to_create_inputs,
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index a4ced6f84f..8f297dcb8f 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -178,7 +178,7 @@ def prepare_line_discount_objects_for_catalogue_promotions(lines_info):
updated_fields: list[str] = []
if not lines_info:
- return
+ return None
for line_info in lines_info:
line = line_info.line
@@ -403,7 +403,7 @@ def get_best_rule(
)
if not rule_discounts:
- return
+ return None
best_rule, best_discount_amount, gift_listing = max(
rule_discounts, key=lambda x: x.discount_amount
@@ -543,26 +543,25 @@ def _get_defaults_for_gift_line(
"quantity": 1,
"currency": order_or_checkout.currency,
}
- else:
- variant = (
- ProductVariant.objects.filter(id=variant_id)
- .select_related("product")
- .only("sku", "product__name")
- .first()
- )
- return {
- "variant_id": variant_id,
- "product_name": variant.product.name if variant else "",
- "product_sku": variant.sku if variant else "",
- "quantity": 1,
- "currency": order_or_checkout.currency,
- "unit_price_net_amount": Decimal(0),
- "unit_price_gross_amount": Decimal(0),
- "total_price_net_amount": Decimal(0),
- "total_price_gross_amount": Decimal(0),
- "is_shipping_required": True,
- "is_gift_card": False,
- }
+ variant = (
+ ProductVariant.objects.filter(id=variant_id)
+ .select_related("product")
+ .only("sku", "product__name")
+ .first()
+ )
+ return {
+ "variant_id": variant_id,
+ "product_name": variant.product.name if variant else "",
+ "product_sku": variant.sku if variant else "",
+ "quantity": 1,
+ "currency": order_or_checkout.currency,
+ "unit_price_net_amount": Decimal(0),
+ "unit_price_gross_amount": Decimal(0),
+ "total_price_net_amount": Decimal(0),
+ "total_price_gross_amount": Decimal(0),
+ "is_shipping_required": True,
+ "is_gift_card": False,
+ }
def get_variants_to_promotion_rules_map(
diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.py
index e7a108b40c..f3a8f71d33 100644
--- a/saleor/discount/utils/voucher.py
+++ b/saleor/discount/utils/voucher.py
@@ -427,7 +427,7 @@ def prepare_line_discount_objects_for_voucher(
updated_fields: list[str] = []
if not lines_info:
- return
+ return None
for line_info in lines_info:
line = line_info.line
diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
index 45dac661b7..991bbcceee 100644
--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
@@ -355,8 +355,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
def _get_customer(cls, customer_id, external_ref):
if customer_id:
return lambda customer: str(customer.id) == customer_id
- else:
- return lambda customer: customer.external_reference == external_ref
+ return lambda customer: customer.external_reference == external_ref
@classmethod
def update_address(cls, info, instance, data, field):
diff --git a/saleor/graphql/account/bulk_mutations/user_bulk_set_active.py b/saleor/graphql/account/bulk_mutations/user_bulk_set_active.py
index 0f5d53e2ce..76085318b7 100644
--- a/saleor/graphql/account/bulk_mutations/user_bulk_set_active.py
+++ b/saleor/graphql/account/bulk_mutations/user_bulk_set_active.py
@@ -42,7 +42,7 @@ class UserBulkSetActive(BaseBulkMutation):
)
}
)
- elif instance.is_superuser:
+ if instance.is_superuser:
raise ValidationError(
{
"is_active": ValidationError(
diff --git a/saleor/graphql/account/dataloaders.py b/saleor/graphql/account/dataloaders.py
index 9512635a69..8941af283d 100644
--- a/saleor/graphql/account/dataloaders.py
+++ b/saleor/graphql/account/dataloaders.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from collections.abc import Iterable
-from typing import Optional, cast
+from typing import Generic, Optional, TypeVar, cast
from ...account.models import Address, CustomerEvent, Group, User
from ...channel.models import Channel
@@ -10,7 +10,7 @@ from ...thumbnail.utils import get_thumbnail_format
from ..core.dataloaders import DataLoader
-class AddressByIdLoader(DataLoader):
+class AddressByIdLoader(DataLoader[int, Address]):
context_key = "address_by_id"
def batch_load(self, keys):
@@ -18,7 +18,7 @@ class AddressByIdLoader(DataLoader):
return [address_map.get(address_id) for address_id in keys]
-class UserByUserIdLoader(DataLoader):
+class UserByUserIdLoader(DataLoader[str, User]):
context_key = "user_by_id"
def batch_load(self, keys):
@@ -26,7 +26,7 @@ class UserByUserIdLoader(DataLoader):
return [user_map.get(user_id) for user_id in keys]
-class CustomerEventsByUserLoader(DataLoader):
+class CustomerEventsByUserLoader(DataLoader[str, list[CustomerEvent]]):
context_key = "customer_events_by_user"
def batch_load(self, keys):
@@ -60,7 +60,7 @@ class ThumbnailByUserIdSizeAndFormatLoader(
return [thumbnails_by_user_size_and_format_map.get(key) for key in keys]
-class UserByEmailLoader(DataLoader):
+class UserByEmailLoader(DataLoader[str, User]):
context_key = "user_by_email"
def batch_load(self, keys):
@@ -72,7 +72,7 @@ class UserByEmailLoader(DataLoader):
return [user_map.get(email) for email in keys]
-class PermissionByCodenameLoader(DataLoader):
+class PermissionByCodenameLoader(DataLoader[str, Permission]):
context_key = "permission_by_codename"
def batch_load(self, keys):
@@ -84,7 +84,10 @@ class PermissionByCodenameLoader(DataLoader):
return [permission_map.get(codename) for codename in keys]
-class BaseAccessibleChannels(DataLoader):
+K = TypeVar("K")
+
+
+class BaseAccessibleChannels(DataLoader[K, list[Channel]], Generic[K]):
def get_group_to_channels_map(self, group_ids):
groups_with_no_channel_restriction = Group.objects.using(
self.database_connection_name
@@ -126,7 +129,7 @@ class BaseAccessibleChannels(DataLoader):
return group_to_channels
-class AccessibleChannelsByGroupIdLoader(BaseAccessibleChannels):
+class AccessibleChannelsByGroupIdLoader(BaseAccessibleChannels[int]):
context_key = "accessiblechannels_by_group"
def batch_load(self, keys):
@@ -134,7 +137,7 @@ class AccessibleChannelsByGroupIdLoader(BaseAccessibleChannels):
return [group_to_channels.get(group_id, []) for group_id in keys]
-class AccessibleChannelsByUserIdLoader(BaseAccessibleChannels):
+class AccessibleChannelsByUserIdLoader(BaseAccessibleChannels[str]):
context_key = "accessiblechannels_by_user"
def batch_load(self, keys):
@@ -157,7 +160,7 @@ class AccessibleChannelsByUserIdLoader(BaseAccessibleChannels):
return [list(user_to_channels[user_id]) for user_id in keys]
-class RestrictedChannelAccessByUserIdLoader(DataLoader):
+class RestrictedChannelAccessByUserIdLoader(DataLoader[int, bool]):
context_key = "restrictedchannelaccess_by_user"
def batch_load(self, keys):
diff --git a/saleor/graphql/account/enums.py b/saleor/graphql/account/enums.py
index 60fbd6c47f..fb5fef675d 100644
--- a/saleor/graphql/account/enums.py
+++ b/saleor/graphql/account/enums.py
@@ -36,6 +36,6 @@ class StaffMemberStatus(BaseEnum):
def description(self):
if self == StaffMemberStatus.ACTIVE:
return "User account has been activated."
- elif self == StaffMemberStatus.DEACTIVATED:
+ if self == StaffMemberStatus.DEACTIVATED:
return "User account has not been activated yet."
return None
diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.py
index ea9c233ad2..e36e77de12 100644
--- a/saleor/graphql/account/i18n.py
+++ b/saleor/graphql/account/i18n.py
@@ -210,7 +210,7 @@ class I18nMixin:
)
}
)
- elif info and not all_permissions_required(info.context, required_permissions):
+ if info and not all_permissions_required(info.context, required_permissions):
raise PermissionDenied(
f"To skip address validation, you need following permissions: "
f"{', '.join(perm.name for perm in required_permissions)}.",
diff --git a/saleor/graphql/account/mutations/account/account_register.py b/saleor/graphql/account/mutations/account/account_register.py
index 54793a72c6..2d61b82f39 100644
--- a/saleor/graphql/account/mutations/account/account_register.py
+++ b/saleor/graphql/account/mutations/account/account_register.py
@@ -109,7 +109,7 @@ class AccountRegister(ModelMutation):
site = get_site_promise(info.context).get()
if not site.settings.enable_account_confirmation_by_email:
return super().clean_input(info, instance, data, **kwargs)
- elif not data.get("redirect_url"):
+ if not data.get("redirect_url"):
raise ValidationError(
{
"redirect_url": ValidationError(
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index f5ea61e726..a87f4aa4e1 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -393,7 +393,7 @@ class UserDeleteMixin:
)
}
)
- elif instance.is_superuser:
+ if instance.is_superuser:
raise ValidationError(
{
"id": ValidationError(
diff --git a/saleor/graphql/account/mutations/permission_group/permission_group_update.py b/saleor/graphql/account/mutations/permission_group/permission_group_update.py
index ad2a3f12a3..0839083ad8 100644
--- a/saleor/graphql/account/mutations/permission_group/permission_group_update.py
+++ b/saleor/graphql/account/mutations/permission_group/permission_group_update.py
@@ -281,7 +281,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
errors: dict,
cleaned_input: dict,
group: models.Group,
- ):
+ ) -> None:
"""Check if after removing users from group all permissions will be manageable.
After removing users from group, for each permission, there should be
@@ -298,7 +298,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
# check if user with manage staff will be added to the group
if add_users:
if any(user.has_perm(manage_staff_permission) for user in add_users):
- return True
+ return
permissions = get_not_manageable_permissions_after_removing_users_from_group(
group, remove_users
diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.py
index 6212345fda..fe33d75ceb 100644
--- a/saleor/graphql/account/resolvers.py
+++ b/saleor/graphql/account/resolvers.py
@@ -131,7 +131,7 @@ def resolve_users(info, ids=None, emails=None):
if ids and emails:
return qs.filter(Q(id__in=ids) | Q(email__in=emails))
- elif ids:
+ if ids:
return qs.filter(id__in=ids)
return qs.filter(email__in=emails)
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index c17fe9ffa8..8698c358d7 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -637,9 +637,9 @@ class User(ModelObjectType[models.User]):
info: ResolveInfo,
size: Optional[int] = None,
format: Optional[str] = None,
- ):
+ ) -> None | Image | Promise[Image]:
if not root.avatar:
- return
+ return None
if size == 0:
return Image(url=root.avatar.url, alt=None)
diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.py
index b6f55d69b1..f033c57c20 100644
--- a/saleor/graphql/app/dataloaders.py
+++ b/saleor/graphql/app/dataloaders.py
@@ -13,7 +13,7 @@ from ..core import SaleorContext
from ..core.dataloaders import BaseThumbnailBySizeAndFormatLoader, DataLoader
-class AppByIdLoader(DataLoader):
+class AppByIdLoader(DataLoader[str, App]):
context_key = "app_by_id"
def batch_load(self, keys):
@@ -25,7 +25,7 @@ class AppByIdLoader(DataLoader):
return [apps.get(key) for key in keys]
-class AppExtensionByIdLoader(DataLoader):
+class AppExtensionByIdLoader(DataLoader[str, AppExtension]):
context_key = "app_extension_by_id"
def batch_load(self, keys):
@@ -35,7 +35,7 @@ class AppExtensionByIdLoader(DataLoader):
return [extensions.get(key) for key in keys]
-class AppExtensionByAppIdLoader(DataLoader):
+class AppExtensionByAppIdLoader(DataLoader[str, AppExtension]):
context_key = "app_extension_by_app_id"
def batch_load(self, keys):
@@ -50,7 +50,7 @@ class AppExtensionByAppIdLoader(DataLoader):
return [extensions_map.get(app_id, []) for app_id in keys]
-class ActiveAppsByAppIdentifierLoader(DataLoader):
+class ActiveAppsByAppIdentifierLoader(DataLoader[str, App]):
context_key = "apps_by_app_identifier"
def batch_load(self, keys):
@@ -63,7 +63,7 @@ class ActiveAppsByAppIdentifierLoader(DataLoader):
return [apps_map.get(app_identifier, []) for app_identifier in keys]
-class AppTokensByAppIdLoader(DataLoader):
+class AppTokensByAppIdLoader(DataLoader[str, AppToken]):
context_key = "app_tokens_by_app_id"
def batch_load(self, keys):
@@ -76,7 +76,7 @@ class AppTokensByAppIdLoader(DataLoader):
return [tokens_by_app_map.get(app_id, []) for app_id in keys]
-class AppByTokenLoader(DataLoader):
+class AppByTokenLoader(DataLoader[str, App]):
context_key = "app_by_token"
def batch_load(self, keys):
diff --git a/saleor/graphql/app/enums.py b/saleor/graphql/app/enums.py
index 2bf4783c88..bf6fd66b12 100644
--- a/saleor/graphql/app/enums.py
+++ b/saleor/graphql/app/enums.py
@@ -6,13 +6,13 @@ from ..core.enums import to_enum
def description(enum):
if enum is None:
return "Enum determining type of your App."
- elif enum == AppTypeEnum.LOCAL:
+ if enum == AppTypeEnum.LOCAL:
return (
"Local Saleor App. The app is fully manageable from dashboard. "
"You can change assigned permissions, add webhooks, "
"or authentication token"
)
- elif enum == AppTypeEnum.THIRDPARTY:
+ if enum == AppTypeEnum.THIRDPARTY:
return (
"Third party external App. Installation is fully automated. "
"Saleor uses a defined App manifest to gather all required information."
diff --git a/saleor/graphql/app/schema.py b/saleor/graphql/app/schema.py
index a3096e1575..7309fe2b69 100644
--- a/saleor/graphql/app/schema.py
+++ b/saleor/graphql/app/schema.py
@@ -138,7 +138,7 @@ class AppQueries(graphene.ObjectType):
_, app_id = from_global_id_or_error(id, only_type="App")
if int(app_id) == app.id:
return app
- elif not app.has_perm(AppPermission.MANAGE_APPS):
+ if not app.has_perm(AppPermission.MANAGE_APPS):
raise PermissionDenied(permissions=[AppPermission.MANAGE_APPS])
return resolve_app(info, id)
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index cf6a57a008..1696d4f0a6 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -595,6 +595,7 @@ class App(ModelObjectType[models.App]):
def resolve_brand(root: models.App, _info: ResolveInfo):
if root.brand_logo_default:
return root
+ return None
class AppCountableConnection(CountableConnection):
@@ -623,3 +624,4 @@ class AppInstallation(ModelObjectType[models.AppInstallation]):
def resolve_brand(root: models.AppInstallation, _info: ResolveInfo):
if root.brand_logo_default:
return root
+ return None
diff --git a/saleor/graphql/attribute/dataloaders.py b/saleor/graphql/attribute/dataloaders.py
index 17937221b7..63226ec227 100644
--- a/saleor/graphql/attribute/dataloaders.py
+++ b/saleor/graphql/attribute/dataloaders.py
@@ -4,7 +4,7 @@ from ...attribute.models import Attribute, AttributeValue
from ..core.dataloaders import DataLoader
-class AttributeValuesByAttributeIdLoader(DataLoader):
+class AttributeValuesByAttributeIdLoader(DataLoader[int, list[AttributeValue]]):
context_key = "attributevalues_by_attribute"
def batch_load(self, keys):
@@ -19,7 +19,7 @@ class AttributeValuesByAttributeIdLoader(DataLoader):
return [attribute_to_attributevalues[attribute_id] for attribute_id in keys]
-class AttributesByAttributeId(DataLoader):
+class AttributesByAttributeId(DataLoader[int, Attribute]):
context_key = "attributes_by_id"
def batch_load(self, keys):
@@ -29,7 +29,7 @@ class AttributesByAttributeId(DataLoader):
return [attributes.get(key) for key in keys]
-class AttributeValueByIdLoader(DataLoader):
+class AttributeValueByIdLoader(DataLoader[int, AttributeValue]):
context_key = "attributevalue_by_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.py
index 8bf0474d64..3838a5fac2 100644
--- a/saleor/graphql/attribute/filters.py
+++ b/saleor/graphql/attribute/filters.py
@@ -215,7 +215,7 @@ def filter_with_choices(qs, _, value):
lookup = Q(input_type__in=AttributeInputType.TYPES_WITH_CHOICES)
if value is True:
return qs.filter(lookup)
- elif value is False:
+ if value is False:
return qs.exclude(lookup)
return qs.none()
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 5384a3d74b..8bfedfc936 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -91,22 +91,22 @@ class AttributeValue(ModelObjectType[models.AttributeValue]):
)
@staticmethod
- def resolve_file(root: models.AttributeValue, _info: ResolveInfo):
+ def resolve_file(root: models.AttributeValue, _info: ResolveInfo) -> None | File:
if not root.file_url:
- return
+ return None
return File(url=root.file_url, content_type=root.content_type)
@staticmethod
def resolve_reference(root: models.AttributeValue, info: ResolveInfo):
- def prepare_reference(attribute):
+ def prepare_reference(attribute) -> None | str:
if attribute.input_type != AttributeInputType.REFERENCE:
- return
+ return None
reference_field = AttributeAssignmentMixin.ENTITY_TYPE_MAPPING[
attribute.entity_type
].value_field
reference_pk = getattr(root, f"{reference_field}_id", None)
if reference_pk is None:
- return
+ return None
reference_id = graphene.Node.to_global_id(
attribute.entity_type, reference_pk
)
diff --git a/saleor/graphql/channel/dataloaders.py b/saleor/graphql/channel/dataloaders.py
index 6e029e7235..1a2017f48d 100644
--- a/saleor/graphql/channel/dataloaders.py
+++ b/saleor/graphql/channel/dataloaders.py
@@ -1,3 +1,5 @@
+from uuid import UUID
+
from django.db.models import Exists, OuterRef
from ...channel.models import Channel
@@ -6,7 +8,7 @@ from ..core.dataloaders import DataLoader
from ..order.dataloaders import OrderByIdLoader
-class ChannelByIdLoader(DataLoader):
+class ChannelByIdLoader(DataLoader[int, Channel]):
context_key = "channel_by_id"
def batch_load(self, keys):
@@ -14,7 +16,7 @@ class ChannelByIdLoader(DataLoader):
return [channels.get(channel_id) for channel_id in keys]
-class ChannelBySlugLoader(DataLoader):
+class ChannelBySlugLoader(DataLoader[str, Channel]):
context_key = "channel_by_slug"
def batch_load(self, keys):
@@ -24,7 +26,7 @@ class ChannelBySlugLoader(DataLoader):
return [channels.get(slug) for slug in keys]
-class ChannelByOrderIdLoader(DataLoader):
+class ChannelByOrderIdLoader(DataLoader[UUID, Channel]):
context_key = "channel_by_order"
def batch_load(self, keys):
@@ -46,7 +48,7 @@ class ChannelByOrderIdLoader(DataLoader):
return OrderByIdLoader(self.context).load_many(keys).then(with_orders)
-class ChannelWithHasOrdersByIdLoader(DataLoader):
+class ChannelWithHasOrdersByIdLoader(DataLoader[int, Channel]):
context_key = "channel_with_has_orders_by_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/checkout/dataloaders/models.py b/saleor/graphql/checkout/dataloaders/models.py
index 8f575ebd03..12f0ee21fe 100644
--- a/saleor/graphql/checkout/dataloaders/models.py
+++ b/saleor/graphql/checkout/dataloaders/models.py
@@ -1,8 +1,10 @@
from collections import defaultdict
from collections.abc import Iterable
+from uuid import UUID
from django.db.models import F
+from ....channel.models import Channel
from ....checkout.models import Checkout, CheckoutLine, CheckoutMetadata
from ....payment.models import TransactionItem
from ...channel.dataloaders import ChannelByIdLoader
@@ -76,7 +78,7 @@ class CheckoutLinesByCheckoutTokenLoader(DataLoader[str, list[CheckoutLine]]):
return [line_map.get(checkout_id, []) for checkout_id in keys]
-class ChannelByCheckoutIDLoader(DataLoader):
+class ChannelByCheckoutIDLoader(DataLoader[UUID, Channel]):
context_key = "channel_by_checkout"
def batch_load(self, keys):
diff --git a/saleor/graphql/checkout/dataloaders/promotion_rule_infos.py b/saleor/graphql/checkout/dataloaders/promotion_rule_infos.py
index 5f7c660bf0..b62521a395 100644
--- a/saleor/graphql/checkout/dataloaders/promotion_rule_infos.py
+++ b/saleor/graphql/checkout/dataloaders/promotion_rule_infos.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from uuid import UUID
from promise import Promise
@@ -19,7 +20,9 @@ from ...translations.dataloaders import (
from .models import CheckoutByTokenLoader, CheckoutLineByIdLoader
-class VariantPromotionRuleInfoByCheckoutLineIdLoader(DataLoader):
+class VariantPromotionRuleInfoByCheckoutLineIdLoader(
+ DataLoader[UUID, list[VariantPromotionRuleInfo]]
+):
context_key = "variant_promotion_rule_info_by_checkout_line_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 09c8d07f23..5d98bd7502 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -189,7 +189,7 @@ def check_lines_quantity(
}
)
- elif allow_zero_quantity and quantity < 0:
+ if allow_zero_quantity and quantity < 0:
raise ValidationError(
{
"quantity": ValidationError(
@@ -491,18 +491,18 @@ def check_permissions_for_custom_prices(app, lines):
def find_line_id_when_variant_parameter_used(
variant_db_id: str, lines_info: list[CheckoutLineInfo]
-):
+) -> None | str:
"""Return line id when variantId parameter was used.
If variant exists in multiple lines error will be returned.
"""
if not lines_info:
- return
+ return None
line_info = list(filter(lambda x: (x.variant.pk == int(variant_db_id)), lines_info))
if not line_info:
- return
+ return None
# if same variant occur in multiple lines `lineId` parameter have to be used
if len(line_info) > 1:
@@ -526,10 +526,10 @@ def find_line_id_when_variant_parameter_used(
def find_variant_id_when_line_parameter_used(
line_db_id: str, lines_info: list[CheckoutLineInfo]
-):
+) -> None | str:
"""Return variant id when lineId parameter was used."""
if not lines_info:
- return
+ return None
line_info = list(filter(lambda x: (str(x.line.pk) == line_db_id), lines_info))
return str(line_info[0].line.variant_id)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 297a286190..5545d8eb2d 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -800,13 +800,13 @@ class Checkout(ModelObjectType[models.Checkout]):
@staticmethod
def resolve_shipping_address(root: models.Checkout, info: ResolveInfo):
if not root.shipping_address_id:
- return
+ return None
return AddressByIdLoader(info.context).load(root.shipping_address_id)
@staticmethod
def resolve_billing_address(root: models.Checkout, info: ResolveInfo):
if not root.billing_address_id:
- return
+ return None
return AddressByIdLoader(info.context).load(root.billing_address_id)
@staticmethod
@@ -833,7 +833,7 @@ class Checkout(ModelObjectType[models.Checkout]):
if not delivery_method or not isinstance(
delivery_method, ShippingMethodData
):
- return
+ return None
return delivery_method
return (
diff --git a/saleor/graphql/context.py b/saleor/graphql/context.py
index f50d02e241..572f486b20 100644
--- a/saleor/graphql/context.py
+++ b/saleor/graphql/context.py
@@ -57,7 +57,7 @@ def get_user(request: SaleorContext) -> Optional[User]:
def set_auth_on_context(request: SaleorContext):
if hasattr(request, "app") and request.app:
request.user = SimpleLazyObject(lambda: None) # type: ignore
- return request
+ return
def user():
return get_user(request) or None
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index d2cf634c72..53187a67d6 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -168,9 +168,9 @@ def _get_sorting_fields(sort_by, qs):
sorting_attribute = sort_by.get("attribute_id")
if sorting_fields and not isinstance(sorting_fields, list):
return [sorting_fields]
- elif not sorting_fields and sorting_attribute is not None:
+ if not sorting_fields and sorting_attribute is not None:
return qs.model.sort_by_attribute_fields()
- elif not sorting_fields:
+ if not sorting_fields:
raise ValueError("Error while preparing cursor values.")
return sorting_fields
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index bab2647ad7..55b836d408 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -115,7 +115,7 @@ def validation_error_to_error_type(
def attach_error_params(error, params: Optional[dict], error_class_fields: set):
if not params:
- return {}
+ return
# If some of the params key overlap with error class fields
# attach param value to the error
error_fields_in_params = set(params.keys()) & error_class_fields
@@ -228,7 +228,7 @@ class BaseMutation(graphene.Mutation):
info: ResolveInfo,
graphene_type: type[ModelObjectType[MT]],
pk: Union[int, str],
- qs=None,
+ qs: Optional[QuerySet[MT]] = None,
) -> Optional[MT]:
"""Attempt to resolve a node from the given internal ID.
@@ -831,6 +831,7 @@ class ModelWithExtRefMutation(ModelMutation):
if object_id:
model_type = cls.get_type_for_model()
return cls.get_node_or_error(info, object_id, only_type=model_type, qs=qs)
+ return None
class ModelWithRestrictedChannelAccessMutation(ModelMutation):
diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.py
index 99983869ad..58dd057885 100644
--- a/saleor/graphql/core/scalars.py
+++ b/saleor/graphql/core/scalars.py
@@ -20,12 +20,13 @@ class Decimal(graphene.Float):
"""
@staticmethod
- def parse_literal(node):
+ def parse_literal(node) -> decimal.Decimal | None:
if isinstance(node, (ast.FloatValue, ast.IntValue)):
try:
return decimal.Decimal(node.value)
except decimal.DecimalException:
return None
+ return None
@staticmethod
def parse_value(value):
@@ -67,7 +68,7 @@ class JSON(GenericScalar):
field.name.value: GenericScalar.parse_literal(field.value)
for field in node.fields
}
- elif isinstance(node, ast.ListValue):
+ if isinstance(node, ast.ListValue):
return [GenericScalar.parse_literal(value) for value in node.values]
return None
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index ebc410fb8f..4cadbf0299 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -130,7 +130,7 @@ def test_filter_input():
def created_filter(self, queryset, _, value):
if CreatedEnum.WEEK == value:
return queryset
- elif CreatedEnum.YEAR == value:
+ if CreatedEnum.YEAR == value:
return queryset
return queryset
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index ed7a60d33b..59132dd81f 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -943,7 +943,7 @@ class Job(graphene.Interface):
@traced_resolver
def resolve_type(cls, instance, _info: "ResolveInfo"):
"""Map a data object to a Graphene type."""
- return None # FIXME: why do we have this method?
+ return # FIXME: why do we have this method?
class TimePeriod(graphene.ObjectType):
diff --git a/saleor/graphql/core/types/converter.py b/saleor/graphql/core/types/converter.py
index 2a2ae9b5cf..4ff666f381 100644
--- a/saleor/graphql/core/types/converter.py
+++ b/saleor/graphql/core/types/converter.py
@@ -21,11 +21,12 @@ from ..filters import (
from .common import NonNullList
-def get_form_field_description(field):
+def get_form_field_description(field) -> str | None:
if hasattr(field, "help_text"):
return field.help_text or None
- elif hasattr(field, "extra"):
+ if hasattr(field, "extra"):
return field.extra.get("help_text") or None
+ return None
@singledispatch
diff --git a/saleor/graphql/core/types/model.py b/saleor/graphql/core/types/model.py
index 7d10fe86a8..9a4861a77f 100644
--- a/saleor/graphql/core/types/model.py
+++ b/saleor/graphql/core/types/model.py
@@ -35,7 +35,7 @@ class ModelObjectType(Generic[MT], BaseObjectType):
raise ValueError(
"ModelObjectType was declared without 'model' option in it's Meta."
)
- elif not issubclass(options["model"], Model):
+ if not issubclass(options["model"], Model):
raise ValueError(
"ModelObjectType was declared with invalid 'model' option value "
"in it's Meta. Expected subclass of django.db.models.Model, "
diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.py
index b517d7abad..50572bc9dd 100644
--- a/saleor/graphql/core/types/taxes.py
+++ b/saleor/graphql/core/types/taxes.py
@@ -185,7 +185,7 @@ class TaxableObjectLine(BaseObjectType):
if isinstance(root, CheckoutLine):
checkout = CheckoutByTokenLoader(info.context).load(root.checkout_id)
- def load_channel(checkout):
+ def load_channel_for_checkout(checkout):
country_code = checkout.get_country()
load_tax_config_with_country = partial(
load_tax_configuration, country_code=country_code
@@ -196,22 +196,21 @@ class TaxableObjectLine(BaseObjectType):
.then(load_tax_config_with_country)
)
- return checkout.then(load_channel)
- else:
- order = OrderByIdLoader(info.context).load(root.order_id)
+ return checkout.then(load_channel_for_checkout)
+ order = OrderByIdLoader(info.context).load(root.order_id)
- def load_channel(order):
- country_code = get_order_country(order)
- load_tax_config_with_country = partial(
- load_tax_configuration, country_code=country_code
- )
- return (
- ChannelByIdLoader(info.context)
- .load(order.channel_id)
- .then(load_tax_config_with_country)
- )
+ def load_channel_for_order(order):
+ country_code = get_order_country(order)
+ load_tax_config_with_country = partial(
+ load_tax_configuration, country_code=country_code
+ )
+ return (
+ ChannelByIdLoader(info.context)
+ .load(order.channel_id)
+ .then(load_tax_config_with_country)
+ )
- return order.then(load_channel)
+ return order.then(load_channel_for_order)
@staticmethod
def resolve_unit_price(root: Union[CheckoutLine, OrderLine], info: ResolveInfo):
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index 83779fcc82..d5502b504f 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -2,7 +2,7 @@ import binascii
import os
import secrets
from dataclasses import dataclass
-from typing import Literal, Optional, Union, overload
+from typing import Literal, NoReturn, Optional, Union, overload
import graphene
from django.conf import settings
@@ -123,7 +123,7 @@ def add_hash_to_file_name(file):
file._name = new_name
-def raise_validation_error(field=None, message=None, code=None):
+def raise_validation_error(field=None, message=None, code=None) -> NoReturn:
raise ValidationError({field: ValidationError(message, code=code)})
@@ -141,12 +141,11 @@ def ext_ref_to_global_id_or_error(
)
if internal_id:
return graphene.Node.to_global_id(model.__name__, internal_id)
- else:
- raise_validation_error(
- field="externalReference",
- message=f"Couldn't resolve to a node: {external_reference}",
- code="not_found",
- )
+ raise_validation_error(
+ field="externalReference",
+ message=f"Couldn't resolve to a node: {external_reference}",
+ code="not_found",
+ )
@dataclass
diff --git a/saleor/graphql/core/utils/resolvers.py b/saleor/graphql/core/utils/resolvers.py
index 38ac1fc51e..c52c4f1cc8 100644
--- a/saleor/graphql/core/utils/resolvers.py
+++ b/saleor/graphql/core/utils/resolvers.py
@@ -12,12 +12,11 @@ def resolve_by_global_id_or_ext_ref(info, model, id, external_reference):
.filter(id=id)
.first()
)
- else:
- return (
- model.objects.using(get_database_connection_name(info.context))
- .filter(external_reference=external_reference)
- .first()
- )
+ return (
+ model.objects.using(get_database_connection_name(info.context))
+ .filter(external_reference=external_reference)
+ .first()
+ )
def resolve_by_global_id_slug_or_ext_ref(info, model, id, slug, external_reference):
@@ -31,15 +30,14 @@ def resolve_by_global_id_slug_or_ext_ref(info, model, id, slug, external_referen
.filter(id=id)
.first()
)
- elif slug:
+ if slug:
return (
model.objects.using(get_database_connection_name(info.context))
.filter(slug=slug)
.first()
)
- else:
- return (
- model.objects.using(get_database_connection_name(info.context))
- .filter(external_reference=external_reference)
- .first()
- )
+ return (
+ model.objects.using(get_database_connection_name(info.context))
+ .filter(external_reference=external_reference)
+ .first()
+ )
diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.py
index 35b039d60e..b9acb8e0d4 100644
--- a/saleor/graphql/core/validators/file.py
+++ b/saleor/graphql/core/validators/file.py
@@ -109,7 +109,7 @@ def _validate_image_format(file, field_name, error_class):
)
}
)
- elif format.lower() not in allowed_extensions:
+ if format.lower() not in allowed_extensions:
raise ValidationError(
{
field_name: ValidationError(
diff --git a/saleor/graphql/csv/dataloaders.py b/saleor/graphql/csv/dataloaders.py
index 7fa0a1078b..d561b56781 100644
--- a/saleor/graphql/csv/dataloaders.py
+++ b/saleor/graphql/csv/dataloaders.py
@@ -4,7 +4,7 @@ from ...csv.models import ExportEvent
from ..core.dataloaders import DataLoader
-class EventsByExportFileIdLoader(DataLoader):
+class EventsByExportFileIdLoader(DataLoader[int, list[ExportEvent]]):
context_key = "events_by_export_file_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/csv/mutations/base_export.py b/saleor/graphql/csv/mutations/base_export.py
index 86675efb75..ea32fb703d 100644
--- a/saleor/graphql/csv/mutations/base_export.py
+++ b/saleor/graphql/csv/mutations/base_export.py
@@ -26,7 +26,7 @@ class BaseExportMutation(BaseMutation):
scope = input["scope"]
if scope == ExportScope.IDS.value: # type: ignore[attr-defined] # mypy does not understand graphene enums # noqa: E501
return cls.clean_ids(input, only_type)
- elif scope == ExportScope.FILTER.value: # type: ignore[attr-defined] # mypy does not understand graphene enums # noqa: E501
+ if scope == ExportScope.FILTER.value: # type: ignore[attr-defined] # mypy does not understand graphene enums # noqa: E501
return cls.clean_filter(input)
return {"all": ""}
diff --git a/saleor/graphql/csv/mutations/export_products.py b/saleor/graphql/csv/mutations/export_products.py
index 1e8e0b00e2..7bb4350550 100644
--- a/saleor/graphql/csv/mutations/export_products.py
+++ b/saleor/graphql/csv/mutations/export_products.py
@@ -127,6 +127,6 @@ class ExportProducts(BaseExportMutation):
def get_items_pks(cls, field, export_info_input, graphene_type):
ids = export_info_input.get(field)
if not ids:
- return
+ return []
pks = cls.get_global_ids_or_error(ids, only_type=graphene_type, field=field)
return pks
diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.py
index 4c3aa0d0ba..e103b07bf3 100644
--- a/saleor/graphql/discount/dataloaders.py
+++ b/saleor/graphql/discount/dataloaders.py
@@ -1,5 +1,6 @@
from collections import defaultdict
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
+from uuid import UUID
from django.db.models import Exists, F, OuterRef, Sum
from django.db.models.functions import Coalesce
@@ -22,8 +23,11 @@ from ...product.models import ProductVariant
from ..channel.dataloaders import ChannelBySlugLoader
from ..core.dataloaders import DataLoader
+if TYPE_CHECKING:
+ from .types.sales import SaleChannelListing
-class VoucherByIdLoader(DataLoader):
+
+class VoucherByIdLoader(DataLoader[int, Voucher]):
context_key = "voucher_by_id"
def batch_load(self, keys):
@@ -31,7 +35,7 @@ class VoucherByIdLoader(DataLoader):
return [vouchers.get(voucher_id) for voucher_id in keys]
-class VoucherCodeByCodeLoader(DataLoader):
+class VoucherCodeByCodeLoader(DataLoader[str, VoucherCode]):
context_key = "voucher_code_by_code"
def batch_load(self, keys):
@@ -46,7 +50,7 @@ class VoucherCodeByCodeLoader(DataLoader):
return [voucher_map.get(code) for code in keys]
-class CodeByVoucherIDLoader(DataLoader):
+class CodeByVoucherIDLoader(DataLoader[int, VoucherCode]):
"""Fetch voucher code.
This dataloader will be deprecated together with `code` field.
@@ -64,7 +68,7 @@ class CodeByVoucherIDLoader(DataLoader):
return [voucher_codes_map.get(voucher_id) for voucher_id in keys]
-class UsedByVoucherIDLoader(DataLoader):
+class UsedByVoucherIDLoader(DataLoader[int, int]):
"""Fetch voucher used.
This dataloader will be deprecated together with `used` field.
@@ -78,13 +82,13 @@ class UsedByVoucherIDLoader(DataLoader):
.filter(id__in=keys)
.annotate(max_used=Coalesce(Sum("codes__used"), 0))
)
- vouchers_map = {}
+ vouchers_map: dict[int, int] = {}
for voucher in vouchers:
vouchers_map[voucher.id] = voucher.max_used # type: ignore
return [vouchers_map.get(voucher_id) for voucher_id in keys]
-class VoucherByCodeLoader(DataLoader):
+class VoucherByCodeLoader(DataLoader[str, Voucher]):
context_key = "voucher_by_code"
def batch_load(self, codes):
@@ -109,7 +113,9 @@ class VoucherByCodeLoader(DataLoader):
)
-class VoucherChannelListingByVoucherIdAndChanneSlugLoader(DataLoader):
+class VoucherChannelListingByVoucherIdAndChannelSlugLoader(
+ DataLoader[tuple[int, str], VoucherChannelListing]
+):
context_key = "voucherchannelisting_by_voucher_and_channel"
def batch_load(self, keys):
@@ -135,7 +141,9 @@ class VoucherChannelListingByVoucherIdAndChanneSlugLoader(DataLoader):
]
-class VoucherChannelListingByVoucherIdLoader(DataLoader):
+class VoucherChannelListingsByVoucherIdLoader(
+ DataLoader[int, list[VoucherChannelListing]]
+):
context_key = "voucherchannellisting_by_voucher"
def batch_load(self, keys):
@@ -220,7 +228,7 @@ class VoucherInfoByVoucherCodeLoader(DataLoader[str, Optional[VoucherInfo]]):
return voucher_infos
-class OrderDiscountsByOrderIDLoader(DataLoader):
+class OrderDiscountsByOrderIDLoader(DataLoader[UUID, list[OrderDiscount]]):
context_key = "orderdiscounts_by_order_id"
def batch_load(self, keys):
@@ -233,7 +241,9 @@ class OrderDiscountsByOrderIDLoader(DataLoader):
return [discount_map.get(order_id, []) for order_id in keys]
-class CheckoutLineDiscountsByCheckoutLineIdLoader(DataLoader):
+class CheckoutLineDiscountsByCheckoutLineIdLoader(
+ DataLoader[UUID, list[CheckoutLineDiscount]]
+):
context_key = "checkout_line_discounts_by_checkout_line_id"
def batch_load(self, keys):
@@ -246,7 +256,7 @@ class CheckoutLineDiscountsByCheckoutLineIdLoader(DataLoader):
return [discount_map.get(checkout_line_id, []) for checkout_line_id in keys]
-class CheckoutDiscountByCheckoutIdLoader(DataLoader):
+class CheckoutDiscountByCheckoutIdLoader(DataLoader[UUID, list[CheckoutDiscount]]):
context_key = "checkout_discount_by_checkout_id"
def batch_load(self, keys):
@@ -261,7 +271,7 @@ class CheckoutDiscountByCheckoutIdLoader(DataLoader):
]
-class PromotionRulesByPromotionIdLoader(DataLoader):
+class PromotionRulesByPromotionIdLoader(DataLoader[int, list[PromotionRule]]):
context_key = "promotion_rules_by_promotion_id"
def batch_load(self, keys):
@@ -277,7 +287,7 @@ class PromotionRulesByPromotionIdLoader(DataLoader):
return [rules_map.get(promotion_id, []) for promotion_id in keys]
-class PromotionEventsByPromotionIdLoader(DataLoader):
+class PromotionEventsByPromotionIdLoader(DataLoader[int, list[PromotionEvent]]):
context_key = "promotion_events_by_promotion_id"
def batch_load(self, keys):
@@ -293,7 +303,7 @@ class PromotionEventsByPromotionIdLoader(DataLoader):
return [events_map.get(promotion_id, []) for promotion_id in keys]
-class PromotionByIdLoader(DataLoader):
+class PromotionByIdLoader(DataLoader[int, Promotion]):
context_key = "promotion_by_id"
def batch_load(self, keys):
@@ -303,7 +313,7 @@ class PromotionByIdLoader(DataLoader):
return [promotions.get(id) for id in keys]
-class ChannelsByPromotionRuleIdLoader(DataLoader):
+class ChannelsByPromotionRuleIdLoader(DataLoader[int, list[Channel]]):
context_key = "channels_by_promotion_rule_id"
def batch_load(self, keys):
@@ -324,7 +334,7 @@ class ChannelsByPromotionRuleIdLoader(DataLoader):
return [rule_to_channels_map.get(rule_id, []) for rule_id in keys]
-class PromotionRuleByIdLoader(DataLoader):
+class PromotionRuleByIdLoader(DataLoader[int, PromotionRule]):
context_key = "promotion_rule_by_id"
def batch_load(self, keys):
@@ -332,7 +342,7 @@ class PromotionRuleByIdLoader(DataLoader):
return [rules.get(id) for id in keys]
-class PromotionByRuleIdLoader(DataLoader):
+class PromotionByRuleIdLoader(DataLoader[int, Promotion]):
context_key = "promotion_by_rule_id"
def batch_load(self, keys):
@@ -348,7 +358,9 @@ class PromotionByRuleIdLoader(DataLoader):
return [promotion_map.get(rule_id) for rule_id in keys]
-class SaleChannelListingByPromotionIdLoader(DataLoader):
+class SaleChannelListingByPromotionIdLoader(
+ DataLoader[int, list["SaleChannelListing"]]
+):
context_key = "sale_channel_listing_by_promotion_id"
def batch_load(self, keys):
@@ -387,7 +399,9 @@ class SaleChannelListingByPromotionIdLoader(DataLoader):
)
-class PromotionRulesByPromotionIdAndChannelSlugLoader(DataLoader):
+class PromotionRulesByPromotionIdAndChannelSlugLoader(
+ DataLoader[tuple[int, str], list[PromotionRule]]
+):
context_key = "promotion_rules_by_promotion_id_and_channel_slug"
def batch_load(self, keys):
@@ -419,7 +433,7 @@ class PromotionRulesByPromotionIdAndChannelSlugLoader(DataLoader):
return Promise.all([channel, promotion_ids]).then(with_channel)
-class PredicateByPromotionIdLoader(DataLoader):
+class PredicateByPromotionIdLoader(DataLoader[int, dict]):
context_key = "predicate_by_promotion_id_and_channel_slug"
def batch_load(self, keys):
@@ -453,7 +467,7 @@ class PredicateByPromotionIdLoader(DataLoader):
)
-class GiftsByPromotionRuleIDLoader(DataLoader):
+class GiftsByPromotionRuleIDLoader(DataLoader[int, list[ProductVariant]]):
context_key = "gifts_by_promotion_rule"
def batch_load(self, keys):
diff --git a/saleor/graphql/discount/mutations/promotion/validators.py b/saleor/graphql/discount/mutations/promotion/validators.py
index 4ec7d08ed9..8bc304e1c1 100644
--- a/saleor/graphql/discount/mutations/promotion/validators.py
+++ b/saleor/graphql/discount/mutations/promotion/validators.py
@@ -60,23 +60,22 @@ def clean_promotion_rule(
return cleaned_input
-def _get_gift_ids(cleaned_input, instance):
+def _get_gift_ids(cleaned_input, instance) -> set[int]:
"""Return the set of gift ids for promotion rule valid after performing mutation."""
if not instance and not any(
field in cleaned_input for field in ["gifts", "add_gifts", "remove_gifts"]
):
- return
+ return set()
if "gifts" in cleaned_input:
gifts = cleaned_input["gifts"] or []
return {gift.id for gift in gifts}
- else:
- # this part is only for PromotionRuleUpdate mutation
- # so the gifts will be fetched once
- current_gift_ids = {gift.id for gift in instance.gifts.all()}
- add_gift_ids = {gift.id for gift in cleaned_input.get("add_gifts", [])}
- remove_gift_ids = {gift.id for gift in cleaned_input.get("remove_gifts", [])}
- return (current_gift_ids | add_gift_ids) - remove_gift_ids
+ # this part is only for PromotionRuleUpdate mutation
+ # so the gifts will be fetched once
+ current_gift_ids = {gift.id for gift in instance.gifts.all()}
+ add_gift_ids = {gift.id for gift in cleaned_input.get("add_gifts", [])}
+ remove_gift_ids = {gift.id for gift in cleaned_input.get("remove_gifts", [])}
+ return (current_gift_ids | add_gift_ids) - remove_gift_ids
def _clean_gifts(gift_ids, errors, error_class, index):
@@ -565,3 +564,4 @@ def get_from_input_or_instance(field: str, input: dict, instance: PromotionRule)
return input[field]
if instance:
return getattr(instance, field)
+ return None
diff --git a/saleor/graphql/discount/mutations/voucher/voucher_update.py b/saleor/graphql/discount/mutations/voucher/voucher_update.py
index bdeb1aeb2d..82a2a6e125 100644
--- a/saleor/graphql/discount/mutations/voucher/voucher_update.py
+++ b/saleor/graphql/discount/mutations/voucher/voucher_update.py
@@ -126,15 +126,14 @@ class VoucherUpdate(VoucherCreate):
code_instance = voucher_instance.codes.first()
code_instance.code = code
return [code_instance]
- else:
- raise ValidationError(
- {
- "code": ValidationError(
- "Cannot update code when multiple codes exists.",
- code=DiscountErrorCode.INVALID.value,
- )
- }
- )
+ raise ValidationError(
+ {
+ "code": ValidationError(
+ "Cannot update code when multiple codes exists.",
+ code=DiscountErrorCode.INVALID.value,
+ )
+ }
+ )
return []
diff --git a/saleor/graphql/discount/types/sales.py b/saleor/graphql/discount/types/sales.py
index 77be5b8dde..9656dc30e9 100644
--- a/saleor/graphql/discount/types/sales.py
+++ b/saleor/graphql/discount/types/sales.py
@@ -162,6 +162,7 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):
return create_connection_slice(
qs, info, kwargs, CategoryCountableConnection
)
+ return None
return (
PredicateByPromotionIdLoader(info.context)
@@ -188,6 +189,7 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):
return create_connection_slice(
qs, info, kwargs, CollectionCountableConnection
)
+ return None
return (
PredicateByPromotionIdLoader(info.context)
@@ -208,6 +210,7 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):
return create_connection_slice(
qs, info, kwargs, ProductCountableConnection
)
+ return None
return (
PredicateByPromotionIdLoader(info.context)
@@ -228,6 +231,7 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):
return create_connection_slice(
qs, info, kwargs, ProductVariantCountableConnection
)
+ return None
return (
PredicateByPromotionIdLoader(info.context)
@@ -245,6 +249,7 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):
def _get_reward_value(rules):
if rules:
return rules[0].reward_value
+ return None
return (
PromotionRulesByPromotionIdAndChannelSlugLoader(info.context)
@@ -260,6 +265,7 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):
def _get_currency(channel):
if channel:
return channel.currency_code
+ return None
return (
ChannelBySlugLoader(info.context)
diff --git a/saleor/graphql/discount/types/vouchers.py b/saleor/graphql/discount/types/vouchers.py
index 58c7000e2d..e42c686376 100644
--- a/saleor/graphql/discount/types/vouchers.py
+++ b/saleor/graphql/discount/types/vouchers.py
@@ -35,8 +35,8 @@ from ...translations.types import VoucherTranslation
from ..dataloaders import (
CodeByVoucherIDLoader,
UsedByVoucherIDLoader,
- VoucherChannelListingByVoucherIdAndChanneSlugLoader,
- VoucherChannelListingByVoucherIdLoader,
+ VoucherChannelListingByVoucherIdAndChannelSlugLoader,
+ VoucherChannelListingsByVoucherIdLoader,
)
from ..enums import DiscountValueTypeEnum, VoucherTypeEnum
@@ -261,7 +261,7 @@ class Voucher(ChannelContextTypeWithMetadata[models.Voucher]):
return None
return (
- VoucherChannelListingByVoucherIdAndChanneSlugLoader(info.context)
+ VoucherChannelListingByVoucherIdAndChannelSlugLoader(info.context)
.load((root.node.id, root.channel_slug))
.then(
lambda channel_listing: channel_listing.discount_value
@@ -276,7 +276,7 @@ class Voucher(ChannelContextTypeWithMetadata[models.Voucher]):
return None
return (
- VoucherChannelListingByVoucherIdAndChanneSlugLoader(info.context)
+ VoucherChannelListingByVoucherIdAndChannelSlugLoader(info.context)
.load((root.node.id, root.channel_slug))
.then(
lambda channel_listing: channel_listing.currency
@@ -291,7 +291,7 @@ class Voucher(ChannelContextTypeWithMetadata[models.Voucher]):
return None
return (
- VoucherChannelListingByVoucherIdAndChanneSlugLoader(info.context)
+ VoucherChannelListingByVoucherIdAndChannelSlugLoader(info.context)
.load((root.node.id, root.channel_slug))
.then(
lambda channel_listing: channel_listing.min_spent
@@ -304,7 +304,7 @@ class Voucher(ChannelContextTypeWithMetadata[models.Voucher]):
def resolve_channel_listings(
root: ChannelContext[models.Voucher], info: ResolveInfo
):
- return VoucherChannelListingByVoucherIdLoader(info.context).load(root.node.id)
+ return VoucherChannelListingsByVoucherIdLoader(info.context).load(root.node.id)
class VoucherCountableConnection(CountableConnection):
diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.py
index 2ec3eb1b8f..d0b5f58c8d 100644
--- a/saleor/graphql/discount/utils.py
+++ b/saleor/graphql/discount/utils.py
@@ -284,14 +284,15 @@ def _handle_predicate(
):
if predicate_type == PredicateObjectType.CATALOGUE:
return _handle_catalogue_predicate(result_qs, base_qs, predicate_data, operator)
- elif predicate_type == PredicateObjectType.CHECKOUT:
+ if predicate_type == PredicateObjectType.CHECKOUT:
return _handle_checkout_predicate(
result_qs, base_qs, predicate_data, operator, currency
)
- elif predicate_type == PredicateObjectType.ORDER:
+ if predicate_type == PredicateObjectType.ORDER:
return _handle_order_predicate(
result_qs, base_qs, predicate_data, operator, currency
)
+ return None
def _handle_catalogue_predicate(
diff --git a/saleor/graphql/giftcard/dataloaders.py b/saleor/graphql/giftcard/dataloaders.py
index a5f70be6ba..3ecda73da8 100644
--- a/saleor/graphql/giftcard/dataloaders.py
+++ b/saleor/graphql/giftcard/dataloaders.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from uuid import UUID
from ...checkout.models import Checkout
from ...giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
@@ -6,7 +7,7 @@ from ...order.models import Order
from ..core.dataloaders import DataLoader
-class GiftCardsByUserLoader(DataLoader):
+class GiftCardsByUserLoader(DataLoader[int, list[GiftCard]]):
context_key = "gift_cards_by_user"
def batch_load(self, keys):
@@ -19,7 +20,7 @@ class GiftCardsByUserLoader(DataLoader):
return [gift_cards_by_user_map.get(user_id, []) for user_id in keys]
-class GiftCardEventsByGiftCardIdLoader(DataLoader):
+class GiftCardEventsByGiftCardIdLoader(DataLoader[int, list[GiftCardEvent]]):
context_key = "giftcardevents_by_giftcard"
def batch_load(self, keys):
@@ -32,7 +33,7 @@ class GiftCardEventsByGiftCardIdLoader(DataLoader):
return [events_map.get(gift_card_id, []) for gift_card_id in keys]
-class GiftCardTagsByGiftCardIdLoader(DataLoader):
+class GiftCardTagsByGiftCardIdLoader(DataLoader[int, list[GiftCardTag]]):
context_key = "giftcardtags_by_giftcard"
def batch_load(self, keys):
@@ -56,7 +57,7 @@ class GiftCardTagsByGiftCardIdLoader(DataLoader):
return [tags_map.get(gift_card_id, []) for gift_card_id in keys]
-class GiftCardsByOrderIdLoader(DataLoader):
+class GiftCardsByOrderIdLoader(DataLoader[UUID, list[GiftCard]]):
context_key = "gift_cards_by_order_id"
def batch_load(self, keys):
@@ -76,7 +77,7 @@ class GiftCardsByOrderIdLoader(DataLoader):
return [cards_map.get(order_id, []) for order_id in keys]
-class GiftCardsByCheckoutIdLoader(DataLoader):
+class GiftCardsByCheckoutIdLoader(DataLoader[UUID, list[GiftCard]]):
context_key = "gift_cards_by_checkout_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.py
index 680e6c2820..9a06604185 100644
--- a/saleor/graphql/giftcard/types.py
+++ b/saleor/graphql/giftcard/types.py
@@ -404,6 +404,7 @@ class GiftCard(ModelObjectType[models.GiftCard]):
requestor, user, AccountPermissions.MANAGE_USERS
):
return user
+ return None
if not root.used_by_id:
return _resolve_used_by(None)
@@ -548,6 +549,7 @@ class GiftCard(ModelObjectType[models.GiftCard]):
requestor, user, AccountPermissions.MANAGE_USERS
):
return user
+ return None
if not root.created_by_id:
return _resolve_user(None)
diff --git a/saleor/graphql/invoice/dataloaders.py b/saleor/graphql/invoice/dataloaders.py
index a0c957b5f6..91e9f4135c 100644
--- a/saleor/graphql/invoice/dataloaders.py
+++ b/saleor/graphql/invoice/dataloaders.py
@@ -4,7 +4,7 @@ from ...invoice.models import Invoice
from ..core.dataloaders import DataLoader
-class InvoicesByOrderIdLoader(DataLoader):
+class InvoicesByOrderIdLoader(DataLoader[int, list[Invoice]]):
context_key = "invoices_by_order_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/menu/dataloaders.py b/saleor/graphql/menu/dataloaders.py
index cf0285c0db..c7bd56b43d 100644
--- a/saleor/graphql/menu/dataloaders.py
+++ b/saleor/graphql/menu/dataloaders.py
@@ -4,7 +4,7 @@ from ...menu.models import Menu, MenuItem
from ..core.dataloaders import DataLoader
-class MenuByIdLoader(DataLoader):
+class MenuByIdLoader(DataLoader[int, Menu]):
context_key = "menu_by_id"
def batch_load(self, keys):
@@ -12,7 +12,7 @@ class MenuByIdLoader(DataLoader):
return [menus.get(menu_id) for menu_id in keys]
-class MenuItemByIdLoader(DataLoader):
+class MenuItemByIdLoader(DataLoader[int, MenuItem]):
context_key = "menuitem_by_id"
def batch_load(self, keys):
@@ -20,7 +20,7 @@ class MenuItemByIdLoader(DataLoader):
return [menu_items.get(menu_item_id) for menu_item_id in keys]
-class MenuItemsByParentMenuLoader(DataLoader):
+class MenuItemsByParentMenuLoader(DataLoader[int, list[MenuItem]]):
context_key = "menuitems_by_parent_menu"
def batch_load(self, keys):
@@ -33,7 +33,7 @@ class MenuItemsByParentMenuLoader(DataLoader):
return [items_map[menu_id] for menu_id in keys]
-class MenuItemChildrenLoader(DataLoader):
+class MenuItemChildrenLoader(DataLoader[int, list[MenuItem]]):
context_key = "menuitem_children"
def batch_load(self, keys):
diff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.py
index cb2e4bdee9..c67035c398 100644
--- a/saleor/graphql/meta/mutations/base.py
+++ b/saleor/graphql/meta/mutations/base.py
@@ -89,6 +89,7 @@ class BaseMetadataMutation(BaseMutation):
return None
if qs and "token" in [field.name for field in qs.model._meta.get_fields()]:
return qs.filter(token=object_id).first()
+ return None
@classmethod
def get_old_sale_instance(cls, global_id, old_sale_id):
@@ -96,14 +97,13 @@ class BaseMetadataMutation(BaseMutation):
old_sale_id=old_sale_id
).first():
return instance
- else:
- raise ValidationError(
- {
- "id": ValidationError(
- f"Couldn't resolve to a node: {global_id}", code="not_found"
- )
- }
- )
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ f"Couldn't resolve to a node: {global_id}", code="not_found"
+ )
+ }
+ )
@classmethod
def validate_model_is_model_with_metadata(cls, model, object_id):
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index 880a118fde..3c55c0f7f6 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -121,13 +121,13 @@ def public_address_permissions(
if address.user_addresses.filter(Exists(staff_users.filter(id=OuterRef("id")))):
return [AccountPermissions.MANAGE_STAFF]
- elif (
+ if (
warehouse_models.Warehouse.objects.using(database_connection_name)
.filter(address_id=address.id)
.exists()
):
return [ProductPermissions.MANAGE_PRODUCTS]
- elif (
+ if (
site_models.SiteSettings.objects.using(database_connection_name)
.filter(company_address_id=address.id)
.exists()
@@ -249,8 +249,7 @@ def attribute_permissions(info: ResolveInfo, attribute_pk: int):
)
if attribute.type == AttributeType.PAGE_TYPE:
return page_type_permissions(info, attribute_pk)
- else:
- return product_type_permissions(info, attribute_pk)
+ return product_type_permissions(info, attribute_pk)
def shipping_permissions(
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index 60b440108f..66f3f30bb8 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -90,7 +90,7 @@ def resolve_object_with_metadata_type(instance):
return discount_types.Sale, instance.pk
return MODEL_TO_TYPE_MAP.get(instance.__class__, None), instance.pk
- elif dataclasses.is_dataclass(instance):
+ if dataclasses.is_dataclass(instance):
DATACLASS_TO_TYPE_MAP = {ShippingMethodData: shipping_types.ShippingMethod}
return DATACLASS_TO_TYPE_MAP.get(instance.__class__, None), instance.id
raise ValueError(f"Unknown type: {instance.__class__}")
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 7222ce07ae..8aff0b6a19 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -1,6 +1,7 @@
from collections import defaultdict
from collections.abc import Iterable
from typing import cast
+from uuid import UUID
from django.db.models import F
@@ -45,7 +46,7 @@ class OrderLinesByVariantIdAndChannelIdLoader(
return [order_line_by_variant_and_channel_map[key] for key in keys]
-class OrderByIdLoader(DataLoader):
+class OrderByIdLoader(DataLoader[UUID, Order]):
context_key = "order_by_id"
def batch_load(self, keys):
@@ -53,7 +54,7 @@ class OrderByIdLoader(DataLoader):
return [orders.get(order_id) for order_id in keys]
-class OrderByNumberLoader(DataLoader):
+class OrderByNumberLoader(DataLoader[str, Order]):
context_key = "order_by_number"
def batch_load(self, keys):
@@ -65,7 +66,7 @@ class OrderByNumberLoader(DataLoader):
return [orders.get(number) for number in keys]
-class OrdersByUserLoader(DataLoader):
+class OrdersByUserLoader(DataLoader[int, list[Order]]):
context_key = "order_by_user"
def batch_load(self, keys):
@@ -78,7 +79,7 @@ class OrdersByUserLoader(DataLoader):
return [orders_by_user_map.get(user_id, []) for user_id in keys]
-class OrderLineByIdLoader(DataLoader):
+class OrderLineByIdLoader(DataLoader[UUID, OrderLine]):
context_key = "orderline_by_id"
def batch_load(self, keys):
@@ -88,7 +89,7 @@ class OrderLineByIdLoader(DataLoader):
return [order_lines.get(line_id) for line_id in keys]
-class OrderLinesByOrderIdLoader(DataLoader):
+class OrderLinesByOrderIdLoader(DataLoader[UUID, list[OrderLine]]):
context_key = "orderlines_by_order"
def batch_load(self, keys):
@@ -103,7 +104,7 @@ class OrderLinesByOrderIdLoader(DataLoader):
return [line_map.get(order_id, []) for order_id in keys]
-class OrderEventsByOrderIdLoader(DataLoader):
+class OrderEventsByOrderIdLoader(DataLoader[UUID, list[OrderEvent]]):
context_key = "orderevents_by_order"
def batch_load(self, keys):
@@ -118,7 +119,7 @@ class OrderEventsByOrderIdLoader(DataLoader):
return [events_map.get(order_id, []) for order_id in keys]
-class OrderEventsByIdLoader(DataLoader):
+class OrderEventsByIdLoader(DataLoader[int, OrderEvent]):
context_key = "orderevents_by_id"
def batch_load(self, keys):
@@ -130,7 +131,7 @@ class OrderEventsByIdLoader(DataLoader):
return [events.get(event_id) for event_id in keys]
-class OrderGrantedRefundsByOrderIdLoader(DataLoader):
+class OrderGrantedRefundsByOrderIdLoader(DataLoader[UUID, list[OrderGrantedRefund]]):
context_key = "order_granted_refunds_by_order_id"
def batch_load(self, keys):
@@ -144,7 +145,9 @@ class OrderGrantedRefundsByOrderIdLoader(DataLoader):
return [refunds_map.get(order_id, []) for order_id in keys]
-class OrderGrantedRefundLinesByOrderGrantedRefundIdLoader(DataLoader):
+class OrderGrantedRefundLinesByOrderGrantedRefundIdLoader(
+ DataLoader[int, list[OrderGrantedRefundLine]]
+):
context_key = "order_granted_refund_lines_by_granted_refund_id"
def batch_load(self, keys):
@@ -160,7 +163,7 @@ class OrderGrantedRefundLinesByOrderGrantedRefundIdLoader(DataLoader):
]
-class AllocationsByOrderLineIdLoader(DataLoader):
+class AllocationsByOrderLineIdLoader(DataLoader[UUID, list[Allocation]]):
context_key = "allocations_by_orderline_id"
def batch_load(self, keys):
@@ -175,7 +178,7 @@ class AllocationsByOrderLineIdLoader(DataLoader):
return [order_lines_to_allocations[order_line_id] for order_line_id in keys]
-class FulfillmentsByOrderIdLoader(DataLoader):
+class FulfillmentsByOrderIdLoader(DataLoader[UUID, list[Fulfillment]]):
context_key = "fulfillments_by_order"
def batch_load(self, keys):
@@ -190,7 +193,7 @@ class FulfillmentsByOrderIdLoader(DataLoader):
return [fulfillments_map.get(order_id, []) for order_id in keys]
-class FulfillmentLinesByIdLoader(DataLoader):
+class FulfillmentLinesByIdLoader(DataLoader[int, FulfillmentLine]):
context_key = "fulfillment_lines_by_id"
def batch_load(self, keys):
@@ -200,7 +203,7 @@ class FulfillmentLinesByIdLoader(DataLoader):
return [fulfillment_lines.get(line_id) for line_id in keys]
-class FulfillmentLinesByFulfillmentIdLoader(DataLoader):
+class FulfillmentLinesByFulfillmentIdLoader(DataLoader[int, list[FulfillmentLine]]):
context_key = "fulfillment_lines_by_fulfillment_id"
def batch_load(self, keys):
@@ -221,7 +224,7 @@ class FulfillmentLinesByFulfillmentIdLoader(DataLoader):
]
-class TransactionItemsByOrderIDLoader(DataLoader):
+class TransactionItemsByOrderIDLoader(DataLoader[UUID, list[TransactionItem]]):
context_key = "transaction_items_by_order_id"
def batch_load(self, keys):
@@ -236,7 +239,9 @@ class TransactionItemsByOrderIDLoader(DataLoader):
return [transactions_map.get(order_id, []) for order_id in keys]
-class TransactionEventsByOrderGrantedRefundIdLoader(DataLoader):
+class TransactionEventsByOrderGrantedRefundIdLoader(
+ DataLoader[int, list[TransactionEvent]]
+):
context_key = "transaction_event_by_order_granted_refund_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 0b04b618eb..728fe17d54 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -247,13 +247,10 @@ class DraftOrderCreate(
)
}
)
- else:
- channel = cls.get_node_or_error(info, channel_id, only_type=Channel)
- cleaned_input["channel"] = channel
- return channel
-
- else:
- return instance.channel if hasattr(instance, "channel") else None
+ channel = cls.get_node_or_error(info, channel_id, only_type=Channel)
+ cleaned_input["channel"] = channel
+ return channel
+ return instance.channel if hasattr(instance, "channel") else None
@classmethod
def clean_voucher_and_voucher_code(cls, voucher, voucher_code):
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index b3e255ff00..d656e807c3 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -5,7 +5,7 @@ from django.core.exceptions import ValidationError
from ....core.taxes import TaxError
from ....core.tracing import traced_atomic_transaction
-from ....order import events
+from ....order import events, models
from ....order.error_codes import OrderErrorCode
from ....order.fetch import fetch_order_lines
from ....order.search import update_order_search_vector
@@ -133,7 +133,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
@staticmethod
def add_lines_to_order(order, lines_data, user, app, manager):
- added_lines: list[OrderLine] = []
+ added_lines: list[models.OrderLine] = []
try:
for line_data in lines_data:
line = add_variant_to_order(
@@ -207,10 +207,10 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
return OrderLinesCreate(order=order, order_lines=added_lines)
@classmethod
- def _find_line_id_for_variant_if_exist(cls, variant_id, lines_info):
+ def _find_line_id_for_variant_if_exist(cls, variant_id, lines_info) -> None | str:
"""Return line id by using provided variantId parameter."""
if not lines_info:
- return
+ return None
line_info = list(
filter(
@@ -219,6 +219,6 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
)
if not line_info or len(line_info) > 1:
- return
+ return None
return str(line_info[0].line.id)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index eac31c5106..f182319c5e 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -44,7 +44,7 @@ from ...permission.enums import (
ProductPermissions,
)
from ...permission.utils import has_one_of_permissions
-from ...product.models import ALL_PRODUCTS_PERMISSIONS, ProductMediaTypes
+from ...product.models import ALL_PRODUCTS_PERMISSIONS, ProductMedia, ProductMediaTypes
from ...shipping.interface import ShippingMethodData
from ...shipping.utils import convert_to_shipping_method_data
from ...tax.utils import get_display_gross_prices
@@ -732,6 +732,7 @@ class Fulfillment(ModelObjectType[models.Fulfillment]):
.load(stock_id)
.then(_resolve_stock_warehouse)
)
+ return None
return (
FulfillmentLinesByFulfillmentIdLoader(info.context)
@@ -930,16 +931,17 @@ class OrderLine(ModelObjectType[models.OrderLine]):
.then(_resolve_url)
)
- def _get_first_variant_image(all_medias):
- if image := next(
+ def _get_first_variant_image(
+ all_medias: list[ProductMedia],
+ ) -> ProductMedia | None:
+ return next(
(
media
for media in all_medias
if media.type == ProductMediaTypes.IMAGE
),
None,
- ):
- return image
+ )
def _get_first_product_image(images):
return _get_image_from_media(images[0]) if images else None
@@ -1647,7 +1649,7 @@ class Order(ModelObjectType[models.Order]):
return obfuscate_address(address)
if not root.billing_address_id:
- return
+ return None
if root.user_id:
user = UserByUserIdLoader(info.context).load(root.user_id)
@@ -1676,7 +1678,7 @@ class Order(ModelObjectType[models.Order]):
return obfuscate_address(address)
if not root.shipping_address_id:
- return
+ return None
if root.user_id:
user = UserByUserIdLoader(info.context).load(root.user_id)
@@ -1851,20 +1853,18 @@ class Order(ModelObjectType[models.Order]):
granted_refunds, transactions, payments = data
if any(p.is_active for p in payments):
return root.total_balance
- else:
- total_granted_refund = sum(
- [granted_refund.amount for granted_refund in granted_refunds],
- zero_money(root.currency),
- )
- total_charged = prices.Money(Decimal(0), root.currency)
- for transaction in transactions:
- total_charged += transaction.amount_charged
- total_charged += transaction.amount_charge_pending
- order_granted_refunds_difference = (
- root.total.gross - total_granted_refund
- )
- return total_charged - order_granted_refunds_difference
+ total_granted_refund = sum(
+ [granted_refund.amount for granted_refund in granted_refunds],
+ zero_money(root.currency),
+ )
+ total_charged = prices.Money(Decimal(0), root.currency)
+
+ for transaction in transactions:
+ total_charged += transaction.amount_charged
+ total_charged += transaction.amount_charge_pending
+ order_granted_refunds_difference = root.total.gross - total_granted_refund
+ return total_charged - order_granted_refunds_difference
granted_refunds = OrderGrantedRefundsByOrderIdLoader(info.context).load(root.id)
transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 1cf6a68665..dbfbe298a2 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -80,6 +80,7 @@ def get_shipping_method_availability_error(
"Shipping method cannot be used with this order.",
code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
)
+ return None
def validate_shipping_method(
diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.py
index 930e013241..74eee1d7d6 100644
--- a/saleor/graphql/page/dataloaders.py
+++ b/saleor/graphql/page/dataloaders.py
@@ -9,7 +9,7 @@ from ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdL
from ..core.dataloaders import DataLoader
-class PageByIdLoader(DataLoader):
+class PageByIdLoader(DataLoader[int, Page]):
context_key = "page_by_id"
def batch_load(self, keys):
@@ -17,7 +17,7 @@ class PageByIdLoader(DataLoader):
return [pages.get(page_id) for page_id in keys]
-class PageTypeByIdLoader(DataLoader):
+class PageTypeByIdLoader(DataLoader[int, PageType]):
context_key = "page_type_by_id"
def batch_load(self, keys):
@@ -25,7 +25,7 @@ class PageTypeByIdLoader(DataLoader):
return [page_types.get(page_type_id) for page_type_id in keys]
-class PagesByPageTypeIdLoader(DataLoader):
+class PagesByPageTypeIdLoader(DataLoader[int, list[Page]]):
"""Loads pages by pages type ID."""
context_key = "pages_by_pagetype"
@@ -42,7 +42,7 @@ class PagesByPageTypeIdLoader(DataLoader):
return [pagetype_to_pages[key] for key in keys]
-class BasePageAttributesByPageTypeIdLoader(DataLoader):
+class BasePageAttributesByPageTypeIdLoader(DataLoader[int, list[Attribute]]):
"""Loads page attributes by page type ID."""
context_key = "page_attributes_by_pagetype"
@@ -103,7 +103,7 @@ class PageAttributesVisibleInStorefrontByPageTypeIdLoader(
)
-class BaseAttributeValuesByPageIdLoader(DataLoader):
+class BaseAttributeValuesByPageIdLoader(DataLoader[int, list[dict]]):
def get_page_attributes_dataloader(self):
raise NotImplementedError()
@@ -174,14 +174,14 @@ class AttributeValuesVisibleInStorefrontByPageIdLoader(
return PageAttributesVisibleInStorefrontByPageTypeIdLoader(self.context)
-class SelectedAttributesAllByPageIdLoader(DataLoader):
+class SelectedAttributesAllByPageIdLoader(DataLoader[int, list[dict]]):
context_key = "selectedattributes_all_by_page"
def batch_load(self, page_ids):
return AttributeValuesAllByPageIdLoader(self.context).load_many(page_ids)
-class SelectedAttributesVisibleInStorefrontPageIdLoader(DataLoader):
+class SelectedAttributesVisibleInStorefrontPageIdLoader(DataLoader[int, list[dict]]):
context_key = "selectedattributes_visible_in_storefront_by_page"
def batch_load(self, page_ids):
diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.py
index 605a7482ca..5d7e4777b3 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -80,10 +80,9 @@ class PageType(ModelObjectType[models.PageType]):
and requestor.has_perm(PagePermissions.MANAGE_PAGES)
):
return PageAttributesAllByPageTypeIdLoader(info.context).load(root.pk)
- else:
- return PageAttributesVisibleInStorefrontByPageTypeIdLoader(
- info.context
- ).load(root.pk)
+ return PageAttributesVisibleInStorefrontByPageTypeIdLoader(info.context).load(
+ root.pk
+ )
@staticmethod
def resolve_available_attributes(
@@ -188,10 +187,9 @@ class Page(ModelObjectType[models.Page]):
and requestor.has_perm(PagePermissions.MANAGE_PAGES)
):
return SelectedAttributesAllByPageIdLoader(info.context).load(root.id)
- else:
- return SelectedAttributesVisibleInStorefrontPageIdLoader(info.context).load(
- root.id
- )
+ return SelectedAttributesVisibleInStorefrontPageIdLoader(info.context).load(
+ root.id
+ )
class PageCountableConnection(CountableConnection):
diff --git a/saleor/graphql/payment/dataloaders.py b/saleor/graphql/payment/dataloaders.py
index f1bf8d5a8a..7d04b81d4b 100644
--- a/saleor/graphql/payment/dataloaders.py
+++ b/saleor/graphql/payment/dataloaders.py
@@ -4,7 +4,7 @@ from ...payment.models import Transaction, TransactionEvent, TransactionItem
from ..core.dataloaders import DataLoader
-class TransactionEventByTransactionIdLoader(DataLoader):
+class TransactionEventByTransactionIdLoader(DataLoader[int, list[TransactionEvent]]):
context_key = "transaction_event_by_transaction_id"
def batch_load(self, keys):
@@ -19,7 +19,7 @@ class TransactionEventByTransactionIdLoader(DataLoader):
return [event_map.get(transaction_id, []) for transaction_id in keys]
-class TransactionItemByIDLoader(DataLoader):
+class TransactionItemByIDLoader(DataLoader[int, TransactionItem]):
context_key = "transaction_items_by_id"
def batch_load(self, keys):
@@ -29,7 +29,7 @@ class TransactionItemByIDLoader(DataLoader):
return [transactions.get(transaction_id) for transaction_id in keys]
-class TransactionByPaymentIdLoader(DataLoader):
+class TransactionByPaymentIdLoader(DataLoader[int, list[Transaction]]):
context_key = "transaction_by_payment_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/payment/enums.py b/saleor/graphql/payment/enums.py
index 4bb5fe66fe..f151dff959 100644
--- a/saleor/graphql/payment/enums.py
+++ b/saleor/graphql/payment/enums.py
@@ -61,15 +61,15 @@ class OrderAction(BaseEnum):
def description(enum):
if enum is None:
return "Enum representing the type of a payment storage in a gateway."
- elif enum == StorePaymentMethodEnum.NONE:
+ if enum == StorePaymentMethodEnum.NONE:
return "Storage is disabled. The payment is not stored."
- elif enum == StorePaymentMethodEnum.ON_SESSION:
+ if enum == StorePaymentMethodEnum.ON_SESSION:
return (
"On session storage type. "
"The payment is stored only to be reused when "
"the customer is present in the checkout flow."
)
- elif enum == StorePaymentMethodEnum.OFF_SESSION:
+ if enum == StorePaymentMethodEnum.OFF_SESSION:
return (
"Off session storage type. "
"The payment is stored to be reused even if the customer is absent."
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_process.py b/saleor/graphql/payment/mutations/transaction/transaction_process.py
index 1c84086c94..1856d61f0e 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_process.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_process.py
@@ -85,9 +85,8 @@ class TransactionProcess(BaseMutation):
def get_action(cls, event: payment_models.TransactionEvent, channel: "Channel"):
if event.type == TransactionEventType.AUTHORIZATION_REQUEST:
return TransactionFlowStrategy.AUTHORIZATION
- elif event.type == TransactionEventType.CHARGE_REQUEST:
+ if event.type == TransactionEventType.CHARGE_REQUEST:
return TransactionFlowStrategy.CHARGE
-
return channel.default_transaction_flow_strategy
@classmethod
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 64d82655bc..87e7049ebb 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -274,6 +274,7 @@ class Payment(ModelObjectType[models.Payment]):
raise PermissionDenied(permissions=permissions)
return resolve_metadata(root.metadata)
+ @staticmethod
def resolve_checkout(root: models.Payment, info):
if not root.checkout_id:
return None
@@ -382,6 +383,7 @@ class TransactionEvent(ModelObjectType[models.TransactionEvent]):
.load(root.app_identifier)
.then(get_first_app_by_identifier)
)
+ return None
if root.app_id:
return AppByIdLoader(info.context).load(root.app_id).then(get_active_app)
@@ -533,13 +535,13 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
@staticmethod
def resolve_order(root: models.TransactionItem, info):
if not root.order_id:
- return
+ return None
return OrderByIdLoader(info.context).load(root.order_id)
@staticmethod
def resolve_checkout(root: models.TransactionItem, info):
if not root.checkout_id:
- return
+ return None
return CheckoutByTokenLoader(info.context).load(root.checkout_id)
@staticmethod
@@ -572,6 +574,7 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
.load(root.app_identifier)
.then(get_first_app_by_identifier)
)
+ return None
if root.app_id:
return AppByIdLoader(info.context).load(root.app_id).then(get_active_app)
diff --git a/saleor/graphql/plugins/dataloaders.py b/saleor/graphql/plugins/dataloaders.py
index ddc6b28202..02dadf8eae 100644
--- a/saleor/graphql/plugins/dataloaders.py
+++ b/saleor/graphql/plugins/dataloaders.py
@@ -3,6 +3,7 @@ from functools import partial, wraps
from promise import Promise
+from ...core.middleware import Requestor
from ...plugins.manager import PluginsManager, get_plugins_manager
from ...plugins.models import EmailTemplate
from ..app.dataloaders import get_app_promise
@@ -10,7 +11,7 @@ from ..core import SaleorContext
from ..core.dataloaders import DataLoader
-class EmailTemplatesByPluginConfigurationLoader(DataLoader):
+class EmailTemplatesByPluginConfigurationLoader(DataLoader[int, list[EmailTemplate]]):
"""Loads email templates by plugin configuration ID."""
context_key = "email_template_by_plugin_configuration"
@@ -27,7 +28,7 @@ class EmailTemplatesByPluginConfigurationLoader(DataLoader):
return [config_to_template[key] for key in keys]
-class PluginManagerByRequestorDataloader(DataLoader):
+class PluginManagerByRequestorDataloader(DataLoader[Requestor, PluginsManager]):
context_key = "plugin_manager_by_requestor"
def batch_load(self, keys):
@@ -35,7 +36,7 @@ class PluginManagerByRequestorDataloader(DataLoader):
return [get_plugins_manager(allow_replica, lambda: user) for user in keys]
-class AnonymousPluginManagerLoader(DataLoader):
+class AnonymousPluginManagerLoader(DataLoader[None, PluginsManager]):
context_key = "anonymous_plugin_manager"
def batch_load(self, keys):
diff --git a/saleor/graphql/plugins/mutations.py b/saleor/graphql/plugins/mutations.py
index d450e2d0d3..40f141d300 100644
--- a/saleor/graphql/plugins/mutations.py
+++ b/saleor/graphql/plugins/mutations.py
@@ -82,7 +82,7 @@ class PluginUpdate(BaseMutation):
)
}
)
- elif plugin not in manager.global_plugins and not channel_id:
+ if plugin not in manager.global_plugins and not channel_id:
raise ValidationError(
{
"id": ValidationError(
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 88199c8139..a11409aa04 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -495,8 +495,7 @@ def filter_has_preordered_variants(qs, _, value):
)
if value:
return qs.filter(Exists(variants.filter(product_id=OuterRef("pk"))))
- else:
- return qs.filter(~Exists(variants.filter(product_id=OuterRef("pk"))))
+ return qs.filter(~Exists(variants.filter(product_id=OuterRef("pk"))))
def filter_collections(qs, _, value):
@@ -1066,8 +1065,7 @@ def where_filter_has_preordered_variants(qs, _, value):
)
if value:
return qs.filter(Exists(variants.filter(product_id=OuterRef("pk"))))
- else:
- return qs.filter(~Exists(variants.filter(product_id=OuterRef("pk"))))
+ return qs.filter(~Exists(variants.filter(product_id=OuterRef("pk"))))
def where_filter_updated_at_range(qs, _, value):
@@ -1335,7 +1333,7 @@ class CollectionFilter(MetadataFilterBase):
channel_slug = get_channel_slug_from_filter_data(self.data)
if value == CollectionPublished.PUBLISHED:
return _filter_collections_is_published(queryset, name, True, channel_slug)
- elif value == CollectionPublished.HIDDEN:
+ if value == CollectionPublished.HIDDEN:
return _filter_collections_is_published(queryset, name, False, channel_slug)
return queryset
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index ba0031c486..2f484a020a 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -261,7 +261,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
)
if is_available_for_purchase is False:
return None
- elif is_available_for_purchase is True and not available_for_purchase_date:
+ if is_available_for_purchase is True and not available_for_purchase_date:
return datetime.datetime.now(tz=datetime.UTC)
return available_for_purchase_date
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
index 9e63911c64..f6726e2088 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
@@ -158,8 +158,7 @@ class ProductVariantCreate(ModelMutation):
code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
params={"attributes": attribute_values.keys()},
)
- else:
- used_attribute_values.append(attribute_values)
+ used_attribute_values.append(attribute_values)
@classmethod
def clean_input(
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
index 53c86501da..11880b9ee6 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
@@ -86,7 +86,7 @@ class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):
)
@classmethod
- def get_instance(cls, info: ResolveInfo, **data):
+ def get_instance(cls, info: ResolveInfo, **data) -> models.ProductVariant | None:
"""Prefetch related fields that are needed to process the mutation.
If we are updating an instance and want to update its attributes, prefetch them.
@@ -99,7 +99,7 @@ class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):
if attributes:
# Prefetches needed by AttributeAssignmentMixin and
# associate_attribute_values_to_instance
- qs = cls.Meta.model.objects.prefetch_related(
+ qs = models.ProductVariant.objects.prefetch_related(
"product__product_type__variant_attributes__values",
"product__product_type__attributevariant",
)
@@ -112,9 +112,9 @@ class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):
if object_id:
return cls.get_node_or_error(
- info, object_id, only_type="ProductVariant", qs=qs
+ info, object_id, only_type=ProductVariant, qs=qs
)
- elif object_sku:
+ if object_sku:
instance = qs.filter(sku=object_sku).first()
if not instance:
raise ValidationError(
@@ -126,6 +126,7 @@ class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):
}
)
return instance
+ return None
@classmethod
def set_track_inventory(cls, _info, instance, cleaned_input):
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index ab6139b6c2..cbb8fef27b 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -103,15 +103,14 @@ def resolve_product(
if id:
_type, id = from_global_id_or_error(id, "Product")
return qs.filter(id=id).first()
- elif slug:
+ if slug:
if slug_language_code:
return qs.filter(
translations__language_code=slug_language_code, translations__slug=slug
).first()
return qs.filter(slug=slug).first()
- else:
- return qs.filter(external_reference=external_reference).first()
+ return qs.filter(external_reference=external_reference).first()
@traced_resolver
@@ -181,10 +180,9 @@ def resolve_variant(
if id:
_, id = from_global_id_or_error(id, "ProductVariant")
return qs.filter(pk=id).first()
- elif sku:
+ if sku:
return qs.filter(sku=sku).first()
- else:
- return qs.filter(external_reference=external_reference).first()
+ return qs.filter(external_reference=external_reference).first()
@traced_resolver
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 05953ab0f4..20eb8ec542 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -1,4 +1,5 @@
import graphene
+from promise import Promise
from ...permission.enums import ProductPermissions
from ...permission.utils import has_one_of_permissions
@@ -365,7 +366,7 @@ class ProductQueries(graphene.ObjectType):
slug=None,
slug_language_code=None,
**kwargs,
- ):
+ ) -> Promise[Category] | None | Category:
validate_one_of_args_is_in_query("id", id, "slug", slug)
if id:
_, id = from_global_id_or_error(id, Category)
@@ -379,6 +380,7 @@ class ProductQueries(graphene.ObjectType):
info, slug, slug_language_code
)
return CategoryBySlugLoader(info.context).load(slug)
+ return None
@staticmethod
@traced_resolver
@@ -502,8 +504,7 @@ class ProductQueries(graphene.ObjectType):
.load(str(channel))
.then(_resolve_product)
)
- else:
- return _resolve_product(None)
+ return _resolve_product(None)
@staticmethod
@traced_resolver
@@ -539,8 +540,7 @@ class ProductQueries(graphene.ObjectType):
.load(str(channel))
.then(_resolve_products)
)
- else:
- return _resolve_products(None)
+ return _resolve_products(None)
@staticmethod
def resolve_product_type(_root, info: ResolveInfo, *, id):
@@ -601,8 +601,7 @@ class ProductQueries(graphene.ObjectType):
.load(str(channel))
.then(_resolve_product_variant)
)
- else:
- return _resolve_product_variant(None)
+ return _resolve_product_variant(None)
@staticmethod
def resolve_product_variants(
@@ -640,8 +639,7 @@ class ProductQueries(graphene.ObjectType):
.load(str(channel))
.then(_resolve_product_variants)
)
- else:
- return _resolve_product_variants(None)
+ return _resolve_product_variants(None)
@staticmethod
@traced_resolver
diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.py
index b35b8beff6..318289f85f 100644
--- a/saleor/graphql/product/types/categories.py
+++ b/saleor/graphql/product/types/categories.py
@@ -2,6 +2,7 @@ from typing import Optional
import graphene
from graphene import relay
+from promise import Promise
from ....permission.utils import has_one_of_permissions
from ....product import models
@@ -118,9 +119,9 @@ class Category(ModelObjectType[models.Category]):
info,
size: Optional[int] = None,
format: Optional[str] = None,
- ):
+ ) -> None | Image | Promise[Image]:
if not root.background_image:
- return
+ return None
alt = root.background_image_alt
if size == 0:
@@ -205,8 +206,7 @@ class Category(ModelObjectType[models.Category]):
.load(str(channel))
.then(_resolve_products)
)
- else:
- return _resolve_products(None)
+ return _resolve_products(None)
@staticmethod
def __resolve_references(roots: list["Category"], info):
diff --git a/saleor/graphql/product/types/collections.py b/saleor/graphql/product/types/collections.py
index 111ed4c20c..406d9b496b 100644
--- a/saleor/graphql/product/types/collections.py
+++ b/saleor/graphql/product/types/collections.py
@@ -3,6 +3,7 @@ from typing import Optional
import graphene
from graphene import relay
+from promise import Promise
from ....permission.enums import ProductPermissions
from ....product import models
@@ -105,10 +106,10 @@ class Collection(ChannelContextTypeWithMetadata[models.Collection]):
info: ResolveInfo,
size: Optional[int] = None,
format: Optional[str] = None,
- ):
+ ) -> None | Image | Promise[Image]:
node = root.node
if not node.background_image:
- return
+ return None
alt = node.background_image_alt
if size == 0:
@@ -163,8 +164,7 @@ class Collection(ChannelContextTypeWithMetadata[models.Collection]):
.load(str(root.channel_slug))
.then(_resolve_products)
)
- else:
- return _resolve_products(None)
+ return _resolve_products(None)
@staticmethod
def resolve_channel_listings(root: ChannelContext[models.Collection], info):
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index a4eb9a52ba..05b82b943f 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -437,8 +437,7 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):
return StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader( # noqa: E501
info.context
).load((root.node.id, country_code, root.channel_slug))
- else:
- return StocksByProductVariantIdLoader(info.context).load(root.node.id)
+ return StocksByProductVariantIdLoader(info.context).load(root.node.id)
@staticmethod
@load_site_callback
@@ -1296,12 +1295,11 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):
.load(root.node.id)
.then(get_selected_attribute_by_slug)
)
- else:
- return (
- SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)
- .load(root.node.id)
- .then(get_selected_attribute_by_slug)
- )
+ return (
+ SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)
+ .load(root.node.id)
+ .then(get_selected_attribute_by_slug)
+ )
@staticmethod
def resolve_attributes(root: ChannelContext[models.Product], info):
@@ -1314,10 +1312,9 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):
return SelectedAttributesAllByProductIdLoader(info.context).load(
root.node.id
)
- else:
- return SelectedAttributesVisibleInStorefrontByProductIdLoader(
- info.context
- ).load(root.node.id)
+ return SelectedAttributesVisibleInStorefrontByProductIdLoader(
+ info.context
+ ).load(root.node.id)
@staticmethod
def resolve_media_by_id(root: ChannelContext[models.Product], info, *, id):
@@ -1743,12 +1740,11 @@ class ProductType(ModelObjectType[models.ProductType]):
.load(root.pk)
.then(unpack_attributes)
)
- else:
- return (
- ProductAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)
- .load(root.pk)
- .then(unpack_attributes)
- )
+ return (
+ ProductAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)
+ .load(root.pk)
+ .then(unpack_attributes)
+ )
@staticmethod
@traced_resolver
@@ -1780,12 +1776,11 @@ class ProductType(ModelObjectType[models.ProductType]):
.load(root.pk)
.then(apply_variant_selection_filter)
)
- else:
- return (
- VariantAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)
- .load(root.pk)
- .then(apply_variant_selection_filter)
- )
+ return (
+ VariantAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)
+ .load(root.pk)
+ .then(apply_variant_selection_filter)
+ )
@staticmethod
@traced_resolver
@@ -1823,12 +1818,11 @@ class ProductType(ModelObjectType[models.ProductType]):
.load(root.pk)
.then(apply_variant_selection_filter)
)
- else:
- return (
- VariantAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)
- .load(root.pk)
- .then(apply_variant_selection_filter)
- )
+ return (
+ VariantAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)
+ .load(root.pk)
+ .then(apply_variant_selection_filter)
+ )
@staticmethod
def resolve_products(root: models.ProductType, info, *, channel=None, **kwargs):
@@ -1853,8 +1847,7 @@ class ProductType(ModelObjectType[models.ProductType]):
.load(str(channel))
.then(_resolve_products)
)
- else:
- return _resolve_products(None)
+ return _resolve_products(None)
@staticmethod
def resolve_available_attributes(root: models.ProductType, info, **kwargs):
@@ -1880,7 +1873,7 @@ class ProductType(ModelObjectType[models.ProductType]):
)
@staticmethod
- def __resolve_references(roots: list["ProductType"], info):
+ def __resolve_references(roots: list[models.ProductType], info):
database_connection_name = get_database_connection_name(info.context)
return resolve_federation_references(
ProductType,
@@ -1921,12 +1914,12 @@ class ProductMedia(ModelObjectType[models.ProductMedia]):
*,
size: Optional[int] = None,
format: Optional[str] = None,
- ):
+ ) -> str | None | Promise[str]:
if root.external_url:
return root.external_url
if not root.image:
- return
+ return None
if size == 0:
return build_absolute_uri(root.image.url)
@@ -1934,7 +1927,7 @@ class ProductMedia(ModelObjectType[models.ProductMedia]):
format = get_thumbnail_format(format)
selected_size = get_thumbnail_size(size)
- def _resolve_url(thumbnail):
+ def _resolve_url(thumbnail) -> str:
url = get_image_or_proxy_url(
thumbnail, str(root.id), "ProductMedia", selected_size, format
)
@@ -1956,7 +1949,7 @@ class ProductMedia(ModelObjectType[models.ProductMedia]):
)
@staticmethod
- def resolve_product_id(root: models.ProductMedia, info):
+ def resolve_product_id(root: models.ProductMedia, info) -> str:
return graphene.Node.to_global_id("Product", root.product_id)
@@ -1980,7 +1973,7 @@ class ProductImage(BaseObjectType):
description = "Represents a product image."
@staticmethod
- def resolve_id(root: models.ProductMedia, info):
+ def resolve_id(root: models.ProductMedia, info) -> str:
return graphene.Node.to_global_id("ProductImage", root.id)
@staticmethod
@@ -1990,9 +1983,9 @@ class ProductImage(BaseObjectType):
*,
size: Optional[int] = None,
format: Optional[str] = None,
- ):
+ ) -> None | str | Promise[str]:
if not root.image:
- return
+ return None
if size == 0:
return build_absolute_uri(root.image.url)
diff --git a/saleor/graphql/shipping/mutations/base.py b/saleor/graphql/shipping/mutations/base.py
index 2bc178c3b7..7166914f0e 100644
--- a/saleor/graphql/shipping/mutations/base.py
+++ b/saleor/graphql/shipping/mutations/base.py
@@ -173,8 +173,7 @@ class ShippingZoneMixin:
)
}
)
- else:
- cls._extend_shipping_zone_countries(data)
+ cls._extend_shipping_zone_countries(data)
else:
data["default"] = False
return data
diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.py
index 078c9b40bd..c64318c61d 100644
--- a/saleor/graphql/shipping/types.py
+++ b/saleor/graphql/shipping/types.py
@@ -84,8 +84,7 @@ class ShippingMethodChannelListing(
def resolve_minimum_order_price(root: models.ShippingMethodChannelListing, info):
if root.minimum_order_price_amount is None:
return None
- else:
- return root.minimum_order_price
+ return root.minimum_order_price
class ShippingMethodPostalCodeRule(
diff --git a/saleor/graphql/shop/mutations/gift_card_settings_update.py b/saleor/graphql/shop/mutations/gift_card_settings_update.py
index 56a272ce09..7a9d13028b 100644
--- a/saleor/graphql/shop/mutations/gift_card_settings_update.py
+++ b/saleor/graphql/shop/mutations/gift_card_settings_update.py
@@ -82,5 +82,5 @@ class GiftCardSettingsUpdate(BaseMutation):
)
}
)
- elif expiry_type == GiftCardSettingsExpiryType.NEVER_EXPIRE:
+ if expiry_type == GiftCardSettingsExpiryType.NEVER_EXPIRE:
input["expiry_period"] = None
diff --git a/saleor/graphql/site/dataloaders.py b/saleor/graphql/site/dataloaders.py
index f3aa2b3cbd..c5e21708dd 100644
--- a/saleor/graphql/site/dataloaders.py
+++ b/saleor/graphql/site/dataloaders.py
@@ -19,7 +19,7 @@ class SiteByIdLoader(DataLoader[int, Site]):
return [sites_mapped.get(site_id) for site_id in keys]
-class SiteByHostLoader(DataLoader):
+class SiteByHostLoader(DataLoader[str, Site]):
context_key = "site_by_host"
def batch_load(self, keys):
diff --git a/saleor/graphql/translations/dataloaders.py b/saleor/graphql/translations/dataloaders.py
index 8c63c690f9..a43e61559d 100644
--- a/saleor/graphql/translations/dataloaders.py
+++ b/saleor/graphql/translations/dataloaders.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from typing import Generic, TypeVar
from ...attribute import models as attribute_models
from ...discount import models as discount_models
@@ -9,8 +10,12 @@ from ...shipping import models as shipping_models
from ...site import models as site_models
from ..core.dataloaders import DataLoader
+T = TypeVar("T")
-class BaseTranslationByIdAndLanguageCodeLoader(DataLoader):
+
+class BaseTranslationByIdAndLanguageCodeLoader(
+ DataLoader[tuple[int, str], T], Generic[T]
+):
model = None
relation_name = None
@@ -42,7 +47,7 @@ class BaseTranslationByIdAndLanguageCodeLoader(DataLoader):
class AttributeTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[attribute_models.AttributeTranslation]
):
context_key = "attribute_translation_by_id_and_language_code"
model = attribute_models.AttributeTranslation
@@ -50,7 +55,7 @@ class AttributeTranslationByIdAndLanguageCodeLoader(
class AttributeValueTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[attribute_models.AttributeValueTranslation]
):
context_key = "attribute_value_translation_by_id_and_language_code"
model = attribute_models.AttributeValueTranslation
@@ -58,7 +63,7 @@ class AttributeValueTranslationByIdAndLanguageCodeLoader(
class CategoryTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[product_models.CategoryTranslation]
):
context_key = "category_translation_by_id_and_language_code"
model = product_models.CategoryTranslation
@@ -66,7 +71,7 @@ class CategoryTranslationByIdAndLanguageCodeLoader(
class CollectionTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[product_models.CollectionTranslation]
):
context_key = "collection_translation_by_id_and_language_code"
model = product_models.CollectionTranslation
@@ -74,7 +79,7 @@ class CollectionTranslationByIdAndLanguageCodeLoader(
class MenuItemTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[menu_models.MenuItemTranslation]
):
context_key = "menu_item_translation_by_id_and_language_code"
model = menu_models.MenuItemTranslation
@@ -82,7 +87,7 @@ class MenuItemTranslationByIdAndLanguageCodeLoader(
class PageTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[page_models.PageTranslation]
):
context_key = "page_translation_by_id_and_language_code"
model = page_models.PageTranslation
@@ -90,7 +95,7 @@ class PageTranslationByIdAndLanguageCodeLoader(
class ProductTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[product_models.ProductTranslation]
):
context_key = "product_translation_by_id_and_language_code"
model = product_models.ProductTranslation
@@ -98,7 +103,7 @@ class ProductTranslationByIdAndLanguageCodeLoader(
class ProductVariantTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[product_models.ProductVariantTranslation]
):
context_key = "product_variant_translation_by_id_and_language_code"
model = product_models.ProductVariantTranslation
@@ -106,7 +111,7 @@ class ProductVariantTranslationByIdAndLanguageCodeLoader(
class ShippingMethodTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[shipping_models.ShippingMethodTranslation]
):
context_key = "shipping_method_translation_by_id_and_language_code"
model = shipping_models.ShippingMethodTranslation
@@ -114,7 +119,7 @@ class ShippingMethodTranslationByIdAndLanguageCodeLoader(
class SiteSettingsTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[site_models.SiteSettingsTranslation]
):
context_key = "site_settings_translation_by_id_and_language_code"
model = site_models.SiteSettingsTranslation
@@ -122,7 +127,7 @@ class SiteSettingsTranslationByIdAndLanguageCodeLoader(
class VoucherTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[discount_models.VoucherTranslation]
):
context_key = "voucher_translation_by_id_and_language_code"
model = discount_models.VoucherTranslation
@@ -130,7 +135,7 @@ class VoucherTranslationByIdAndLanguageCodeLoader(
class PromotionTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[discount_models.PromotionTranslation]
):
context_key = "promotion_translation_by_id_and_language_code"
model = discount_models.PromotionTranslation
@@ -138,7 +143,7 @@ class PromotionTranslationByIdAndLanguageCodeLoader(
class PromotionRuleTranslationByIdAndLanguageCodeLoader(
- BaseTranslationByIdAndLanguageCodeLoader
+ BaseTranslationByIdAndLanguageCodeLoader[discount_models.PromotionRuleTranslation]
):
context_key = "promotion_rule_translation_by_id_and_language_code"
model = discount_models.PromotionRuleTranslation
diff --git a/saleor/graphql/translations/resolvers.py b/saleor/graphql/translations/resolvers.py
index e3b6d94bc4..fcb24789e8 100644
--- a/saleor/graphql/translations/resolvers.py
+++ b/saleor/graphql/translations/resolvers.py
@@ -8,9 +8,10 @@ from ...shipping import models as shipping_models
from ...site import models as site_models
from ..core import ResolveInfo
from ..core.context import get_database_connection_name
+from ..core.dataloaders import DataLoader
from . import dataloaders
-TYPE_TO_TRANSLATION_LOADER_MAP = {
+TYPE_TO_TRANSLATION_LOADER_MAP: dict[type, type[DataLoader]] = {
attribute_models.Attribute: (
dataloaders.AttributeTranslationByIdAndLanguageCodeLoader
),
diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.py
index 8b3aa63b8b..d5c511fc86 100644
--- a/saleor/graphql/translations/schema.py
+++ b/saleor/graphql/translations/schema.py
@@ -59,7 +59,7 @@ class TranslatableItem(graphene.Union):
instance_type == Promotion and instance.old_sale_id
):
return translation_types.SaleTranslatableContent
- elif instance_type in TYPES_TRANSLATIONS_MAP:
+ if instance_type in TYPES_TRANSLATIONS_MAP:
return TYPES_TRANSLATIONS_MAP[instance_type]
return super().resolve_type(instance, info)
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index e3eaf3153c..4b3705f3ba 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -418,12 +418,11 @@ class ProductTranslatableContent(ModelObjectType[product_models.Product]):
.load(root.id)
.then(get_translatable_attribute_values)
)
- else:
- return (
- SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)
- .load(root.id)
- .then(get_translatable_attribute_values)
- )
+ return (
+ SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)
+ .load(root.id)
+ .then(get_translatable_attribute_values)
+ )
@staticmethod
def resolve_product_id(root: product_models.Product, _info):
@@ -714,12 +713,11 @@ class PageTranslatableContent(ModelObjectType[page_models.Page]):
.load(root.id)
.then(get_translatable_attribute_values)
)
- else:
- return (
- SelectedAttributesVisibleInStorefrontPageIdLoader(info.context)
- .load(root.id)
- .then(get_translatable_attribute_values)
- )
+ return (
+ SelectedAttributesVisibleInStorefrontPageIdLoader(info.context)
+ .load(root.id)
+ .then(get_translatable_attribute_values)
+ )
@staticmethod
def resolve_page_id(root: page_models.Page, _info):
diff --git a/saleor/graphql/utils/sorting.py b/saleor/graphql/utils/sorting.py
index c0fedd4ee5..adfb9b6186 100644
--- a/saleor/graphql/utils/sorting.py
+++ b/saleor/graphql/utils/sorting.py
@@ -75,7 +75,7 @@ def sort_queryset(
raise GraphQLError(
"You must provide either `field` or `attributeId` to sort the products."
)
- elif sorting_attribute is not None: # empty string as sorting_attribute is valid
+ if sorting_attribute is not None: # empty string as sorting_attribute is valid
return _sort_queryset_by_attribute(
queryset, sorting_attribute, sorting_direction
)
diff --git a/saleor/graphql/utils/validators.py b/saleor/graphql/utils/validators.py
index ee9a6ac512..9b835f0ef6 100644
--- a/saleor/graphql/utils/validators.py
+++ b/saleor/graphql/utils/validators.py
@@ -65,8 +65,7 @@ def __queries_or_introspection_in_inline_fragment(
is_query and not fragment.type_condition
):
return __queries_or_introspection_in_selections(selections, is_query=True)
- else:
- return __queries_or_introspection_in_selections(selections, is_query=False)
+ return __queries_or_introspection_in_selections(selections, is_query=False)
def __queries_or_introspection_in_operation_definition(definition: OperationDefinition):
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index e62d227314..d2b0ec2668 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -112,13 +112,11 @@ class GraphQLView(View):
if settings.PLAYGROUND_ENABLED:
return self.render_playground(request)
return HttpResponseNotAllowed(["OPTIONS", "POST"])
- elif request.method == "POST":
+ if request.method == "POST":
return self.handle_query(request)
- else:
- if settings.PLAYGROUND_ENABLED:
- return HttpResponseNotAllowed(["GET", "OPTIONS", "POST"])
- else:
- return HttpResponseNotAllowed(["OPTIONS", "POST"])
+ if settings.PLAYGROUND_ENABLED:
+ return HttpResponseNotAllowed(["GET", "OPTIONS", "POST"])
+ return HttpResponseNotAllowed(["OPTIONS", "POST"])
def render_playground(self, request):
return render(
diff --git a/saleor/graphql/webhook/mutations/webhook_dry_run.py b/saleor/graphql/webhook/mutations/webhook_dry_run.py
index 403e4ca7ba..ec48215e26 100644
--- a/saleor/graphql/webhook/mutations/webhook_dry_run.py
+++ b/saleor/graphql/webhook/mutations/webhook_dry_run.py
@@ -111,11 +111,10 @@ class WebhookDryRun(BaseMutation):
if type == "Sale":
object_id = cls.get_global_id_or_error(object_id, "Sale")
return discount_models.Promotion.objects.get(old_sale_id=object_id)
- elif type == "App":
+ if type == "App":
qs = App.objects.filter(removed_at__isnull=True)
return cls.get_node_or_error(info, object_id, field="objectId", qs=qs)
- else:
- return cls.get_node_or_error(info, object_id, field="objectId")
+ return cls.get_node_or_error(info, object_id, field="objectId")
@classmethod
def perform_mutation(cls, _root, info, **data):
diff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.py
index d3cd649464..81849bb059 100644
--- a/saleor/graphql/webhook/mutations/webhook_trigger.py
+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py
@@ -88,7 +88,7 @@ class WebhookTrigger(BaseMutation):
event_name = (
event_type[0].upper() + to_camel_case(event_type)[1:] if event_type else ""
)
- raise_validation_error(
+ return raise_validation_error(
message=(
f"Event type: {event_name}, "
f"which was parsed from webhook's "
diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.py
index e0a538593b..12d7096fcd 100644
--- a/saleor/graphql/webhook/resolvers.py
+++ b/saleor/graphql/webhook/resolvers.py
@@ -54,12 +54,11 @@ def resolve_sample_payload(info: ResolveInfo, event_name, app):
)
if not required_permission:
return payloads.generate_sample_payload(event_name)
- else:
- if app and app.has_perm(required_permission):
- return payloads.generate_sample_payload(event_name)
- if user and user.has_perm(required_permission):
- return payloads.generate_sample_payload(event_name)
- raise PermissionDenied(permissions=[required_permission])
+ if app and app.has_perm(required_permission):
+ return payloads.generate_sample_payload(event_name)
+ if user and user.has_perm(required_permission):
+ return payloads.generate_sample_payload(event_name)
+ raise PermissionDenied(permissions=[required_permission])
def resolve_shipping_methods_for_checkout(
diff --git a/saleor/menu/migrations/0007_auto_20180807_0547.py b/saleor/menu/migrations/0007_auto_20180807_0547.py
index ae9a540e0d..d1b1e60d30 100644
--- a/saleor/menu/migrations/0007_auto_20180807_0547.py
+++ b/saleor/menu/migrations/0007_auto_20180807_0547.py
@@ -17,11 +17,11 @@ def get_linked_object_url(menu_item):
return Category(
**get_linked_object_kwargs(menu_item.category)
).get_absolute_url()
- elif menu_item.collection:
+ if menu_item.collection:
return Collection(
**get_linked_object_kwargs(menu_item.collection)
).get_absolute_url()
- elif menu_item.page:
+ if menu_item.page:
return Page(**get_linked_object_kwargs(menu_item.page)).get_absolute_url()
return None
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 06d630ac1c..0dca192aa4 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -198,7 +198,7 @@ def create_order_line(
line_data,
manager,
allocate_stock=False,
-):
+) -> OrderLine:
channel = order.channel
variant = line_data.variant
quantity = line_data.quantity
@@ -348,7 +348,7 @@ def add_variant_to_order(
app,
manager,
allocate_stock=False,
-):
+) -> OrderLine:
"""Add total_quantity of variant to order.
Returns an order line the variant was added to.
@@ -397,13 +397,12 @@ def add_variant_to_order(
return line
- if line_data.variant_id:
- return create_order_line(
- order,
- line_data,
- manager,
- allocate_stock,
- )
+ return create_order_line(
+ order,
+ line_data,
+ manager,
+ allocate_stock,
+ )
def update_line_base_unit_prices_with_custom_price(
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 32ec48b58f..e5bb4402a1 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -222,7 +222,7 @@ def _create_transaction_data(
def _request_payment_action(
- transaction_action_data: "TransactionActionData",
+ transaction_action_data: TransactionActionData,
manager: "PluginsManager",
channel_slug: str,
event_type: str,
@@ -564,12 +564,12 @@ def payment_refund_or_void(
def _get_success_transaction(
kind: str, payment: Payment, transaction_id: Optional[str]
-):
+) -> None | Transaction:
if not transaction_id:
try:
transaction_id = _get_past_transaction_token(payment, kind)
except PaymentError:
- return
+ return None
return payment.transactions.filter(
token=transaction_id,
action_required=False,
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 43f6a49866..6a390435ca 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -258,7 +258,7 @@ class AdyenGatewayPlugin(BasePlugin):
config = self._get_gateway_config()
if path.startswith(WEBHOOK_PATH):
return handle_webhook(request, config)
- elif path.startswith(ADDITIONAL_ACTION_PATH):
+ if path.startswith(ADDITIONAL_ACTION_PATH):
with opentracing.global_tracer().start_active_span(
"adyen.checkout.payment_details"
) as scope:
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index c52d385659..bfe435833b 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -233,7 +233,7 @@ def handle_not_created_order(notification, payment, checkout, kind, manager):
ChargeStatus.PARTIALLY_CHARGED,
ChargeStatus.FULLY_CHARGED,
}:
- return
+ return None
transaction = create_new_transaction(
notification, payment, TransactionKind.ACTION_TO_CONFIRM
@@ -586,11 +586,11 @@ def handle_failed_refund(notification: dict[str, Any], gateway_config: GatewayCo
# we don't know anything about refund so we have to skip the notification about
# failed refund.
return
-
if refund_transaction.kind == TransactionKind.REFUND_FAILED:
# The failed refund is already saved
return
- elif refund_transaction.kind == TransactionKind.REFUND_ONGOING:
+
+ if refund_transaction.kind == TransactionKind.REFUND_ONGOING:
# create new failed transaction which will allows us to discover duplicated
# notification
create_new_transaction(notification, payment, TransactionKind.REFUND_FAILED)
diff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.py
index 003d2f071a..d1486696af 100644
--- a/saleor/payment/gateways/np_atobarai/api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -138,7 +138,7 @@ def format_price(price: Decimal, currency: str) -> int:
def _get_goods_name(line: PaymentLineData, config: "ApiConfig") -> str:
if not config.sku_as_name:
return line.product_name
- elif sku := line.product_sku:
+ if sku := line.product_sku:
return sku
return str(line.variant_id)
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.py
index dcb21b492f..cdc5bd4b9f 100644
--- a/saleor/payment/gateways/razorpay/__init__.py
+++ b/saleor/payment/gateways/razorpay/__init__.py
@@ -44,13 +44,14 @@ def _generate_response(
)
-def check_payment_supported(payment_information: PaymentData):
+def check_payment_supported(payment_information: PaymentData) -> str | None:
"""Check that a given payment is supported."""
if payment_information.currency not in SUPPORTED_CURRENCIES:
return errors.UNSUPPORTED_CURRENCY % {"currency": payment_information.currency}
+ return None
-def get_error_message_from_razorpay_error(exc: BaseException):
+def get_error_message_from_razorpay_error(exc: BaseException) -> str:
"""Convert a Razorpay error to a user-friendly error message.
It also logs the exception to stderr.
@@ -58,8 +59,7 @@ def get_error_message_from_razorpay_error(exc: BaseException):
logger.exception(exc)
if isinstance(exc, razorpay.errors.BadRequestError):
return errors.INVALID_REQUEST
- else:
- return errors.SERVER_ERROR
+ return errors.SERVER_ERROR
def clean_razorpay_response(response: dict):
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.py
index eb228df33a..4e0a9ec0ff 100644
--- a/saleor/payment/gateways/stripe/plugin.py
+++ b/saleor/payment/gateways/stripe/plugin.py
@@ -179,10 +179,9 @@ class StripeGatewayPlugin(BasePlugin):
) -> Optional[str]:
if store_payment_method == StorePaymentMethodEnum.ON_SESSION:
return "on_session"
- elif store_payment_method == StorePaymentMethodEnum.OFF_SESSION:
+ if store_payment_method == StorePaymentMethodEnum.OFF_SESSION:
return "off_session"
- else:
- return None
+ return None
def process_payment(
self, payment_information: "PaymentData", previous_value
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 7eaa9221b9..73356e9e4b 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -112,14 +112,13 @@ def _channel_slug_is_different_from_payment_channel_slug(
order = payment.order
if checkout is not None:
return channel_slug != checkout.channel.slug
- elif order is not None:
+ if order is not None:
return channel_slug != order.channel.slug
- else:
- logger.warning(
- "Both payment.checkout and payment.order cannot be None",
- extra={"payment_id": payment.id},
- )
- return True
+ logger.warning(
+ "Both payment.checkout and payment.order cannot be None",
+ extra={"payment_id": payment.id},
+ )
+ return True
def _get_payment(payment_intent_id: str, with_lock=True) -> Optional[Payment]:
@@ -223,7 +222,6 @@ def _finalize_checkout(
logger.info(
"Failed to complete checkout %s.", checkout.pk, extra={"error": str(e)}
)
- return None
def _get_or_create_transaction(
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 14a5a37a3f..67c1c6888d 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -144,7 +144,7 @@ def create_payment_lines_information(
if checkout:
return create_checkout_payment_lines_information(checkout, manager)
- elif order:
+ if order:
return create_order_payment_lines_information(order)
return PaymentLinesData(
@@ -976,11 +976,11 @@ def get_failed_transaction_event_type_for_request_event(
):
if request_event.type == TransactionEventType.AUTHORIZATION_REQUEST:
return TransactionEventType.AUTHORIZATION_FAILURE
- elif request_event.type == TransactionEventType.CHARGE_REQUEST:
+ if request_event.type == TransactionEventType.CHARGE_REQUEST:
return TransactionEventType.CHARGE_FAILURE
- elif request_event.type == TransactionEventType.REFUND_REQUEST:
+ if request_event.type == TransactionEventType.REFUND_REQUEST:
return TransactionEventType.REFUND_FAILURE
- elif request_event.type == TransactionEventType.CANCEL_REQUEST:
+ if request_event.type == TransactionEventType.CANCEL_REQUEST:
return TransactionEventType.CANCEL_FAILURE
return None
@@ -994,17 +994,17 @@ def get_failed_type_based_on_event(event: TransactionEvent):
TransactionEventType.AUTHORIZATION_ADJUSTMENT,
]:
return TransactionEventType.AUTHORIZATION_FAILURE
- elif event.type in [
+ if event.type in [
TransactionEventType.CHARGE_BACK,
TransactionEventType.CHARGE_SUCCESS,
]:
return TransactionEventType.CHARGE_FAILURE
- elif event.type in [
+ if event.type in [
TransactionEventType.REFUND_REVERSE,
TransactionEventType.REFUND_SUCCESS,
]:
return TransactionEventType.REFUND_FAILURE
- elif event.type == TransactionEventType.CANCEL_SUCCESS:
+ if event.type == TransactionEventType.CANCEL_SUCCESS:
return TransactionEventType.CANCEL_FAILURE
return event.type
diff --git a/saleor/permission/utils.py b/saleor/permission/utils.py
index 2052e10d8d..776e3cae99 100644
--- a/saleor/permission/utils.py
+++ b/saleor/permission/utils.py
@@ -86,7 +86,7 @@ def permission_required(
if isinstance(requestor, User):
return requestor.has_perms(perms)
- elif requestor:
+ if requestor:
# for now MANAGE_STAFF permission for app is not supported
if AccountPermissions.MANAGE_STAFF in perms:
return False
diff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.py
index 0540cf46ed..b524c06a7c 100644
--- a/saleor/plugins/admin_email/plugin.py
+++ b/saleor/plugins/admin_email/plugin.py
@@ -218,8 +218,8 @@ class AdminEmailPlugin(BasePlugin):
self,
event: Union[NotifyEventType, str],
payload_func: Callable[[], dict],
- previous_value,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
@@ -234,6 +234,7 @@ class AdminEmailPlugin(BasePlugin):
event_func = event_map[event]
config = asdict(self.config)
event_func(payload_func, config, self)
+ return previous_value
@classmethod
def validate_plugin_configuration(
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index d93408ce01..28269367dc 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1689,7 +1689,7 @@ class BasePlugin:
#
# Note: This method is deprecated in Saleor 3.20 and will be removed in Saleor 3.21.
# Webhook-related functionality will be moved from the plugin to core modules.
- event_delivery_retry: Callable[["EventDelivery", Any], EventDelivery]
+ event_delivery_retry: Callable[[EventDelivery, None], None]
def token_is_required_as_payment_input(self, previous_value):
return previous_value
@@ -1774,7 +1774,7 @@ class BasePlugin:
new_value = new_value.lower() == "true"
if item_type == ConfigurationTypeField.OUTPUT:
# OUTPUT field is read only. No need to update it
- return
+ return None
return new_value
@classmethod
diff --git a/saleor/plugins/email_common.py b/saleor/plugins/email_common.py
index eb69c21921..2be04e82b5 100644
--- a/saleor/plugins/email_common.py
+++ b/saleor/plugins/email_common.py
@@ -143,10 +143,10 @@ def format_datetime(this, date, date_format=None):
return date.strftime(date_format)
-def get_product_image_thumbnail(this, size: int, image_data):
+def get_product_image_thumbnail(this, size: int, image_data) -> None | str:
"""Use provided size to get a correct image."""
if image_data is None:
- return
+ return None
expected_size = get_thumbnail_size(size)
return image_data.get("original", {}).get(str(expected_size))
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index b5940a6f01..618aae114f 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -2680,7 +2680,7 @@ class PluginsManager(PaymentInterface):
def save_plugin_configuration(
self, plugin_id, channel_slug: Optional[str], cleaned_data: dict
- ):
+ ) -> None | PluginConfiguration:
if channel_slug:
plugins = self.get_plugins(channel_slug=channel_slug)
channel = (
@@ -2709,6 +2709,7 @@ class PluginsManager(PaymentInterface):
plugin.active = configuration.active
plugin.configuration = configuration.configuration
return configuration
+ return None
def get_plugin(
self, plugin_id: str, channel_slug: Optional[str] = None
@@ -2893,6 +2894,5 @@ def get_plugins_manager(
with opentracing.global_tracer().start_active_span("get_plugins_manager"):
if allow_replica:
return PluginsManager(settings.PLUGINS, requestor_getter, allow_replica)
- else:
- with allow_writer():
- return PluginsManager(settings.PLUGINS, requestor_getter, allow_replica)
+ with allow_writer():
+ return PluginsManager(settings.PLUGINS, requestor_getter, allow_replica)
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 87fc384405..6446f65386 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -645,7 +645,7 @@ def get_incorrect_or_missing_urls(urls: dict) -> list[str]:
return incorrect_urls
-def get_incorrect_fields(plugin_configuration: "PluginConfiguration"):
+def get_incorrect_fields(plugin_configuration: "PluginConfiguration") -> list[str]:
"""Return missing or incorrect configuration fields for OpenIDConnectPlugin."""
configuration = plugin_configuration.configuration
configuration = {item["name"]: item["value"] for item in configuration}
@@ -662,7 +662,6 @@ def get_incorrect_fields(plugin_configuration: "PluginConfiguration"):
"oauth_token_url": configuration["oauth_token_url"],
}
)
-
elif configuration["user_info_url"]:
urls_to_validate.update(
{
@@ -686,6 +685,7 @@ def get_incorrect_fields(plugin_configuration: "PluginConfiguration"):
if not configuration["client_secret"]:
incorrect_fields.append("client_secret")
return incorrect_fields
+ return []
def get_saleor_permissions_qs_from_scope(scope: str) -> QuerySet[Permission]:
diff --git a/saleor/plugins/sendgrid/plugin.py b/saleor/plugins/sendgrid/plugin.py
index 8ee0e8448e..6a8433d0a8 100644
--- a/saleor/plugins/sendgrid/plugin.py
+++ b/saleor/plugins/sendgrid/plugin.py
@@ -226,8 +226,8 @@ class SendgridEmailPlugin(BasePlugin):
self,
event: Union[NotifyEventType, str],
payload_func: Callable[[], dict],
- previous_value,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
@@ -254,6 +254,7 @@ class SendgridEmailPlugin(BasePlugin):
return previous_value
payload = payload_func()
event_task.delay(payload, asdict(self.config))
+ return previous_value
@classmethod
def validate_plugin_configuration(
diff --git a/saleor/plugins/user_email/plugin.py b/saleor/plugins/user_email/plugin.py
index e2006382a9..1ef9e09724 100644
--- a/saleor/plugins/user_email/plugin.py
+++ b/saleor/plugins/user_email/plugin.py
@@ -392,8 +392,8 @@ class UserEmailPlugin(BasePlugin):
self,
event: Union[NotifyEventType, str],
payload_func: Callable[[], dict],
- previous_value,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
event_map = get_user_event_map()
@@ -408,6 +408,7 @@ class UserEmailPlugin(BasePlugin):
config = asdict(self.config)
self._add_missing_configuration(config)
event_func(payload_func, config, self)
+ return previous_value
@classmethod
def validate_plugin_configuration(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index aae4b9cd60..07af8b103d 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -255,6 +255,7 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.ACCOUNT_CONFIRMED,
user,
)
+ return previous_value
def account_confirmation_requested(
self,
@@ -273,6 +274,7 @@ class WebhookPlugin(BasePlugin):
token,
redirect_url,
)
+ return previous_value
def account_change_email_requested(
self,
@@ -293,6 +295,7 @@ class WebhookPlugin(BasePlugin):
redirect_url,
new_email,
)
+ return previous_value
def account_email_changed(
self,
@@ -305,6 +308,7 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.ACCOUNT_EMAIL_CHANGED,
user,
)
+ return previous_value
def account_set_password_requested(
self,
@@ -323,6 +327,7 @@ class WebhookPlugin(BasePlugin):
token,
redirect_url,
)
+ return previous_value
def account_delete_requested(
self,
@@ -341,6 +346,7 @@ class WebhookPlugin(BasePlugin):
token,
redirect_url,
)
+ return previous_value
def account_deleted(self, user: "User", previous_value: None) -> None:
if not self.active:
@@ -349,6 +355,7 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.ACCOUNT_DELETED,
user,
)
+ return previous_value
def _trigger_address_event(self, event_type, address):
if webhooks := get_webhooks_for_event(event_type):
@@ -376,16 +383,19 @@ class WebhookPlugin(BasePlugin):
if not self.active:
return previous_value
self._trigger_address_event(WebhookEventAsyncType.ADDRESS_CREATED, address)
+ return previous_value
def address_updated(self, address: "Address", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_address_event(WebhookEventAsyncType.ADDRESS_UPDATED, address)
+ return previous_value
def address_deleted(self, address: "Address", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_address_event(WebhookEventAsyncType.ADDRESS_DELETED, address)
+ return previous_value
def _trigger_app_event(self, event_type, app):
if webhooks := get_webhooks_for_event(event_type):
@@ -405,21 +415,25 @@ class WebhookPlugin(BasePlugin):
if not self.active:
return previous_value
self._trigger_app_event(WebhookEventAsyncType.APP_INSTALLED, app)
+ return previous_value
def app_updated(self, app: "App", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_app_event(WebhookEventAsyncType.APP_UPDATED, app)
+ return previous_value
def app_deleted(self, app: "App", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_app_event(WebhookEventAsyncType.APP_DELETED, app)
+ return previous_value
def app_status_changed(self, app: "App", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_app_event(WebhookEventAsyncType.APP_STATUS_CHANGED, app)
+ return previous_value
def _trigger_attribute_event(self, event_type, attribute, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -445,6 +459,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_attribute_event(
WebhookEventAsyncType.ATTRIBUTE_CREATED, attribute
)
+ return previous_value
def attribute_updated(
self, attribute: "Attribute", previous_value: None, webhooks=None
@@ -454,6 +469,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_attribute_event(
WebhookEventAsyncType.ATTRIBUTE_UPDATED, attribute, webhooks=webhooks
)
+ return previous_value
def attribute_deleted(
self, attribute: "Attribute", previous_value: None, webhooks=None
@@ -463,6 +479,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_attribute_event(
WebhookEventAsyncType.ATTRIBUTE_DELETED, attribute, webhooks=webhooks
)
+ return previous_value
def _trigger_attribute_value_event(
self, event_type, attribute_value, webhooks=None
@@ -497,6 +514,7 @@ class WebhookPlugin(BasePlugin):
attribute_value,
webhooks=webhooks,
)
+ return previous_value
def attribute_value_updated(
self, attribute_value: "AttributeValue", previous_value: None
@@ -506,6 +524,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_attribute_value_event(
WebhookEventAsyncType.ATTRIBUTE_VALUE_UPDATED, attribute_value
)
+ return previous_value
def attribute_value_deleted(
self, attribute_value: "AttributeValue", previous_value: None, webhooks=None
@@ -517,6 +536,7 @@ class WebhookPlugin(BasePlugin):
attribute_value,
webhooks=webhooks,
)
+ return previous_value
def __trigger_category_event(self, event_type, category, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -538,11 +558,13 @@ class WebhookPlugin(BasePlugin):
if not self.active:
return previous_value
self.__trigger_category_event(WebhookEventAsyncType.CATEGORY_CREATED, category)
+ return previous_value
def category_updated(self, category: "Category", previous_value: None) -> None:
if not self.active:
return previous_value
self.__trigger_category_event(WebhookEventAsyncType.CATEGORY_UPDATED, category)
+ return previous_value
def category_deleted(
self, category: "Category", previous_value: None, webhooks=None
@@ -552,6 +574,7 @@ class WebhookPlugin(BasePlugin):
self.__trigger_category_event(
WebhookEventAsyncType.CATEGORY_DELETED, category, webhooks=webhooks
)
+ return previous_value
def __trigger_channel_event(self, event_type, channel, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -574,6 +597,7 @@ class WebhookPlugin(BasePlugin):
if not self.active:
return previous_value
self.__trigger_channel_event(WebhookEventAsyncType.CHANNEL_CREATED, channel)
+ return previous_value
def channel_updated(
self, channel: "Channel", previous_value: None, webhooks=None
@@ -583,11 +607,13 @@ class WebhookPlugin(BasePlugin):
self.__trigger_channel_event(
WebhookEventAsyncType.CHANNEL_UPDATED, channel, webhooks=webhooks
)
+ return previous_value
def channel_deleted(self, channel: "Channel", previous_value: None) -> None:
if not self.active:
return previous_value
self.__trigger_channel_event(WebhookEventAsyncType.CHANNEL_DELETED, channel)
+ return previous_value
def channel_status_changed(self, channel: "Channel", previous_value: None) -> None:
if not self.active:
@@ -595,6 +621,7 @@ class WebhookPlugin(BasePlugin):
self.__trigger_channel_event(
WebhookEventAsyncType.CHANNEL_STATUS_CHANGED, channel
)
+ return previous_value
def channel_metadata_updated(
self, channel: "Channel", previous_value: None
@@ -604,6 +631,7 @@ class WebhookPlugin(BasePlugin):
self.__trigger_channel_event(
WebhookEventAsyncType.CHANNEL_METADATA_UPDATED, channel
)
+ return previous_value
def _trigger_gift_card_event(
self, event_type, gift_card: "GiftCard", webhooks=None
@@ -632,6 +660,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_gift_card_event(
WebhookEventAsyncType.GIFT_CARD_CREATED, gift_card, webhooks=webhooks
)
+ return previous_value
def gift_card_updated(self, gift_card: "GiftCard", previous_value: None) -> None:
if not self.active:
@@ -639,6 +668,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_gift_card_event(
WebhookEventAsyncType.GIFT_CARD_UPDATED, gift_card
)
+ return previous_value
def gift_card_deleted(
self, gift_card: "GiftCard", previous_value: None, webhooks=None
@@ -648,6 +678,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_gift_card_event(
WebhookEventAsyncType.GIFT_CARD_DELETED, gift_card, webhooks=webhooks
)
+ return previous_value
def gift_card_sent(
self,
@@ -681,6 +712,7 @@ class WebhookPlugin(BasePlugin):
},
self.requestor,
)
+ return previous_value
def gift_card_metadata_updated(
self, gift_card: "GiftCard", previous_value: None
@@ -690,6 +722,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_metadata_updated_event(
WebhookEventAsyncType.GIFT_CARD_METADATA_UPDATED, gift_card
)
+ return previous_value
def gift_card_status_changed(
self, gift_card: "GiftCard", previous_value: None, webhooks=None
@@ -699,6 +732,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_gift_card_event(
WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED, gift_card, webhooks=webhooks
)
+ return previous_value
def _trigger_export_event(self, event_type: str, export: "ExportFile"):
if webhooks := get_webhooks_for_event(event_type):
@@ -727,6 +761,7 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.GIFT_CARD_EXPORT_COMPLETED,
export,
)
+ return previous_value
def _get_webhooks_for_order_events(
self,
@@ -755,7 +790,9 @@ class WebhookPlugin(BasePlugin):
filtered_webhooks.append(webhook)
return filtered_webhooks
- def order_created(self, order: "Order", previous_value: Any, webhooks=None) -> Any:
+ def order_created(
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_CREATED
@@ -772,6 +809,7 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def _trigger_menu_event(self, event_type, menu, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -790,11 +828,13 @@ class WebhookPlugin(BasePlugin):
if not self.active:
return previous_value
self._trigger_menu_event(WebhookEventAsyncType.MENU_CREATED, menu)
+ return previous_value
def menu_updated(self, menu: "Menu", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_menu_event(WebhookEventAsyncType.MENU_UPDATED, menu)
+ return previous_value
def menu_deleted(self, menu: "Menu", previous_value: None, webhooks=None) -> None:
if not self.active:
@@ -802,6 +842,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_menu_event(
WebhookEventAsyncType.MENU_DELETED, menu, webhooks=webhooks
)
+ return previous_value
def __trigger_menu_item_event(self, event_type, menu_item, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -829,6 +870,7 @@ class WebhookPlugin(BasePlugin):
self.__trigger_menu_item_event(
WebhookEventAsyncType.MENU_ITEM_CREATED, menu_item
)
+ return previous_value
def menu_item_updated(self, menu_item: "MenuItem", previous_value: None) -> None:
if not self.active:
@@ -836,6 +878,7 @@ class WebhookPlugin(BasePlugin):
self.__trigger_menu_item_event(
WebhookEventAsyncType.MENU_ITEM_UPDATED, menu_item
)
+ return previous_value
def menu_item_deleted(
self, menu_item: "MenuItem", previous_value: None, webhooks=None
@@ -845,10 +888,11 @@ class WebhookPlugin(BasePlugin):
self.__trigger_menu_item_event(
WebhookEventAsyncType.MENU_ITEM_DELETED, menu_item, webhooks=webhooks
)
+ return previous_value
def order_confirmed(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_CONFIRMED
@@ -865,10 +909,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def order_fully_paid(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_FULLY_PAID
@@ -885,8 +930,9 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
- def order_paid(self, order: "Order", previous_value: Any, webhooks=None) -> Any:
+ def order_paid(self, order: "Order", previous_value: None, webhooks=None) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_PAID
@@ -903,8 +949,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
- def order_refunded(self, order: "Order", previous_value: Any, webhooks=None) -> Any:
+ def order_refunded(
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_REFUNDED
@@ -921,10 +970,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def order_fully_refunded(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_FULLY_REFUNDED
@@ -941,8 +991,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
- def order_updated(self, order: "Order", previous_value: Any, webhooks=None) -> Any:
+ def order_updated(
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_UPDATED
@@ -959,8 +1012,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
- def order_expired(self, order: "Order", previous_value: Any, webhooks=None) -> Any:
+ def order_expired(
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_EXPIRED
@@ -977,13 +1033,14 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def sale_created(
self,
sale: "Promotion",
current_catalogue: defaultdict[str, set[str]],
- previous_value: Any,
- ) -> Any:
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.SALE_CREATED
@@ -1003,14 +1060,15 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=sale_data_generator,
)
+ return previous_value
def sale_updated(
self,
sale: "Promotion",
previous_catalogue: defaultdict[str, set[str]],
current_catalogue: defaultdict[str, set[str]],
- previous_value: Any,
- ) -> Any:
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.SALE_UPDATED
@@ -1030,14 +1088,15 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=sale_data_generator,
)
+ return previous_value
def sale_deleted(
self,
sale: "Promotion",
previous_catalogue: defaultdict[str, set[str]],
- previous_value: Any,
+ previous_value: None,
webhooks=None,
- ) -> Any:
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.SALE_DELETED
@@ -1056,14 +1115,15 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=sale_data_generator,
)
+ return previous_value
def sale_toggle(
self,
sale: "Promotion",
catalogue: defaultdict[str, set[str]],
- previous_value: Any,
+ previous_value: None,
webhooks=None,
- ):
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.SALE_TOGGLE
@@ -1082,6 +1142,7 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=sale_data_generator,
)
+ return previous_value
def _trigger_promotion_event(
self, event_type: str, promotion: "Promotion", webhooks=None
@@ -1099,57 +1160,62 @@ class WebhookPlugin(BasePlugin):
def promotion_created(
self,
promotion: "Promotion",
- previous_value: Any,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_event(
WebhookEventAsyncType.PROMOTION_CREATED, promotion
)
+ return previous_value
def promotion_updated(
self,
promotion: "Promotion",
- previous_value: Any,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_event(
WebhookEventAsyncType.PROMOTION_UPDATED, promotion
)
+ return previous_value
def promotion_deleted(
- self, promotion: "Promotion", previous_value: Any, webhooks=None
- ):
+ self, promotion: "Promotion", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_event(
WebhookEventAsyncType.PROMOTION_DELETED, promotion, webhooks=webhooks
)
+ return previous_value
def promotion_started(
self,
promotion: "Promotion",
- previous_value: Any,
+ previous_value: None,
webhooks=None,
- ):
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_event(
WebhookEventAsyncType.PROMOTION_STARTED, promotion, webhooks=webhooks
)
+ return previous_value
def promotion_ended(
self,
promotion: "Promotion",
- previous_value: Any,
+ previous_value: None,
webhooks=None,
- ):
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_event(
WebhookEventAsyncType.PROMOTION_ENDED, promotion, webhooks=webhooks
)
+ return previous_value
def _trigger_promotion_rule_event(
self, event_type: str, promotion_rule: "PromotionRule"
@@ -1173,43 +1239,46 @@ class WebhookPlugin(BasePlugin):
def promotion_rule_created(
self,
promotion_rule: "PromotionRule",
- previous_value: Any,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_rule_event(
WebhookEventAsyncType.PROMOTION_RULE_CREATED, promotion_rule
)
+ return previous_value
def promotion_rule_updated(
self,
promotion_rule: "PromotionRule",
- previous_value: Any,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_rule_event(
WebhookEventAsyncType.PROMOTION_RULE_UPDATED, promotion_rule
)
+ return previous_value
def promotion_rule_deleted(
self,
promotion_rule: "PromotionRule",
- previous_value: Any,
- ):
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
self._trigger_promotion_rule_event(
WebhookEventAsyncType.PROMOTION_RULE_DELETED, promotion_rule
)
+ return previous_value
def invoice_request(
self,
order: "Order",
invoice: "Invoice",
number: Optional[str],
- previous_value: Any,
- ) -> Any:
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.INVOICE_REQUESTED
@@ -1225,8 +1294,9 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=invoice_data_generator,
)
+ return previous_value
- def invoice_delete(self, invoice: "Invoice", previous_value: Any):
+ def invoice_delete(self, invoice: "Invoice", previous_value: None) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.INVOICE_DELETED
@@ -1242,8 +1312,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=invoice_data_generator,
)
+ return previous_value
- def invoice_sent(self, invoice: "Invoice", email: str, previous_value: Any) -> Any:
+ def invoice_sent(
+ self, invoice: "Invoice", email: str, previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.INVOICE_SENT
@@ -1259,10 +1332,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=invoice_data_generator,
)
+ return previous_value
def order_cancelled(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_CANCELLED
@@ -1279,10 +1353,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def order_fulfilled(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_FULFILLED
@@ -1299,10 +1374,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def order_metadata_updated(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_METADATA_UPDATED
@@ -1313,6 +1389,7 @@ class WebhookPlugin(BasePlugin):
webhooks=webhooks,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def _get_webhooks_for_order_bulk_created_event(
self, order_channel_slugs: set[str]
@@ -1336,7 +1413,7 @@ class WebhookPlugin(BasePlugin):
filtered_webhooks.append(webhook)
return filtered_webhooks
- def order_bulk_created(self, orders: list["Order"], previous_value: Any) -> Any:
+ def order_bulk_created(self, orders: list["Order"], previous_value: None) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_BULK_CREATED
@@ -1362,10 +1439,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=generate_bulk_order_payload,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def draft_order_created(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.DRAFT_ORDER_CREATED
@@ -1382,10 +1460,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def draft_order_updated(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.DRAFT_ORDER_UPDATED
@@ -1402,10 +1481,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def draft_order_deleted(
- self, order: "Order", previous_value: Any, webhooks=None
- ) -> Any:
+ self, order: "Order", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.DRAFT_ORDER_DELETED
@@ -1422,13 +1502,14 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=order_data_generator,
queue=settings.ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def fulfillment_created(
self,
fulfillment: "Fulfillment",
notify_customer: bool = True,
- previous_value: Optional[Any] = None,
- ):
+ previous_value: None = None,
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.FULFILLMENT_CREATED
@@ -1447,8 +1528,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=fulfillment_data_generator,
)
+ return previous_value
- def fulfillment_canceled(self, fulfillment: "Fulfillment", previous_value):
+ def fulfillment_canceled(
+ self, fulfillment: "Fulfillment", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.FULFILLMENT_CANCELED
@@ -1464,13 +1548,14 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=fulfillment_data_generator,
)
+ return previous_value
def fulfillment_approved(
self,
fulfillment: "Fulfillment",
notify_customer: Optional[bool] = True,
- previous_value: Optional[Any] = None,
- ):
+ previous_value: None = None,
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.FULFILLMENT_APPROVED
@@ -1489,15 +1574,21 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=fulfillment_data_generator,
)
+ return previous_value
- def fulfillment_metadata_updated(self, fulfillment: "Fulfillment", previous_value):
+ def fulfillment_metadata_updated(
+ self, fulfillment: "Fulfillment", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_metadata_updated_event(
WebhookEventAsyncType.FULFILLMENT_METADATA_UPDATED, fulfillment
)
+ return previous_value
- def tracking_number_updated(self, fulfillment: "Fulfillment", previous_value):
+ def tracking_number_updated(
+ self, fulfillment: "Fulfillment", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.FULFILLMENT_TRACKING_NUMBER_UPDATED
@@ -1510,8 +1601,9 @@ class WebhookPlugin(BasePlugin):
fulfillment,
self.requestor,
)
+ return previous_value
- def customer_created(self, customer: "User", previous_value: Any) -> Any:
+ def customer_created(self, customer: "User", previous_value: None) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.CUSTOMER_CREATED
@@ -1527,10 +1619,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=customer_data_generator,
)
+ return previous_value
def customer_updated(
- self, customer: "User", previous_value: Any, webhooks=None
- ) -> Any:
+ self, customer: "User", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.CUSTOMER_UPDATED
@@ -1546,10 +1639,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=customer_data_generator,
)
+ return previous_value
def customer_deleted(
- self, customer: "User", previous_value: Any, webhooks=None
- ) -> Any:
+ self, customer: "User", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.CUSTOMER_DELETED
@@ -1565,17 +1659,21 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=customer_data_generator,
)
+ return previous_value
def customer_metadata_updated(
- self, customer: "User", previous_value: Any, webhooks=None
- ) -> Any:
+ self, customer: "User", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_metadata_updated_event(
WebhookEventAsyncType.CUSTOMER_METADATA_UPDATED, customer, webhooks=webhooks
)
+ return previous_value
- def collection_created(self, collection: "Collection", previous_value: Any) -> Any:
+ def collection_created(
+ self, collection: "Collection", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.COLLECTION_CREATED
@@ -1591,8 +1689,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=collection_data_generator,
)
+ return previous_value
- def collection_updated(self, collection: "Collection", previous_value: Any) -> Any:
+ def collection_updated(
+ self, collection: "Collection", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.COLLECTION_UPDATED
@@ -1608,10 +1709,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=collection_data_generator,
)
+ return previous_value
def collection_deleted(
- self, collection: "Collection", previous_value: Any, webhooks=None
- ) -> Any:
+ self, collection: "Collection", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.COLLECTION_DELETED
@@ -1627,19 +1729,21 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=collection_data_generator,
)
+ return previous_value
def collection_metadata_updated(
- self, collection: "Collection", previous_value: Any
- ) -> Any:
+ self, collection: "Collection", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_metadata_updated_event(
WebhookEventAsyncType.COLLECTION_METADATA_UPDATED, collection
)
+ return previous_value
def product_created(
- self, product: "Product", previous_value: Any, webhooks=None
- ) -> Any:
+ self, product: "Product", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_CREATED
@@ -1655,10 +1759,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_data_generator,
)
+ return previous_value
def product_updated(
- self, product: "Product", previous_value: Any, webhooks=None
- ) -> Any:
+ self, product: "Product", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_UPDATED
@@ -1674,14 +1779,18 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_data_generator,
)
+ return previous_value
- def product_metadata_updated(self, product: "Product", previous_value: Any) -> Any:
+ def product_metadata_updated(
+ self, product: "Product", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_metadata_updated_event(
WebhookEventAsyncType.PRODUCT_METADATA_UPDATED, product
)
+ return previous_value
def product_export_completed(
self, export: "ExportFile", previous_value: None
@@ -1692,14 +1801,15 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.PRODUCT_EXPORT_COMPLETED,
export,
)
+ return previous_value
def product_deleted(
self,
product: "Product",
variants: list[int],
- previous_value: Any,
+ previous_value: None,
webhooks=None,
- ) -> Any:
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_DELETED
@@ -1715,8 +1825,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_data_generator,
)
+ return previous_value
- def product_media_created(self, media: "ProductMedia", previous_value: Any) -> Any:
+ def product_media_created(
+ self, media: "ProductMedia", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_MEDIA_CREATED
@@ -1730,8 +1843,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=media_data_generator,
)
+ return previous_value
- def product_media_updated(self, media: "ProductMedia", previous_value: Any) -> Any:
+ def product_media_updated(
+ self, media: "ProductMedia", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_MEDIA_UPDATED
@@ -1745,8 +1861,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=media_data_generator,
)
+ return previous_value
- def product_media_deleted(self, media: "ProductMedia", previous_value: Any) -> Any:
+ def product_media_deleted(
+ self, media: "ProductMedia", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_MEDIA_DELETED
@@ -1760,10 +1879,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=media_data_generator,
)
+ return previous_value
def product_variant_created(
- self, product_variant: "ProductVariant", previous_value: Any, webhooks=None
- ) -> Any:
+ self, product_variant: "ProductVariant", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_VARIANT_CREATED
@@ -1779,14 +1899,15 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_variant_data_generator,
)
+ return previous_value
def product_variant_updated(
self,
product_variant: "ProductVariant",
- previous_value: Any,
+ previous_value: None,
webhooks=None,
**kwargs,
- ) -> Any:
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED
@@ -1803,10 +1924,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=product_variant_data_generator,
**kwargs,
)
+ return previous_value
def product_variant_deleted(
- self, product_variant: "ProductVariant", previous_value: Any, webhooks=None
- ) -> Any:
+ self, product_variant: "ProductVariant", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DELETED
@@ -1822,19 +1944,21 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_variant_data_generator,
)
+ return previous_value
def product_variant_metadata_updated(
- self, product_variant: "ProductVariant", previous_value: Any
- ) -> Any:
+ self, product_variant: "ProductVariant", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_metadata_updated_event(
WebhookEventAsyncType.PRODUCT_VARIANT_METADATA_UPDATED, product_variant
)
+ return previous_value
def product_variant_out_of_stock(
- self, stock: "Stock", previous_value: Any, webhooks=None
- ) -> Any:
+ self, stock: "Stock", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_VARIANT_OUT_OF_STOCK
@@ -1850,10 +1974,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_variant_data_generator,
)
+ return previous_value
def product_variant_back_in_stock(
- self, stock: "Stock", previous_value: Any, webhooks=None
- ) -> Any:
+ self, stock: "Stock", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_VARIANT_BACK_IN_STOCK
@@ -1869,10 +1994,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_variant_data_generator,
)
+ return previous_value
def product_variant_stock_updated(
- self, stock: "Stock", previous_value: Any, webhooks=None
- ) -> Any:
+ self, stock: "Stock", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED
@@ -1888,10 +2014,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=product_variant_data_generator,
)
+ return previous_value
def checkout_created(
- self, checkout: "Checkout", previous_value: Any, webhooks=None
- ) -> Any:
+ self, checkout: "Checkout", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.CHECKOUT_CREATED
@@ -1908,10 +2035,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=checkout_data_generator,
queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def checkout_updated(
- self, checkout: "Checkout", previous_value: Any, webhooks=None
- ) -> Any:
+ self, checkout: "Checkout", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.CHECKOUT_UPDATED
@@ -1928,10 +2056,11 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=checkout_data_generator,
queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def checkout_fully_paid(
- self, checkout: "Checkout", previous_value: Any, webhooks=None
- ) -> Any:
+ self, checkout: "Checkout", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
@@ -1948,19 +2077,24 @@ class WebhookPlugin(BasePlugin):
legacy_data_generator=checkout_data_generator,
queue=settings.CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME,
)
+ return previous_value
def checkout_metadata_updated(
- self, checkout: "Checkout", previous_value: Any, webhooks=None
- ) -> Any:
+ self, checkout: "Checkout", previous_value: None, webhooks=None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_metadata_updated_event(
WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED, checkout, webhooks=webhooks
)
+ return previous_value
def notify(
- self, event: Union[NotifyEventType, str], payload_func: Callable, previous_value
- ) -> Any:
+ self,
+ event: Union[NotifyEventType, str],
+ payload_func: Callable,
+ previous_value: None,
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.NOTIFY_USER
@@ -1980,8 +2114,9 @@ class WebhookPlugin(BasePlugin):
"Webhook %s triggered for %s notify event.", event_type, event
)
self.trigger_webhooks_async(data, event_type, webhooks)
+ return previous_value
- def page_created(self, page: "Page", previous_value: Any) -> Any:
+ def page_created(self, page: "Page", previous_value: None) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PAGE_CREATED
@@ -1995,8 +2130,9 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=page_data_generator,
)
+ return previous_value
- def page_updated(self, page: "Page", previous_value: Any) -> Any:
+ def page_updated(self, page: "Page", previous_value: None) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PAGE_UPDATED
@@ -2010,8 +2146,9 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=page_data_generator,
)
+ return previous_value
- def page_deleted(self, page: "Page", previous_value: Any) -> Any:
+ def page_deleted(self, page: "Page", previous_value: None) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.PAGE_DELETED
@@ -2025,6 +2162,7 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=page_data_generator,
)
+ return previous_value
def _trigger_page_type_event(self, event_type, page_type):
if webhooks := get_webhooks_for_event(event_type):
@@ -2040,28 +2178,31 @@ class WebhookPlugin(BasePlugin):
payload, event_type, webhooks, page_type, self.requestor
)
- def page_type_created(self, page_type: "PageType", previous_value: Any) -> Any:
+ def page_type_created(self, page_type: "PageType", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_page_type_event(
WebhookEventAsyncType.PAGE_TYPE_CREATED, page_type
)
+ return previous_value
- def page_type_updated(self, page_type: "PageType", previous_value: Any) -> Any:
+ def page_type_updated(self, page_type: "PageType", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_page_type_event(
WebhookEventAsyncType.PAGE_TYPE_UPDATED, page_type
)
+ return previous_value
- def page_type_deleted(self, page_type: "PageType", previous_value: Any) -> Any:
+ def page_type_deleted(self, page_type: "PageType", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_page_type_event(
WebhookEventAsyncType.PAGE_TYPE_DELETED, page_type
)
+ return previous_value
- def _trigger_permission_group_event(self, event_type, group):
+ def _trigger_permission_group_event(self, event_type, group) -> None:
if webhooks := get_webhooks_for_event(event_type):
payload = self._serialize_payload(
{
@@ -2073,26 +2214,29 @@ class WebhookPlugin(BasePlugin):
payload, event_type, webhooks, group, self.requestor
)
- def permission_group_created(self, group: "Group", previous_value: Any) -> Any:
+ def permission_group_created(self, group: "Group", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_permission_group_event(
WebhookEventAsyncType.PERMISSION_GROUP_CREATED, group
)
+ return previous_value
- def permission_group_updated(self, group: "Group", previous_value: Any) -> Any:
+ def permission_group_updated(self, group: "Group", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_permission_group_event(
WebhookEventAsyncType.PERMISSION_GROUP_UPDATED, group
)
+ return previous_value
- def permission_group_deleted(self, group: "Group", previous_value: Any) -> Any:
+ def permission_group_deleted(self, group: "Group", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_permission_group_event(
WebhookEventAsyncType.PERMISSION_GROUP_DELETED, group
)
+ return previous_value
def _trigger_shipping_price_event(self, event_type, shipping_method, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -2120,6 +2264,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_shipping_price_event(
WebhookEventAsyncType.SHIPPING_PRICE_CREATED, shipping_method
)
+ return previous_value
def shipping_price_updated(
self, shipping_method: "ShippingMethod", previous_value: None
@@ -2129,6 +2274,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_shipping_price_event(
WebhookEventAsyncType.SHIPPING_PRICE_UPDATED, shipping_method
)
+ return previous_value
def shipping_price_deleted(
self, shipping_method: "ShippingMethod", previous_value: None, webhooks=None
@@ -2141,6 +2287,7 @@ class WebhookPlugin(BasePlugin):
shipping_method,
webhooks=webhooks,
)
+ return previous_value
def _trigger_shipping_zone_event(self, event_type, shipping_zone, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -2166,6 +2313,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_shipping_zone_event(
WebhookEventAsyncType.SHIPPING_ZONE_CREATED, shipping_zone
)
+ return previous_value
def shipping_zone_updated(
self, shipping_zone: "ShippingZone", previous_value: None
@@ -2175,6 +2323,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_shipping_zone_event(
WebhookEventAsyncType.SHIPPING_ZONE_UPDATED, shipping_zone
)
+ return previous_value
def shipping_zone_deleted(
self, shipping_zone: "ShippingZone", previous_value: None, webhooks=None
@@ -2186,15 +2335,17 @@ class WebhookPlugin(BasePlugin):
shipping_zone,
webhooks=webhooks,
)
+ return previous_value
def shipping_zone_metadata_updated(
- self, shipping_zone: "ShippingZone", previous_value: Any
- ) -> Any:
+ self, shipping_zone: "ShippingZone", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
self._trigger_metadata_updated_event(
WebhookEventAsyncType.SHIPPING_ZONE_METADATA_UPDATED, shipping_zone
)
+ return previous_value
def _trigger_staff_event(self, event_type, staff_user, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -2217,11 +2368,13 @@ class WebhookPlugin(BasePlugin):
if not self.active:
return previous_value
self._trigger_staff_event(WebhookEventAsyncType.STAFF_CREATED, staff_user)
+ return previous_value
def staff_updated(self, staff_user: "User", previous_value: None) -> None:
if not self.active:
return previous_value
self._trigger_staff_event(WebhookEventAsyncType.STAFF_UPDATED, staff_user)
+ return previous_value
def staff_deleted(
self, staff_user: "User", previous_value: None, webhooks=None
@@ -2231,6 +2384,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_staff_event(
WebhookEventAsyncType.STAFF_DELETED, staff_user, webhooks=webhooks
)
+ return previous_value
def staff_set_password_requested(
self,
@@ -2249,6 +2403,7 @@ class WebhookPlugin(BasePlugin):
token,
redirect_url,
)
+ return previous_value
def thumbnail_created(
self,
@@ -2267,8 +2422,11 @@ class WebhookPlugin(BasePlugin):
subscribable_object=thumbnail,
legacy_data_generator=thumbnail_data_generator,
)
+ return previous_value
- def translation_created(self, translation: "Translation", previous_value: Any):
+ def translation_created(
+ self, translation: "Translation", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.TRANSLATION_CREATED
@@ -2284,8 +2442,11 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=translation_data_generator,
)
+ return previous_value
- def translation_updated(self, translation: "Translation", previous_value: Any):
+ def translation_updated(
+ self, translation: "Translation", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.TRANSLATION_UPDATED
@@ -2301,6 +2462,7 @@ class WebhookPlugin(BasePlugin):
self.requestor,
legacy_data_generator=translation_data_generator,
)
+ return previous_value
def _trigger_warehouse_event(self, event_type, warehouse):
if webhooks := get_webhooks_for_event(event_type):
@@ -2324,6 +2486,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_warehouse_event(
WebhookEventAsyncType.WAREHOUSE_CREATED, warehouse
)
+ return previous_value
def warehouse_updated(self, warehouse: "Warehouse", previous_value: None) -> None:
if not self.active:
@@ -2331,6 +2494,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_warehouse_event(
WebhookEventAsyncType.WAREHOUSE_UPDATED, warehouse
)
+ return previous_value
def warehouse_deleted(self, warehouse: "Warehouse", previous_value: None) -> None:
if not self.active:
@@ -2338,6 +2502,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_warehouse_event(
WebhookEventAsyncType.WAREHOUSE_DELETED, warehouse
)
+ return previous_value
def warehouse_metadata_updated(
self, warehouse: "Warehouse", previous_value: None
@@ -2347,6 +2512,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_metadata_updated_event(
WebhookEventAsyncType.WAREHOUSE_METADATA_UPDATED, warehouse
)
+ return previous_value
def _trigger_voucher_event(self, event_type, voucher, code, webhooks=None):
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
@@ -2374,6 +2540,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_voucher_event(
WebhookEventAsyncType.VOUCHER_CREATED, voucher, code
)
+ return previous_value
def voucher_updated(
self, voucher: "Voucher", code: str, previous_value: None
@@ -2383,6 +2550,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_voucher_event(
WebhookEventAsyncType.VOUCHER_UPDATED, voucher, code
)
+ return previous_value
def voucher_deleted(
self, voucher: "Voucher", code: str, previous_value: None, webhooks=None
@@ -2392,8 +2560,11 @@ class WebhookPlugin(BasePlugin):
self._trigger_voucher_event(
WebhookEventAsyncType.VOUCHER_DELETED, voucher, code, webhooks=webhooks
)
+ return previous_value
- def _trigger_voucher_code_event(self, event_type, voucher_codes, webhooks=None):
+ def _trigger_voucher_code_event(
+ self, event_type, voucher_codes, webhooks=None
+ ) -> None:
if webhooks := self._get_webhooks_for_event(event_type, webhooks):
data = [
{
@@ -2415,6 +2586,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_voucher_code_event(
WebhookEventAsyncType.VOUCHER_CODES_CREATED, voucher_codes, webhooks
)
+ return previous_value
def voucher_codes_deleted(
self, voucher_codes: list["VoucherCode"], previous_value: None, webhooks=None
@@ -2424,6 +2596,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_voucher_code_event(
WebhookEventAsyncType.VOUCHER_CODES_DELETED, voucher_codes, webhooks
)
+ return previous_value
def voucher_metadata_updated(
self, voucher: "Voucher", previous_value: None
@@ -2433,6 +2606,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_metadata_updated_event(
WebhookEventAsyncType.VOUCHER_METADATA_UPDATED, voucher
)
+ return previous_value
def voucher_code_export_completed(
self, export: "ExportFile", previous_value: None
@@ -2443,6 +2617,7 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.VOUCHER_CODE_EXPORT_COMPLETED,
export,
)
+ return previous_value
def shop_metadata_updated(self, shop: "SiteSettings", previous_value: None) -> None:
if not self.active:
@@ -2450,12 +2625,16 @@ class WebhookPlugin(BasePlugin):
self._trigger_metadata_updated_event(
WebhookEventAsyncType.SHOP_METADATA_UPDATED, shop
)
+ return previous_value
- def event_delivery_retry(self, delivery: "EventDelivery", previous_value: Any):
+ def event_delivery_retry(
+ self, delivery: "EventDelivery", previous_value: None
+ ) -> None:
if not self.active:
return previous_value
delivery_update(delivery, status=EventDeliveryStatus.PENDING)
send_webhook_request_async.delay(delivery.pk)
+ return previous_value
def stored_payment_method_request_delete(
self,
@@ -2682,10 +2861,9 @@ class WebhookPlugin(BasePlugin):
self,
transaction_data: "TransactionActionData",
event_type: str,
- previous_value: Any,
) -> None:
if not self.active:
- return previous_value
+ return
if not transaction_data.transaction_app_owner:
create_failed_transaction_event(
@@ -2699,44 +2877,43 @@ class WebhookPlugin(BasePlugin):
"Transaction request skipped for %s. Missing relation to App.",
transaction_data.transaction.psp_reference,
)
- return None
+ return
if not transaction_data.event:
logger.warning(
"Transaction request skipped for %s. Missing relation to TransactionEvent.",
transaction_data.transaction.psp_reference,
)
- return None
+ return
trigger_transaction_request(transaction_data, event_type, self.requestor)
- return None
def transaction_charge_requested(
self, transaction_data: "TransactionActionData", previous_value: Any
- ):
- return self._request_transaction_action(
+ ) -> None:
+ self._request_transaction_action(
transaction_data,
WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
- previous_value,
)
+ return previous_value
def transaction_refund_requested(
self, transaction_data: "TransactionActionData", previous_value: Any
- ):
- return self._request_transaction_action(
+ ) -> None:
+ self._request_transaction_action(
transaction_data,
WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
- previous_value,
)
+ return previous_value
def transaction_cancelation_requested(
self, transaction_data: "TransactionActionData", previous_value: Any
- ):
- return self._request_transaction_action(
+ ) -> None:
+ self._request_transaction_action(
transaction_data,
WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED,
- previous_value,
)
+ return previous_value
def __run_payment_webhook(
self,
@@ -3041,6 +3218,7 @@ class WebhookPlugin(BasePlugin):
self._trigger_metadata_updated_event(
WebhookEventAsyncType.TRANSACTION_ITEM_METADATA_UPDATED, transaction_item
)
+ return previous_value
def authorize_payment(
self, payment_information: "PaymentData", previous_value, **kwargs
@@ -3180,18 +3358,17 @@ class WebhookPlugin(BasePlugin):
checkout_info.checkout,
pregenerated_subscription_payloads=pregenerated_subscription_payloads,
)
- else:
- return trigger_all_webhooks_sync(
- event_type,
- lambda: generate_checkout_payload_for_tax_calculation(
- checkout_info,
- lines,
- ),
- parse_tax_data,
- checkout_info.checkout,
- self.requestor,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
- )
+ return trigger_all_webhooks_sync(
+ event_type,
+ lambda: generate_checkout_payload_for_tax_calculation(
+ checkout_info,
+ lines,
+ ),
+ parse_tax_data,
+ checkout_info.checkout,
+ self.requestor,
+ pregenerated_subscription_payloads=pregenerated_subscription_payloads,
+ )
def get_taxes_for_order(
self, order: "Order", app_identifier, previous_value
@@ -3204,14 +3381,13 @@ class WebhookPlugin(BasePlugin):
lambda: generate_order_payload_for_tax_calculation(order),
order,
)
- else:
- return trigger_all_webhooks_sync(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES,
- lambda: generate_order_payload_for_tax_calculation(order),
- parse_tax_data,
- order,
- self.requestor,
- )
+ return trigger_all_webhooks_sync(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ lambda: generate_order_payload_for_tax_calculation(order),
+ parse_tax_data,
+ order,
+ self.requestor,
+ )
def get_shipping_methods_for_checkout(
self, checkout: "Checkout", previous_value: Any
diff --git a/saleor/product/migrations/0183_calculate_discounted_prices.py b/saleor/product/migrations/0183_calculate_discounted_prices.py
index 598bcd7e54..839aa694fc 100644
--- a/saleor/product/migrations/0183_calculate_discounted_prices.py
+++ b/saleor/product/migrations/0183_calculate_discounted_prices.py
@@ -370,7 +370,7 @@ def get_product_discounts(
def get_discount(sale, sale_channel_listing):
if not sale_channel_listing:
- return
+ return None
if sale.type == "fixed":
discount_amount = Money(
sale_channel_listing.discount_value, sale_channel_listing.currency
@@ -382,6 +382,7 @@ def get_discount(sale, sale_channel_listing):
percentage=sale_channel_listing.discount_value,
rounding=ROUND_HALF_UP,
)
+ return None
class Migration(migrations.Migration):
diff --git a/saleor/product/product_images.py b/saleor/product/product_images.py
index 9cded409f5..cba4ec0dd5 100644
--- a/saleor/product/product_images.py
+++ b/saleor/product/product_images.py
@@ -14,7 +14,9 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-def get_product_image_thumbnail_url(product_media: Optional["ProductMedia"], size: int):
+def get_product_image_thumbnail_url(
+ product_media: Optional["ProductMedia"], size: int
+) -> str:
"""Return product media image thumbnail or placeholder if there is no image."""
size = get_thumbnail_size(size)
if not product_media or not product_media.image:
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index c5a3fe4026..072019a175 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -83,8 +83,7 @@ def _calculate_product_price_with_taxes(
# support for apps will be added in the future.
if tax_calculation_strategy == TaxCalculationStrategy.FLAT_RATES:
return calculate_flat_rate_tax(price, tax_rate, prices_entered_with_tax)
- else:
- return TaxedMoney(price, price)
+ return TaxedMoney(price, price)
def get_product_availability(
diff --git a/saleor/site/patch_sites.py b/saleor/site/patch_sites.py
index 6e322253fb..523c81b425 100644
--- a/saleor/site/patch_sites.py
+++ b/saleor/site/patch_sites.py
@@ -33,7 +33,7 @@ def new_get_current(self, request=None):
)
THREADED_SITE_CACHE[site_id] = site
return THREADED_SITE_CACHE[site_id]
- elif request:
+ if request:
host = request.get_host()
try:
# First attempt to look up the site by host with or without port.
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 5636e80fc4..1a7a0d37c0 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1183,10 +1183,9 @@ def user_checkout_with_items_for_cc(user_checkout_for_cc, product_list):
def user_checkouts(request, user_checkout_with_items, user_checkout_with_items_for_cc):
if request.param == "regular":
return user_checkout_with_items
- elif request.param == "click_and_collect":
+ if request.param == "click_and_collect":
return user_checkout_with_items_for_cc
- else:
- raise ValueError("Internal test error")
+ raise ValueError("Internal test error")
@pytest.fixture
@@ -5790,6 +5789,7 @@ def delivery_method(request, warehouse_for_cc, shipping_method):
return warehouse_for_cc
if request.param == "shipping_method":
return shipping_method
+ return None
@pytest.fixture
@@ -6926,6 +6926,7 @@ def setup_mock_for_cache():
{key: {"value": new_value, "ttl": current_data["ttl"]}}
)
return new_value
+ return None
mocked_get_cache = MagicMock()
mocked_set_cache = MagicMock()
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index f539cf7fc8..8183e06479 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -19,9 +19,8 @@ def lazy_re_compile(regex, flags=0):
# Compile the regex if it was not passed pre-compiled.
if isinstance(regex, str):
return re.compile(regex, flags)
- else:
- assert not flags, "flags must be empty if regex is passed pre-compiled"
- return regex
+ assert not flags, "flags must be empty if regex is passed pre-compiled"
+ return regex
return SimpleLazyObject(_compile)
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 62f3441b99..6387729396 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -243,7 +243,7 @@ def _create_allocations(
stocks_allocations: dict,
stocks_reservations: dict,
insufficient_stock: list[InsufficientStockData],
-):
+) -> tuple[list[InsufficientStockData], list[Any]]:
quantity = line_info.quantity
quantity_allocated = 0
allocations = []
@@ -277,6 +277,7 @@ def _create_allocations(
)
)
return insufficient_stock, []
+ return [], allocations
def deallocate_stock(
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 8329cd3683..45ce855702 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -1135,6 +1135,7 @@ def _generate_sample_order_payload(event_name):
if order:
anonymized_order = anonymize_order(order)
return generate_order_payload(anonymized_order)
+ return None
@allow_writer()
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index 15a926db26..faad3de3ae 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -103,9 +103,9 @@ def serialize_checkout_lines_for_tax_calculation(
def serialize_product_attributes(product: "Product") -> list[dict]:
data = []
- def _prepare_reference(attribute, attr_value):
+ def _prepare_reference(attribute, attr_value) -> None | str:
if attribute.input_type != AttributeInputType.REFERENCE:
- return
+ return None
if attribute.entity_type == AttributeEntityType.PAGE:
reference_pk = attr_value.reference_page_id
elif attribute.entity_type == AttributeEntityType.PRODUCT:
@@ -171,9 +171,9 @@ def serialize_product_attributes(product: "Product") -> list[dict]:
def serialize_variant_attributes(variant: "ProductVariant") -> list[dict]:
data = []
- def _prepare_reference(attribute, attr_value):
+ def _prepare_reference(attribute, attr_value) -> None | str:
if attribute.input_type != AttributeInputType.REFERENCE:
- return
+ return None
if attribute.entity_type == AttributeEntityType.PAGE:
reference_pk = attr_value.reference_page_id
elif attribute.entity_type == AttributeEntityType.PRODUCT:
diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.py
index 5ed3b948fa..3dbd2d8f6b 100644
--- a/saleor/webhook/transport/asynchronous/transport.py
+++ b/saleor/webhook/transport/asynchronous/transport.py
@@ -258,10 +258,10 @@ def trigger_webhooks_async(
retry_kwargs={"max_retries": 5},
)
@allow_writer()
-def send_webhook_request_async(self, event_delivery_id):
+def send_webhook_request_async(self, event_delivery_id) -> None:
delivery = get_delivery_for_webhook(event_delivery_id)
if not delivery:
- return None
+ return
webhook = delivery.webhook
domain = get_domain()
diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.py
index 7760722ad2..82861c8d9c 100644
--- a/saleor/webhook/transport/shipping.py
+++ b/saleor/webhook/transport/shipping.py
@@ -23,14 +23,14 @@ from .synchronous.transport import trigger_webhook_sync_if_not_cached
logger = logging.getLogger(__name__)
-def to_shipping_app_id(app: "App", shipping_method_id: str) -> "str":
+def to_shipping_app_id(app: App, shipping_method_id: str) -> str:
app_identifier = app.identifier or app.id
return base64.b64encode(
str.encode(f"{APP_ID_PREFIX}:{app_identifier}:{shipping_method_id}")
).decode("utf-8")
-def convert_to_app_id_with_identifier(shipping_app_id: str):
+def convert_to_app_id_with_identifier(shipping_app_id: str) -> None | str:
"""Prepare the shipping_app_id in format `app:<app-identifier>/method_id>`.
The format of shipping_app_id has been changes so we need to support both of them.
@@ -40,7 +40,7 @@ def convert_to_app_id_with_identifier(shipping_app_id: str):
decoded_id = base64.b64decode(shipping_app_id).decode()
splitted_id = decoded_id.split(":")
if len(splitted_id) != 3:
- return
+ return None
try:
app_id = int(splitted_id[1])
except (TypeError, ValueError):
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index 450c0e2b85..5610507412 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -59,14 +59,14 @@ logger = logging.getLogger(__name__)
retry_kwargs={"max_retries": 5},
)
@allow_writer()
-def handle_transaction_request_task(self, delivery_id, request_event_id):
+def handle_transaction_request_task(self, delivery_id, request_event_id) -> None:
request_event = TransactionEvent.objects.filter(id=request_event_id).first()
if not request_event:
logger.error(
"Cannot find the request event with id: %s for transaction-request webhook.",
request_event_id,
)
- return None
+ return
delivery = get_delivery_for_webhook(delivery_id)
if not delivery:
recalculate_refundable_for_checkout(request_event.transaction, request_event)
@@ -74,7 +74,7 @@ def handle_transaction_request_task(self, delivery_id, request_event_id):
"Cannot find the delivery with id: %s for transaction-request webhook.",
delivery_id,
)
- return None
+ return
attempt = create_attempt(delivery, self.request.id)
response, response_data = _send_webhook_request_sync(delivery, attempt=attempt)
if response.response_status_code and response.response_status_code >= 500:
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index c90f953e84..9b3386057f 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -472,7 +472,7 @@ def save_unsuccessful_delivery_attempt(attempt: "EventDeliveryAttempt"):
def trigger_transaction_request(
transaction_data: "TransactionActionData", event_type: str, requestor
-):
+) -> None:
from ..payloads import generate_transaction_action_request_payload
from .synchronous.transport import (
create_delivery_for_subscription_sync_event,
@@ -490,7 +490,7 @@ def trigger_transaction_request(
recalculate_refundable_for_checkout(
transaction_data.transaction, transaction_data.event
)
- return None
+ return
webhook = get_webhooks_for_event(
event_type, apps_ids=[transaction_data.transaction_app_owner.pk]
).first()
@@ -502,7 +502,7 @@ def trigger_transaction_request(
recalculate_refundable_for_checkout(
transaction_data.transaction, transaction_data.event
)
- return None
+ return
if webhook.subscription_query:
delivery = None
@@ -522,7 +522,7 @@ def trigger_transaction_request(
recalculate_refundable_for_checkout(
transaction_data.transaction, transaction_data.event
)
- return None
+ return
else:
payload = generate_transaction_action_request_payload(
transaction_data, requestor
@@ -542,7 +542,6 @@ def trigger_transaction_request(
delivery.id,
transaction_data.event.id,
)
- return None
def parse_tax_data(